Also tries to geocode in the country's languages if geocoded and given text don't...
[platal.git] / classes / gmapsgeocoder.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 // Implementation of a Geocoder using the Google Maps API. Please refer to
23 // the following links for details:
24 // http://code.google.com/apis/maps/documentation/services.html#Geocoding
25 // http://code.google.com/intl/en/apis/maps/documentation/geocoding/
26 // http://code.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy
27 //
28 // It requires the properties gmaps_key and gmaps_url to be defined in section
29 // Geocoder in plat/al's configuration (platal.ini & platal.conf).
30 class GMapsGeocoder extends Geocoder {
31
32 // Maximum number of Geocoding calls to the Google Maps API.
33 const MAX_GMAPS_RPC_CALLS = 5;
34 // Maximum levenshtein distance authorized between input and geocoded text in a single line.
35 const MAX_LINE_DISTANCE = 5;
36 // Maximum levenshtein distance authorized between input and geocoded text in the whole text.
37 const MAX_TOTAL_DISTANCE = 6;
38
39 public function getGeocodedAddress(Address &$address) {
40 $this->prepareAddress($address);
41 $textAddress = $this->getTextToGeocode($address->text);
42
43 // Try to geocode the full address.
44 if (($geocodedData = $this->getPlacemarkForAddress($textAddress))) {
45 $this->getUpdatedAddress($address, $geocodedData, null);
46 return;
47 }
48
49 // If the full geocoding failed, try to geocode only the final part of the address.
50 // We start by geocoding everything but the first line, and continue until we get
51 // a result. To respect the limit of GMaps calls, we ignore the first few lines
52 // if there are too many address lines.
53 $addressLines = explode("\n", $textAddress);
54 $linesCount = count($addressLines);
55 for ($i = max(1, $linesCount - self::MAX_GMAPS_RPC_CALLS + 1); $i < $linesCount; ++$i) {
56 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
57 $toGeocode = implode("\n", array_slice($addressLines, $i));
58 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode))) {
59 $this->getUpdatedAddress($address, $geocodedData, $extraLines);
60 return;
61 }
62 }
63 }
64
65 public function stripGeocodingFromAddress(Address &$address) {
66 $address->geocodedText = null;
67 $address->geoloc_choice = null;
68 $address->countryId = null;
69 $address->country = null;
70 $address->administrativeAreaName = null;
71 $address->subAdministrativeAreaName = null;
72 $address->localityName = null;
73 $address->thoroughfareName = null;
74 $address->postalCode = null;
75 $address->accuracy = 0;
76 }
77
78 // Updates the address with the geocoded information from Google Maps. Also
79 // cleans up the final informations.
80 private function getUpdatedAddress(Address &$address, array $geocodedData, $extraLines) {
81 $this->fillAddressWithGeocoding($address, $geocodedData, false);
82 $this->formatAddress($address, $extraLines);
83 }
84
85 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
86 // address, by querying the Google Maps API. Returns the array on success,
87 // and null otherwise.
88 private function getPlacemarkForAddress($address, $defaultLanguage = null) {
89 if (is_null($defaultLanguage)) {
90 $defaultLanguage = Platal::globals()->geocoder->gmaps_hl;
91 }
92
93 $url = $this->getGeocodingUrl($address, $defaultLanguage);
94 $geoData = $this->getGeoJsonFromUrl($url);
95
96 return ($geoData ? $this->getPlacemarkFromJson($geoData) : null);
97 }
98
99 // Prepares address to be geocoded
100 private function prepareAddress(Address &$address) {
101 $address->text = preg_replace('/\s*\n\s*/m', "\n", trim($address->text));
102 }
103
104 // Builds the Google Maps geocoder url to fetch information about @p address.
105 // Returns the built url.
106 private function getGeocodingUrl($address, $defaultLanguage) {
107 global $globals;
108
109 $parameters = array(
110 'key' => $globals->geocoder->gmaps_key,
111 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
112 'hl' => $defaultLanguage,
113 'oe' => 'utf8', // Output encoding.
114 'output' => 'json', // Output format.
115 'gl' => $globals->geocoder->gmaps_gl,
116 'q' => $address, // The queries address.
117 );
118
119 return $globals->geocoder->gmaps_url . '?' . http_build_query($parameters);
120 }
121
122 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
123 // Returns the json array on success, and null otherwise.
124 private function getGeoJsonFromUrl($url) {
125 global $globals;
126
127 // Prepare a backtrace object to log errors.
128 $bt = null;
129 if ($globals->debug & DEBUG_BT) {
130 if (!isset(PlBacktrace::$bt['Geoloc'])) {
131 new PlBacktrace('Geoloc');
132 }
133 $bt = &PlBacktrace::$bt['Geoloc'];
134 $bt->start($url);
135 }
136
137 // Fetch the geocoding data.
138 $rawData = file_get_contents($url);
139 if (!$rawData) {
140 if ($bt) {
141 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
142 }
143 return null;
144 }
145
146 // Decode the JSON-encoded data, and check for their validity.
147 $data = json_decode($rawData, true);
148 if ($bt) {
149 $bt->stop(count($data), null, $data);
150 }
151
152 return $data;
153 }
154
155 // Extracts the most appropriate placemark from the JSON data fetched from
156 // Google Maps. Returns a Placemark array on success, and null otherwise. See
157 // http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured
158 // for details on the Placemark structure.
159 private function getPlacemarkFromJson(array $data) {
160 // Check for geocoding failures.
161 if (!isset($data['Status']['code']) || $data['Status']['code'] != 200) {
162 // TODO: handle non-200 codes in a better way, since the code might
163 // indicate a temporary error on Google's side.
164 return null;
165 }
166
167 // Check that at least one placemark was found.
168 if (count($data['Placemark']) == 0) {
169 return null;
170 }
171
172 // Extract the placemark with the best accuracy. This is not always the
173 // best result (since the same address may yield two different placemarks).
174 $result = $data['Placemark'][0];
175 foreach ($data['Placemark'] as $place) {
176 if ($place['AddressDetails']['Accuracy'] > $result['AddressDetails']['Accuracy']) {
177 $result = $place;
178 }
179 }
180
181 return $result;
182 }
183
184 // Fills the address with the geocoded data
185 private function fillAddressWithGeocoding(Address &$address, $geocodedData, $isLocal) {
186 // The geocoded address three is
187 // Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
188 // with all the possible shortcuts
189 // The address is formatted as xAL, or eXtensible Address Language, an international
190 // standard for address formatting.
191 // xAL documentation: http://www.oasis-open.org/committees/ciq/ciq.html#6
192 if ($isLocal) {
193 $ext = 'Local';
194 } else {
195 $ext = ucfirst(Platal::globals()->geocoder->gmaps_hl);
196 $address->geocodedText = str_replace(', ', "\n", $geocodedData['address']);
197 }
198
199 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
200 $address->accuracy = $geocodedData['AddressDetails']['Accuracy'];
201 }
202
203 $currentPosition = $geocodedData['AddressDetails'];
204 if (isset($currentPosition['Country'])) {
205 $country = 'country' . $ext;
206 $currentPosition = $currentPosition['Country'];
207 $address->countryId = $currentPosition['CountryNameCode'];
208 $address->$country = $currentPosition['CountryName'];
209 }
210 if (isset($currentPosition['AdministrativeArea'])) {
211 $administrativeAreaName = 'administrativeAreaName' . $ext;
212 $currentPosition = $currentPosition['AdministrativeArea'];
213 $address->$administrativeAreaName = $currentPosition['AdministrativeAreaName'];
214 }
215 if (isset($currentPosition['SubAdministrativeArea'])) {
216 $subAdministrativeAreaName = 'subAdministrativeAreaName' . $ext;
217 $currentPosition = $currentPosition['SubAdministrativeArea'];
218 $address->$subAdministrativeAreaName = $currentPosition['SubAdministrativeAreaName'];
219 }
220 if (isset($currentPosition['Locality'])) {
221 $localityName = 'localityName' . $ext;
222 $currentPosition = $currentPosition['Locality'];
223 $address->$localityName = $currentPosition['LocalityName'];
224 }
225 if (isset($currentPosition['PostalCode'])) {
226 $address->postalCode = $currentPosition['PostalCode']['PostalCodeNumber'];
227 }
228
229 // Gets coordinates.
230 if (isset($geocodedData['Point']['coordinates'][0])) {
231 $address->latitude = $geocodedData['Point']['coordinates'][0];
232 }
233 if (isset($geocodedData['Point']['coordinates'][1])) {
234 $address->longitude = $geocodedData['Point']['coordinates'][1];
235 }
236 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
237 $address->north = $geocodedData['ExtendedData']['LatLonBox']['north'];
238 }
239 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
240 $address->south = $geocodedData['ExtendedData']['LatLonBox']['south'];
241 }
242 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
243 $address->east = $geocodedData['ExtendedData']['LatLonBox']['east'];
244 }
245 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
246 $address->west = $geocodedData['ExtendedData']['LatLonBox']['west'];
247 }
248 }
249
250 // Compares the geocoded address with the given address and returns true
251 // iff their are close enough to be considered as equals or not.
252 private function compareAddress($address)
253 {
254 $same = true;
255 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
256 array('', "\n"), $address->geocodedText));
257 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
258 array('', "\n"), $address->text));
259 $arrayGeoloc = explode("\n", $geoloc);
260 $arrayText = explode("\n", $text);
261 $countGeoloc = count($arrayGeoloc);
262 $countText = count($arrayText);
263
264 $totalDistance = 0;
265 if (($countText > $countGeoloc) || ($countText < $countGeoloc - 1)
266 || (($countText == $countGeoloc - 1)
267 && ($arrayText[$countText - 1] == strtoupper($address->country)))) {
268 $same = false;
269 } else {
270 for ($i = 0; $i < $countGeoloc && $i < $countText; ++$i) {
271 $lineDistance = levenshtein($arrayText[$i], trim($arrayGeoloc[$i]));
272 $totalDistance += $lineDistance;
273 if ($lineDistance > self::MAX_LINE_DISTANCE || $totalDistance > self::MAX_TOTAL_DISTANCE) {
274 $same = false;
275 break;
276 }
277 }
278 }
279
280 return $same;
281 }
282
283 // Formats the text of the geocoded address using the unused data and
284 // compares it to the given address. If they are too different, the user
285 // will be asked to choose between them.
286 private function formatAddress(Address &$address, $extraLines)
287 {
288 if ($extraLines) {
289 $address->geocodedText = $extraLines . "\n" . $address->geocodedText;
290 }
291
292 if ($this->compareAddress($address)) {
293 $address->geocodedText = null;
294 } else {
295 $languages = XDB::fetchOneCell('SELECT IF(ISNULL(gc1.belongsTo), gc1.languages, gc2.languages)
296 FROM geoloc_countries AS gc1
297 LEFT JOIN geoloc_countries AS gc2 ON (gc1.belongsTo = gc2.iso_3166_1_a2)
298 WHERE gc1.iso_3166_1_a2 = {?}',
299 $address->countryId);
300 $toGeocode = substr($address->text, strlen($extraLines));
301 foreach (explode(',', $languages) as $language) {
302 if ($language != Platal::globals()->geocoder->gmaps_hl) {
303 $geocodedData = $this->getPlacemarkForAddress($toGeocode, $language);
304 $address->geocodedText = str_replace(', ', "\n", $geocodedData['address']);
305 if ($extraLines) {
306 $address->geocodedText = $extraLines . "\n" . $address->geocodedText;
307 }
308 if ($this->compareAddress($address)) {
309 $this->fillAddressWithGeocoding($address, $geocodedData, true);
310 $address->geocodedText = null;
311 break;
312 }
313 }
314 }
315 $address->geocodedText = str_replace("\n", "\r\n", $address->geocodedText);
316 }
317 $address->text = str_replace("\n", "\r\n", $address->text);
318 }
319
320 // Trims the name of the real country if it contains an ISO 3166-1 non-country
321 // item. For that purpose, we compare the last but one line of the address with
322 // all non-country items of ISO 3166-1.
323 private function getTextToGeocode($text)
324 {
325 $res = XDB::iterator('SELECT countryEn, country
326 FROM geoloc_countries
327 WHERE belongsTo IS NOT NULL');
328 $countries = array();
329 foreach ($res as $item) {
330 $countries[] = $item[0];
331 $countries[] = $item[1];
332 }
333 $textLines = explode("\n", $text);
334 $countLines = count($textLines);
335 $needle = strtoupper(trim($textLines[$countLines - 2]));
336 $isPseudoCountry = false;
337 foreach ($countries as $country) {
338 if (strtoupper($country) == $needle) {
339 $isPseudoCountry = true;
340 break;
341 }
342 }
343
344 if ($isPseudoCountry) {
345 return implode("\n", array_slice($textLines, 0, -1));
346 }
347 return $text;
348 }
349 }
350
351 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
352 ?>