SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/GeoSeach.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13. namespace Sprout\Helpers;
  14.  
  15. use DateTime;
  16. use Kohana;
  17.  
  18. use karmabunny\pdb\Exceptions\RowMissingException;
  19. use Sprout\Helpers\HttpReq;
  20. use Sprout\Helpers\Pdb;
  21.  
  22.  
  23. class GeoSeach
  24. {
  25. /**
  26.   * Return lat, lng by given query
  27.   *
  28.   * @param string $request Typically an address
  29.   * @return array [lat => float, lng => float]
  30.   * @return null No result found
  31.   */
  32. public static function getByQuery($request)
  33. {
  34. try {
  35. $q = "SELECT geo.lat, geo.lng
  36. FROM ~geosearch_cache AS geo
  37. WHERE query = ?
  38. LIMIT 1";
  39. $row = Pdb::query($q, [$request], 'row');
  40.  
  41. if ($row['lat'] == 0 and $row['lng'] == 0) {
  42. return null;
  43. } else {
  44. return $row;
  45. }
  46.  
  47. } catch (RowMissingException $ex) {
  48. // No cache record, so do a lookup instead
  49. }
  50.  
  51. $opts = [];
  52. $opts['method'] = 'GET';
  53. $opts['headers'] = [
  54. 'User-Agent' => sprintf('PHP/%s Sprout/%u (%s)', PHP_VERSION, Kohana::config('core.version_brand'), Kohana::config('sprout.site_title')),
  55. ];
  56.  
  57. $params = [];
  58. $params['q'] = $request;
  59. $params['format'] = 'json';
  60. $url = 'https://nominatim.openstreetmap.org/search?' . http_build_query($params);
  61.  
  62. $result = HttpReq::req($url, $opts);
  63. $result = json_decode($result);
  64.  
  65. $dt = new DateTime();
  66. $dt->modify('+ 6 months');
  67.  
  68. $data = [];
  69. $data['query'] = $request;
  70. $data['lat'] = !empty($result[0]->lat) ? $result[0]->lat : 0;
  71. $data['lng'] = !empty($result[0]->lon) ? $result[0]->lon : 0;
  72. $data['date_expiry'] = $dt->format('Y-m-d');
  73. Pdb::insert('geosearch_cache', $data);
  74.  
  75. if (count($result) == 0) {
  76. return null;
  77. } else {
  78. return ['lat' => $result[0]->lat, 'lng' => $result[0]->lon];
  79. }
  80. }
  81. }
  82.