Improves country detection for postal addresses formatting.
[platal.git] / classes / gmapsgeocoder.php
CommitLineData
4c906759
SJ
1<?php
2/***************************************************************************
d4c08d89 3 * Copyright (C) 2003-2010 Polytechnique.org *
4c906759
SJ
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
4c906759
SJ
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).
30class GMapsGeocoder extends Geocoder {
31
32 // Maximum number of Geocoding calls to the Google Maps API.
33 const MAX_GMAPS_RPC_CALLS = 5;
7bc2c396
SJ
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;
4c906759 38
4e7a3faa
SJ
39 public function getGeocodedAddress(Address &$address) {
40 $this->prepareAddress($address);
41 $textAddress = $this->getTextToGeocode($address->text);
4c906759
SJ
42
43 // Try to geocode the full address.
44 if (($geocodedData = $this->getPlacemarkForAddress($textAddress))) {
4e7a3faa
SJ
45 $this->getUpdatedAddress($address, $geocodedData, null);
46 return;
4c906759
SJ
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))) {
4e7a3faa
SJ
59 $this->getUpdatedAddress($address, $geocodedData, $extraLines);
60 return;
4c906759
SJ
61 }
62 }
4c906759
SJ
63 }
64
4e7a3faa
SJ
65 public function stripGeocodingFromAddress(Address &$address) {
66 $address->geocodedText = null;
4e7a3faa
SJ
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;
73f6c165 76 }
00e5200b 77
4c906759
SJ
78 // Updates the address with the geocoded information from Google Maps. Also
79 // cleans up the final informations.
4e7a3faa 80 private function getUpdatedAddress(Address &$address, array $geocodedData, $extraLines) {
803612ae 81 $this->fillAddressWithGeocoding($address, $geocodedData, false);
4c906759 82 $this->formatAddress($address, $extraLines);
4c906759
SJ
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.
803612ae
SJ
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);
4c906759
SJ
94 $geoData = $this->getGeoJsonFromUrl($url);
95
96 return ($geoData ? $this->getPlacemarkFromJson($geoData) : null);
97 }
98
99 // Prepares address to be geocoded
4e7a3faa
SJ
100 private function prepareAddress(Address &$address) {
101 $address->text = preg_replace('/\s*\n\s*/m', "\n", trim($address->text));
4c906759
SJ
102 }
103
104 // Builds the Google Maps geocoder url to fetch information about @p address.
105 // Returns the built url.
803612ae 106 private function getGeocodingUrl($address, $defaultLanguage) {
4c906759
SJ
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.
803612ae 112 'hl' => $defaultLanguage,
4c906759
SJ
113 'oe' => 'utf8', // Output encoding.
114 'output' => 'json', // Output format.
ce3e0af3 115 'gl' => $globals->geocoder->gmaps_gl,
4c906759
SJ
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) {
4e7a3faa 141 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
4c906759
SJ
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
803612ae 185 private function fillAddressWithGeocoding(Address &$address, $geocodedData, $isLocal) {
4c906759
SJ
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
803612ae
SJ
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
4c906759 199 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
4e7a3faa 200 $address->accuracy = $geocodedData['AddressDetails']['Accuracy'];
4c906759
SJ
201 }
202
203 $currentPosition = $geocodedData['AddressDetails'];
204 if (isset($currentPosition['Country'])) {
803612ae 205 $country = 'country' . $ext;
4e7a3faa
SJ
206 $currentPosition = $currentPosition['Country'];
207 $address->countryId = $currentPosition['CountryNameCode'];
803612ae 208 $address->$country = $currentPosition['CountryName'];
4c906759
SJ
209 }
210 if (isset($currentPosition['AdministrativeArea'])) {
803612ae
SJ
211 $administrativeAreaName = 'administrativeAreaName' . $ext;
212 $currentPosition = $currentPosition['AdministrativeArea'];
213 $address->$administrativeAreaName = $currentPosition['AdministrativeAreaName'];
4c906759
SJ
214 }
215 if (isset($currentPosition['SubAdministrativeArea'])) {
803612ae
SJ
216 $subAdministrativeAreaName = 'subAdministrativeAreaName' . $ext;
217 $currentPosition = $currentPosition['SubAdministrativeArea'];
218 $address->$subAdministrativeAreaName = $currentPosition['SubAdministrativeAreaName'];
4c906759
SJ
219 }
220 if (isset($currentPosition['Locality'])) {
803612ae
SJ
221 $localityName = 'localityName' . $ext;
222 $currentPosition = $currentPosition['Locality'];
223 $address->$localityName = $currentPosition['LocalityName'];
4c906759
SJ
224 }
225 if (isset($currentPosition['PostalCode'])) {
4e7a3faa 226 $address->postalCode = $currentPosition['PostalCode']['PostalCodeNumber'];
4c906759
SJ
227 }
228
229 // Gets coordinates.
230 if (isset($geocodedData['Point']['coordinates'][0])) {
4e7a3faa 231 $address->latitude = $geocodedData['Point']['coordinates'][0];
4c906759
SJ
232 }
233 if (isset($geocodedData['Point']['coordinates'][1])) {
4e7a3faa 234 $address->longitude = $geocodedData['Point']['coordinates'][1];
4c906759
SJ
235 }
236 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
4e7a3faa 237 $address->north = $geocodedData['ExtendedData']['LatLonBox']['north'];
4c906759
SJ
238 }
239 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
4e7a3faa 240 $address->south = $geocodedData['ExtendedData']['LatLonBox']['south'];
4c906759
SJ
241 }
242 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
4e7a3faa 243 $address->east = $geocodedData['ExtendedData']['LatLonBox']['east'];
4c906759
SJ
244 }
245 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
4e7a3faa 246 $address->west = $geocodedData['ExtendedData']['LatLonBox']['west'];
4c906759
SJ
247 }
248 }
249
803612ae
SJ
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 {
4c906759 254 $same = true;
4c906759 255 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
4e7a3faa 256 array('', "\n"), $address->geocodedText));
4c906759 257 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
4e7a3faa 258 array('', "\n"), $address->text));
4c906759
SJ
259 $arrayGeoloc = explode("\n", $geoloc);
260 $arrayText = explode("\n", $text);
261 $countGeoloc = count($arrayGeoloc);
262 $countText = count($arrayText);
263
7bc2c396 264 $totalDistance = 0;
4c906759
SJ
265 if (($countText > $countGeoloc) || ($countText < $countGeoloc - 1)
266 || (($countText == $countGeoloc - 1)
4e7a3faa 267 && ($arrayText[$countText - 1] == strtoupper($address->country)))) {
4c906759
SJ
268 $same = false;
269 } else {
270 for ($i = 0; $i < $countGeoloc && $i < $countText; ++$i) {
7bc2c396
SJ
271 $lineDistance = levenshtein($arrayText[$i], trim($arrayGeoloc[$i]));
272 $totalDistance += $lineDistance;
273 if ($lineDistance > self::MAX_LINE_DISTANCE || $totalDistance > self::MAX_TOTAL_DISTANCE) {
4c906759 274 $same = false;
7bc2c396 275 break;
4c906759
SJ
276 }
277 }
278 }
7bc2c396 279
803612ae
SJ
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)) {
4e7a3faa 293 $address->geocodedText = null;
eecbf7f5 294 } else {
803612ae
SJ
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 }
4e7a3faa 315 $address->geocodedText = str_replace("\n", "\r\n", $address->geocodedText);
4c906759 316 }
4e7a3faa 317 $address->text = str_replace("\n", "\r\n", $address->text);
5a10ab14
SJ
318 }
319
00e5200b
SJ
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.
4e7a3faa 323 private function getTextToGeocode($text)
00e5200b 324 {
1c305d4c 325 $res = XDB::iterator('SELECT countryEn, country
00e5200b
SJ
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 }
4e7a3faa 333 $textLines = explode("\n", $text);
00e5200b
SJ
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) {
02c4b93a 345 return implode("\n", array_slice($textLines, 0, -1));
00e5200b 346 }
4e7a3faa 347 return $text;
00e5200b 348 }
4c906759
SJ
349}
350
351// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
352?>