location_add.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. $page_title = "Add Location";
  3. $customer = Customer::getForAdmin();
  4. if(!$customer) throw new Exception("You do not have permission to access this page.");
  5. Core::addBreadcrumb("/account", "Account");
  6. Core::addBreadcrumb("/account/locations", "Locations");
  7. Core::addBreadcrumb("/account/locations?customer_id=$customer->id", "$customer->name Locations");
  8. Core::addBreadcrumb("/account/locations/add", $page_title);
  9. $location = new Location;
  10. $location->customer_id = $customer->id;
  11. $submit = http::value("submit");
  12. if($submit) {
  13. try {
  14. Core::validateCSRFToken($submit);
  15. $form_exception = new FormException;
  16. $location->name = http::value("name", "trim");
  17. $location->address_1 = http::value("address", "trim");
  18. if(empty($location->name)) $form_exception->addError("Name is required.");
  19. if(empty($location->address_1)) {
  20. $form_exception->addError("Full address is required.");
  21. }
  22. else {
  23. // Geocode the full address
  24. try {
  25. $results = Geolocation::geocode($location->address_1);
  26. $result = $results[0];
  27. foreach($result->address_components as $component) {
  28. $types = $component->types;
  29. if(in_array("postal_code", $types)) $location->postal_code = $component->long_name;
  30. if(in_array("route", $types)) $location->address_1 = $component->long_name;
  31. if(in_array("postal_town", $types)) $location->city = $component->long_name;
  32. if(in_array("administrative_area_level_1", $types)) $location->state = $component->long_name;
  33. if(in_array("country", $types)) $location->country = $component->long_name;
  34. }
  35. $location->latitude = $result->geometry->location->lat;
  36. $location->longitude = $result->geometry->location->lng;
  37. }
  38. catch(Exception $e) {
  39. $form_exception->addError("Failed to get location from full address: " . $e->getMessage());
  40. }
  41. }
  42. if($form_exception->hasErrors()) throw $form_exception;
  43. $success = $location->commit();
  44. if(!$success) throw new Exception("Failed to add location at this time. Please try again later.");
  45. Core::addAlert("success", "Location added successfully.");
  46. HTTP::redirect("/account/locations/$location->id");
  47. }
  48. catch(FormException $e) {
  49. $e->generateAlerts();
  50. }
  51. catch(Exception $e) {
  52. Core::addAlert("danger", $e->getMessage());
  53. }
  54. }
  55. View::includeOnce("header", compact("page_title"));
  56. View::include("location_add_form", compact("location"));
  57. View::includeOnce("footer");
  58. ?>