7f937ddbf5d98c583ac13c6db652510b5064f066
[readifood.git] / lib / functions.php
1 <?php
2
3   function parse_parameters($parameters) {
4     $name = null;
5     $id = null;
6     $args = array();
7
8     if (count($parameters) > 0) {
9       $name = array_shift($parameters);
10
11       /* Recall that we shifted. */
12       if (count($parameters) > 0) {
13         if (is_numeric($parameters[0])) {
14           $id = array_shift($parameters);
15         }
16       }
17
18       $args = $parameters;
19     }
20
21     return array($name, $id, $args);
22   }
23
24   function pagination() {
25     $first_page = 1;
26     $per_page = $GLOBALS['default_page_size'];
27
28     parse_str($_SERVER['QUERY_STRING'], $params);
29     if (array_key_exists('page', $params)) if (is_numeric($params['page'])) $first_page = $params['page'];
30     if (array_key_exists('size', $params)) if (is_numeric($params['size'])) $per_page = $params['size'];
31
32     return array($first_page, $per_page);
33   }
34
35   function page_link($alt, $n, $cur, $max, $size) {
36     $links = array();
37     if ($n < 1 || $n == $cur || $n > $max) return $alt;
38     $params = array('page' => $n);
39     if ($size != $GLOBALS['default_page_size']) $params['size'] = $size;
40     $url = http_build_query($params);
41     return "<a href=\"?$url\">$alt</a> ";
42   }
43
44   function show_pagination($pager, $n = 5) {
45     if (! $pager->haveToPaginate()) return;
46
47     list($first_page, $per_page) = pagination();
48
49     $pages = ceil($pager->getNbResults() / $per_page);
50
51     /* Highlight the fact we skipped some pages. */
52     $linked_pages = $pager->getLinks($n);
53     $first_link = $linked_pages[0];
54     $last_link = end($linked_pages);
55
56     $links = array();
57     $links[] = page_link('First', 1, $first_page, $pages, $per_page);
58     $links[] = page_link('Previous', $first_page - 1, $first_page, $pages, $per_page);
59     if ($first_link > 1) $links[] = page_link('...', $first_page, $pages, $per_page);
60     foreach ($linked_pages as $link) $links[] = page_link($link, $link, $first_page, $pages, $per_page);
61     if ($last_link < $pages) $links[] = page_link('...', $first_page, $pages, $per_page);
62     $links[] = page_link('Next', $first_page + 1, $first_page, $pages, $per_page);
63     $links[] = page_link('Last', $pages, $first_page, $pages, $per_page);
64
65     echo "<p>Page: ";
66     echo implode(' / ', $links);
67     echo "</p>\n";
68   }
69
70   function get_city_by_name($name, $postcode_area = null, $verbose = true) {
71     $q = new CityQuery;
72
73     $m = $q->filterByName(urldecode($name));
74     if (isset($postcode_area)) {
75       $m->filterByPostcodeArea($postcode_area);
76     }
77     $cities = $m->find();
78
79     switch ($m->count()) {
80       case 0:
81         if ($verbose) echo "<p>No such city!</p>\n";
82         return null;
83
84       case 1:
85         return $cities[0];
86
87       default:
88         if ($verbose) echo "<p>Can't identify city uniquely.</p>!\n";
89         return null;
90     }
91   }
92
93   function get_city_by_id($id, $verbose = true) {
94     $q = new CityQuery;
95     $city = $q->findOneById($id);
96
97     if (! $q->count()) {
98       if ($verbose) echo "<p>No such city!</p>\n";
99       return null;
100     }
101
102     return $city;
103   }
104
105   function get_area_by_name($name, $verbose = true) {
106     $q = new AreaQuery;
107     $areas = $q->filterByName(urldecode($name))->find();
108
109     switch ($q->count()) {
110       case 0:
111         if ($verbose) echo "<p>No such area!</p>\n";
112         return null;
113
114       case 1:
115         return $areas[0];
116
117       default:
118         if ($verbose) echo "<p>Can't identify area uniquely.</p>!\n";
119         return null;
120     }
121   }
122
123   function get_area_by_id($id, $verbose = true) {
124     $q = new AreaQuery;
125     $area = $q->findOneById($id);
126
127     if (! $q->count()) {
128       if ($verbose) echo "<p>No such area!</p>\n";
129       return null;
130     }
131
132     return $area;
133   }
134
135   function get_area_city($area) {
136     $q = new CityQuery;
137     return $q->findOneById($area->getCityId());
138   }
139
140   function get_contact_by_name($name, $verbose = true) {
141     $q = new ContactQuery;
142     $contact = $q->filterByDisplayname(urldecode($name))->find();
143
144     switch ($q->count()) {
145       case 0:
146         if ($verbose) echo "<p>No such contact!</p>\n";
147         return null;
148
149       case 1:
150         return $contacts[0];
151
152       default:
153         if ($verbose) echo "<p>Can't identify contact uniquely.</p>!\n";
154         return null;
155     }
156   }
157
158   function get_contact_by_id($id, $verbose = true) {
159     $q = new ContactQuery;
160     $contact = $q->findOneById($id);
161
162     if (! $q->count()) {
163       if ($verbose) echo "<p>No such contact!</p>\n";
164       return null;
165     }
166
167     return $contact;
168   }
169
170   function get_hub_by_name($name, $verbose = true) {
171     $q = new HubQuery;
172     $hubs = $q->filterByDisplayname(urldecode($name))->find();
173
174     switch ($q->count()) {
175       case 0:
176         if ($verbose) echo "<p>No such hub!</p>\n";
177         return null;
178
179       case 1:
180         return $hubs[0];
181
182       default:
183         if ($verbose) echo "<p>Can't identify hub uniquely.</p>!\n";
184         return null;
185     }
186   }
187
188   function get_hub_by_id($id, $verbose = true) {
189     $q = new HubQuery;
190     $hub = $q->findOneById($id);
191
192     if (! $q->count()) {
193       if ($verbose) echo "<p>No such hub!</p>\n";
194       return null;
195     }
196
197     return $hub;
198   }
199
200   function get_donation_by_id($id, $verbose = true) {
201     $q = new DonationQuery;
202     $donation = $q->findOneById($id);
203
204     if (! $q->count()) {
205       if ($verbose) echo "<p>No such donation!</p>\n";
206       return null;
207     }
208
209     return $donation;
210   }
211
212   function get_order_by_id($id, $verbose = true) {
213     $q = new OrderQuery;
214     $order = $q->findOneById($id);
215
216     if (! $q->count()) {
217       if ($verbose) echo "<p>No such order!</p>\n";
218       return null;
219     }
220
221     return $order;
222   }
223
224   function get_order_ids_by_state($state_mask) {
225     $order_ids = array();
226     $dbh = Propel::getConnection();
227     $sth = $dbh->prepare("select * from OrderState o where updated=(select max(updated) from OrderState where order_id=o.order_id) and state & $state_mask");
228     $sth->execute();
229     $order_states = OrderStatePeer::populateObjects($sth);
230     foreach ($order_states as $order_state) $order_ids[] = $order_state->getOrderId();
231     return $order_ids;
232   }
233
234   function get_beneficiary_orders($contact, $state_mask = null) {
235     $q = new OrderQuery;
236     $q->filterByBeneficiaryId($contact->getId());
237     if ($state_mask) $q->filterById(get_order_ids_by_state($state_mask));
238     return $q->orderByDate()->find();
239   }
240
241   function get_requester_orders($contact, $state_mask = null) {
242     $q = new OrderQuery;
243     $q->filterByRequesterId($contact->getId());
244     if ($state_mask) $q->filterById(get_order_ids_by_state($state_mask));
245     return $q->orderByDate()->find();
246   }
247
248   function get_contact_orders($contact, $state_mask = null) {
249     $q = new OrderQuery;
250     $q->filterByBeneficiaryId($contact->getId())->_or()->filterByRequesterId($contact->getId());
251     if ($state_mask) $q->filterById(get_order_ids_by_state($state_mask));
252     return $q->orderByDate()->find();
253   }
254
255   function get_user_by_contact_id($id, $verbose = true) {
256     $q = new UserQuery;
257     $user = $q->findOneByContactId($id);
258
259     if (! $q->count()) {
260       if ($verbose) echo "<p>No such user!</p>\n";
261       return null;
262     }
263
264     return $user;
265   }
266
267   function get_city_displayname($city) {
268     return $city->getName() . ", " . $city->getPostcodeArea();
269   }
270
271   function get_area_displayname($area) {
272     return $area->getName() . " in " . get_city_displayname(CityQuery::create()->findOneById($area->getCityId()));
273   }
274
275   function get_donation_displayname($donation) {
276     return sprintf("%0.2fkg on %s", $donation->getQuantity() / 1000, $donation->getDate());
277   }
278
279   function get_order_parcel_string($order) {
280     global $parcel_sizes, $parcel_contents;
281
282     $parcel_size = null;
283     for ($i = 0 ; $i < count($parcel_sizes); $i++) {
284       if ($order->getParcel() & (1 << $i)) {
285         $parcel_size = $parcel_sizes[$i];
286         break;
287       }
288     }
289
290     $selected = array();
291     for ($i = count($parcel_sizes); $i < count($parcel_contents); $i++) {
292       if ($order->getParcel() & (1 << $i)) $selected[] = $parcel_contents[$i];
293     }
294
295     $ret = implode(": ", array($parcel_size, implode(", ", $selected)));
296     $ret = preg_replace('/^: /', '', $ret);
297     $ret = preg_replace('/: $/', '', $ret);
298
299     return $ret;
300   }
301
302   function get_order_displayname($order) {
303     return sprintf("<span class=\"small\">%s</span> on %s", get_order_parcel_string($order), $order->getDate());
304   }
305
306   function get_order_state_string($order_state = null) {
307     global $states;
308
309     if (is_null($order_state)) return null;
310
311     for ($i = 0; $i < count($states); $i++) {
312       if ($order_state->getState() & (1 << $i)) {
313         return $states[$i];
314       }
315     }
316
317     return "unknown";
318   }
319
320   function get_order_state($order) {
321     $q = new OrderStateQuery();
322     return $q->filterByOrderId($order->getId())->orderByUpdated('desc')->findOne();
323   }
324
325   function get_order_summary($order) {
326     $ret = "Order ";
327     $order_state = get_order_state($order);
328     if ($order_state) $ret = "<strong>" . ucfirst(get_order_state_string($order_state)) . "</strong> order ";
329     $ret .= $order->getStrongLink($order->getId()) . ": " . get_order_displayname($order);
330
331     if (check_admin(1)) $ret .= " " . $order->getDeleteLink();
332
333     /* XXX: Should pull from query. */
334     $q = new ContactQuery;
335     $contact = $q->findOneById($order->getRequesterId());
336     if ($contact) {
337       $ret .= " referred by " . $contact->getLink();
338       $area = get_contact_area($contact);
339       if ($area) $ret .= " in " . $area->getLink();
340     }
341
342     $q = new ContactQuery;
343     $contact = $q->findOneById($order->getBeneficiaryId());
344     if ($contact) {
345       $ret .= " for " . $contact->getLink();
346       $area = get_contact_area($contact);
347       if ($area) $ret .= " in " . $area->getLink();
348     }
349
350     if ($order->getHubId()) {
351       $q = new HubQuery;
352       $hub = $q->findOneById($order->getHubId());
353       if ($hub) $ret .= " to hub " . $hub->getLink();
354       $area = get_hub_area($hub);
355       if ($area) $ret .= " in " . $area->getLink();
356     }
357
358     return $ret;
359   }
360
361   function get_address_area($address) {
362     $q = new AreaQuery;
363     return $q->findOneById($address->getAreaId());
364   }
365
366   function get_address_map_link($address) {
367     $postcode = trim($address->getPostcode());
368     if ($postcode) {
369       # mrt=loc specifies a location search.
370       $map = "maps.google.co.uk/maps?q=" . urlencode($postcode) . "&mrt=loc";
371       $url = "http://$map";
372       # output=embed allows display in an iframe.
373       # iwloc=near hides the popup window for the embedded view.
374       $embed = $GLOBALS['http'] . "://$map&output=embed&iwloc=near";
375       $html = " ";
376       $html .= get_small_link_with_id("map", "Map", $url);
377       $html .= "<script>\n  $(function() {\n";
378       $html .= "    var x = 0;\n";
379       $html .= "    var y = 0;\n";
380       $html .= "    var loaded = false;\n";
381       $html .= "    $(\"#map\").hover(function(e) {\n";
382       $html .= "      x = $(this).outerWidth();\n";
383       $html .= "      y = $(this).outerHeight() / 2;\n";
384       $html .= "      $(\"#popup\").css(\"left\", e.pageX + x).css(\"top\", e.pageY + y);;\n";
385       $html .= "      $(\"#popup\").show();\n";
386       $html .= "      if (! loaded) {\n";
387       $html .= "        $(\"#popup\").html(\"<iframe width='100%' height='100%' src='$embed'></iframe>\");\n";
388       $html .= "        loaded = true;\n";
389       $html .= "      }\n";
390       $html .= "    },function() {\n";
391       $html .= "      $(\"#popup\").hide();\n";
392       $html .= "    })\n";
393       $html .= "  });</script>";
394       return $html;
395     }
396   }
397
398   function get_contact_address($contact) {
399     $q = new AddressQuery;
400     return $q->findOneById($contact->getAddressId());
401   }
402
403   function get_contact_area($contact) {
404     $address = get_contact_address($contact);
405     if (! $address) return null;
406
407     return get_address_area($address);
408   }
409
410   function get_contact_city($contact) {
411     $area = get_contact_area($contact);
412     if (! $area) return null;
413
414     return get_area_city($area);
415   }
416
417   /* Parcel strings are the same so this can work. */
418   function get_contact_parcel_string($contact) {
419     return get_order_parcel_string($contact);
420   }
421
422   /* Hub and Contact are similar enough that this can work. */
423   function get_hub_address($hub) {
424     return get_contact_address($hub);
425   }
426
427   /* Hub and Contact are similar enough that this can work. */
428   function get_hub_area($hub) {
429     return get_contact_area($hub);
430   }
431
432   /* Hub and Contact are similar enough that this can work. */
433   function get_hub_city($hub) {
434     return get_contact_city($hub);
435   }
436
437   function get_area_contacts($area_id = null, $role = null) {
438     $q = new ContactQuery;
439     if (isset($area_id)) $q->useAddressQuery()->filterByAreaId($area_id)->endUse();
440     if (isset($role)) $q->where("role & $role");
441     return $q->orderByDisplayname()->find();
442   }
443
444   function get_area_requesters($area_id = null) {
445     return get_area_contacts($area_id, $GLOBALS['ROLE_REQUESTER']);
446   }
447
448   function get_area_beneficiaries($area_id = null) {
449     return get_area_contacts($area_id, $GLOBALS['ROLE_BENEFICIARY']);
450   }
451
452   function get_area_donors($area_id = null) {
453     return get_area_contacts($area_id, $GLOBALS['ROLE_DONOR']);
454   }
455
456   function get_city_contacts($city_id = null, $role = null) {
457     /* XXX */
458     $area_ids = array();
459     $areas = get_city_areas($city_id);
460     foreach ($areas as $area) $area_ids[] = $area->getId();
461     return get_area_contacts($area_ids, $role);
462   }
463
464   function get_city_requesters($city_id = null) {
465     return get_city_contacts($city_id, $GLOBALS['ROLE_REQUESTER']);
466   }
467
468   function get_city_beneficiaries($city_id = null) {
469     return get_city_contacts($city_id, $GLOBALS['ROLE_BENEFICIARY']);
470   }
471
472   function get_city_donors($city_id = null) {
473     return get_city_contacts($city_id, $GLOBALS['ROLE_DONOR']);
474   }
475
476   function get_city_drivers($city_id = null) {
477     return get_city_contacts($city_id, $GLOBALS['ROLE_DRIVER']);
478   }
479
480   function get_role_string($object, $roles) {
481     $role = $object->getRole();
482
483     $selected = array();
484
485     for ($i =0; $i < count($roles); $i++) {
486       if ($role & (1 << $i)) $selected[] = $roles[$i];
487     }
488
489     return implode(", ", $selected);
490   }
491
492   function get_contact_role_string($contact) {
493     return get_role_string($contact, $GLOBALS['contact_roles']);
494   }
495
496   function get_hub_role_string($hub) {
497     return get_role_string($hub, $GLOBALS['hub_roles']);
498   }
499
500   function show_role_form($role, $roles) {
501     for ($i = 0; $i < count($roles); $i++) {
502       echo " <input type=\"checkbox\" id=\"role_$i\" name=\"role_$i\"";
503       if ($role & (1 << $i)) echo " checked";
504       echo "><label for=\"role_$i\">$roles[$i]</label>\n";
505     }
506   }
507
508   function get_area_hubs($area_id = null) {
509     $q = new HubQuery;
510     if (isset($area_id)) $q->useAddressQuery()->filterByAreaId($area_id)->endUse();
511     return $q->orderByDisplayname()->find();
512   }
513
514   function get_city_areas($city_id = null) {
515     $q = new AreaQuery;
516     $q->join("City")->orderBy("City.Name");
517     if (isset($city_id)) $q->filterByCityId($city_id);
518     return $q->orderByName()->find();
519   }
520
521   function get_city_areas_with_contacts($city_id = null, $role = null) {
522     $q = new AreaQuery;
523     $q->join("City")->orderBy("City.Name");
524     if (isset($city_id)) $q->filterByCityId($city_id);
525     /* XXX */
526     if (isset($role)) $q->useAddressQuery()->join("Contact")->useContactQuery()->where("role & $role")->endUse()->endUse();
527     else $q->useAddressQuery()->join("Contact")->endUse();
528     return $q->orderByName()->distinct()->find();
529   }
530
531   function get_city_areas_with_hubs($city_id = null) {
532     $q = new AreaQuery;
533     $q->join("City")->orderBy("City.Name");
534     if (isset($city_id)) $q->filterByCityId($city_id);
535     $q->useAddressQuery()->join("Hub")->endUse();
536     return $q->orderByName()->distinct()->find();
537   }
538
539   function get_city_hubs($city_id = null) {
540     $q = new HubQuery;
541     if (isset($city_id)) $q->useAddressQuery()->useAreaQuery()->filterByCityId($city_id)->endUse()->endUse();
542     return $q->orderByDisplayname()->find();
543   }
544
545   function iso8601_to_ymd($iso8601) {
546     return split("-", $iso8601);
547   }
548
549   function ymd_to_iso8601($name) {
550     $y = $_POST[$name . "_y"];
551     if (! $y) return null;
552     $m = $_POST[$name . "_m"];
553     if (! $m) $m = 1;
554     $d = $_POST[$name . "_d"];
555     if (! $d) $d = 1;
556     return sprintf("%04d-%02d-%02d", $y, $m, $d);
557   }
558
559   function show_date_form($name, $date = null) {
560     if (! isset($date)) $date = date('Y-m-d', time());
561     datepicker($name, $date);
562   }
563
564   function validate_postcode($postcode, &$outward = null, &$inward = null) {
565     /*
566       Valid postcode formats (BS7666):
567
568         AN NLL
569         ABN NLL
570         ANN NLL
571         ABNN NLL
572         ABND NLL
573         ANC NLL
574
575       Where N is a number; A is a letter not including Q, V, X;
576       B is a letter not including I, J, Z; C is a letter from the set
577       ABCDEFGHJKSTUW; D is a letter from the set ABEHMNPRVWXY;
578       L is a letter from the set ABDEFGHJLNPQRSTUWXYZ.
579
580       The postcode GIR 0AA is also valid.
581     */
582     $outward = $inward = null;
583
584     /* Treat blank as valid for convenience. */
585     $postcode = trim($postcode);
586     if (! $postcode) return true;
587
588     $A = '[ABCDEFGHIJKLMNOPRSTUWYZ]';
589     $B = '[ABCDEFGHKLMNOPQRSTUVWXY]';
590     $C = '[ABCDEFGHJKSTUW]';
591     $D = '[ABEHMNPRVWXY]';
592     $L = '[ABDEFGHJLNPQRSTUWXYZ]';
593     $N = '\d';
594     if (! preg_match("/^($A$N|$A$B$N|$A$N$N|$A$B$N$N|$A$B$N$D|$A$N$C|GIR)\s*($N$L$L)$/", $postcode, $m)) return false;
595     if ($m[1] == "GIR" && $m[2] != "0AA") return false;
596     list($ignored, $outward, $inward) = $m;
597     return true;
598   }
599
600   function format_postcode($postcode, $complain = true) {
601     if (validate_postcode($postcode, $outward, $inward)) {
602       return "$outward $inward";
603     }
604     if ($complain) {
605       echo "<p>Invalid postcode!</p>\n";
606       return null;
607     }
608   }
609
610   function get_small_link_with_id() {
611     /* Args are <id>, <alt text>, <format>, [<stuff> ...] */
612     $args = func_get_args();
613     $id = array_shift($args);
614     if (isset($id)) $id = " id=\"$id\"";
615     $html = htmlspecialchars(array_shift($args));
616     $url = array_shift($args);
617     return vsprintf("<a$id class=\"small noprint\" href=\"$url\">$html</a>\n", $args);
618   }
619
620   function get_small_link() {
621     /* Args are <alt text>, <format>, [<stuff> ...] */
622     $args = func_get_args();
623     array_unshift($args, null);
624     return call_user_func_array("get_small_link_with_id", $args);
625   }
626
627   function small_link() {
628     echo call_user_func_array("get_small_link", func_get_args());
629   }
630
631   function check_dates($description, $from, $to, $mandatory_from = true, $mandatory_to = true) {
632     $Description = ucfirst($description);
633     if ($from || $mandatory_from) {
634       list($y, $m, $d) = explode('-', $from);
635       if (! checkdate($m, $d, $y)) {
636         echo "<p>Invalid $description start date!</p>\n";
637         return false;
638       }
639       $start = mktime(0, 0, 0, $m, $d, $y);
640     }
641     else $start = 0;
642
643     if ($to || $mandatory_to) {
644       list($y, $m, $d) = explode('-', $to);
645       if (! checkdate($m, $d, $y)) {
646         echo "<p>Invalid $description end date!</p>\n";
647         return false;
648       }
649       $end = mktime(0, 0, 0, $m, $d, $y);
650     }
651     else $end = PHP_INT_MAX;
652
653     if ($end < $start) {
654       echo "<p>$Description end date is earlier than start date!</p>\n";
655       return false;
656     }
657
658     return true;
659   }
660
661   include_once(join(DIRECTORY_SEPARATOR, array($lib_root, "admin.php")));
662   include_once(join(DIRECTORY_SEPARATOR, array($lib_root, "forms.php")));
663
664 ?>