Switches to a 3-state geocoding: the user can choose to keep the geocoded properties...
[platal.git] / include / geocoding.inc.php
CommitLineData
4c906759
SJ
1<?php
2/***************************************************************************
3 * Copyright (C) 2003-2009 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// Interface for an address geocoder. It provides support for transforming a free
23// form address into a fully structured one.
24// TODO: define and use an Address object instead of a key-value map.
25abstract class Geocoder {
26 // Geocodes @p the address, and returns the corresponding updated address.
27 // Unknown key-value pairs available in the input map are retained as-is.
28 abstract public function getGeocodedAddress(array $address);
29
73f6c165
SJ
30 // Cleans the address from its geocoded data
31 abstract public function stripGeocodingFromAddress(array $address);
32
4c906759
SJ
33 // Updates geoloc_administrativeareas, geoloc_subadministrativeareas and
34 // geoloc_localities databases with new geocoded data and returns the
35 // corresponding id.
36 static public function getAreaId(array &$address, $area)
37 {
38 static $databases = array(
39 'administrativeArea' => 'geoloc_administrativeareas',
40 'subAdministrativeArea' => 'geoloc_subadministrativeareas',
41 'locality' => 'geoloc_localities',
42 );
43
44 if (isset($address[$area . 'Name']) && isset($databases[$area])) {
45 $res = XDB::query("SELECT id
46 FROM " . $databases[$area] . "
47 WHERE name = {?}",
48 $address[$area . 'Name']);
49 if ($res->numRows() == 0) {
50 $address[$area . 'Id'] = XDB::execute("INSERT INTO " . $databases[$area] . " (name, country)
51 VALUES ({?}, {?})",
52 $address[$area . 'Name'], $address['countryId']);
53 } else {
54 $address[$area . 'Id'] = $res->fetchOneCell();
55 }
56 }
57 }
8f60459a
SJ
58
59 // Returns the part of the text preceeding the line with the postal code
60 // and the city name, within the limit of $limit number of lines.
61 static public function getFirstLines($text, $postalCode, $limit)
62 {
63 $textArray = explode("\n", $text);
64 for ($i = 0; $i < count($textArray); ++$i) {
65 if ($i > $limit || strpos($textLine, $postalCode) !== false) {
66 $limit = $i; break;
67 }
68 }
69 return implode("\n", array_slice($textArray, 0, $limit));
70 }
2aa2c77a
SJ
71
72 // Returns the number of non geocoded addresses for a user.
73 static public function countNonGeocoded($pid)
74 {
75 $res = XDB::query("SELECT COUNT(*)
76 FROM profile_addresses
77 WHERE pid = {?} AND FIND_IN_SET('home', type) AND accuracy = 0",
78 $pid);
79 return $res->fetchOneCell();
80 }
4c906759
SJ
81}
82
83// Implementation of a Geocoder using the Google Maps API. Please refer to
84// the following links for details:
85// http://code.google.com/apis/maps/documentation/services.html#Geocoding
86// http://code.google.com/intl/en/apis/maps/documentation/geocoding/
87// http://code.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy
88//
89// It requires the properties gmaps_key and gmaps_url to be defined in section
90// Geocoder in plat/al's configuration (platal.ini & platal.conf).
91class GMapsGeocoder extends Geocoder {
92
93 // Maximum number of Geocoding calls to the Google Maps API.
94 const MAX_GMAPS_RPC_CALLS = 5;
95
96 public function getGeocodedAddress(array $address) {
97 $address = $this->prepareAddress($address);
98 $textAddress = $address['text'];
99
100 // Try to geocode the full address.
101 if (($geocodedData = $this->getPlacemarkForAddress($textAddress))) {
102 return $this->getUpdatedAddress($address, $geocodedData, null);
103 }
104
105 // If the full geocoding failed, try to geocode only the final part of the address.
106 // We start by geocoding everything but the first line, and continue until we get
107 // a result. To respect the limit of GMaps calls, we ignore the first few lines
108 // if there are too many address lines.
109 $addressLines = explode("\n", $textAddress);
110 $linesCount = count($addressLines);
111 for ($i = max(1, $linesCount - self::MAX_GMAPS_RPC_CALLS + 1); $i < $linesCount; ++$i) {
112 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
113 $toGeocode = implode("\n", array_slice($addressLines, $i));
114 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode))) {
115 return $this->getUpdatedAddress($address, $geocodedData, $extraLines);
116 }
117 }
118
119 // No geocoding could be done, the initial address is returned as-is.
120 return $address;
121 }
122
73f6c165 123 public function stripGeocodingFromAddress(array $address) {
5a10ab14
SJ
124 unset($address['geoloc'], $address['geoloc_choice'], $address['geocodedPostalText'],
125 $address['countryId'], $address['country'], $address['administrativeAreaName'],
73f6c165
SJ
126 $address['subAdministrativeAreaName'], $address['localityName'],
127 $address['thoroughfareName'], $address['postalCode']);
128 $address['accuracy'] = 0;
129 return $address;
130 }
131
4c906759
SJ
132 // Updates the address with the geocoded information from Google Maps. Also
133 // cleans up the final informations.
134 private function getUpdatedAddress(array $address, array $geocodedData, $extraLines) {
135 $this->fillAddressWithGeocoding(&$address, $geocodedData);
136
137 // If the accuracy is 6, it means only the street has been gecoded
138 // but not the number, thus we need to fix it.
139 if ($address['accuracy'] == 6) {
140 $this->fixStreetNumber($address);
141 }
142
143 // We can now format the address.
144 $this->formatAddress($address, $extraLines);
145
146 // Some entities in ISO 3166 are not countries, thus they have to be replaced
147 // by the country they belong to.
148 // TODO: fixCountry($address);
149
150 return $address;
151 }
152
153 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
154 // address, by querying the Google Maps API. Returns the array on success,
155 // and null otherwise.
156 private function getPlacemarkForAddress($address) {
157 $url = $this->getGeocodingUrl($address);
158 $geoData = $this->getGeoJsonFromUrl($url);
159
160 return ($geoData ? $this->getPlacemarkFromJson($geoData) : null);
161 }
162
163 // Prepares address to be geocoded
164 private function prepareAddress($address) {
165 $address['text'] = preg_replace('/\s*\n\s*/m', "\n", trim($address['text']));
5a10ab14 166 $address['postalText'] = $this->getPostalAddress($address['text']);
4c906759
SJ
167 $address['updateTime'] = time();
168 unset($address['changed']);
169 return $address;
170 }
171
172 // Builds the Google Maps geocoder url to fetch information about @p address.
173 // Returns the built url.
174 private function getGeocodingUrl($address) {
175 global $globals;
176
177 $parameters = array(
178 'key' => $globals->geocoder->gmaps_key,
179 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
180 'hl' => 'fr', // Output langage.
181 'oe' => 'utf8', // Output encoding.
182 'output' => 'json', // Output format.
183 'gl' => 'fr', // Location preferences (addresses are in France by default).
184 'q' => $address, // The queries address.
185 );
186
187 return $globals->geocoder->gmaps_url . '?' . http_build_query($parameters);
188 }
189
190 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
191 // Returns the json array on success, and null otherwise.
192 private function getGeoJsonFromUrl($url) {
193 global $globals;
194
195 // Prepare a backtrace object to log errors.
196 $bt = null;
197 if ($globals->debug & DEBUG_BT) {
198 if (!isset(PlBacktrace::$bt['Geoloc'])) {
199 new PlBacktrace('Geoloc');
200 }
201 $bt = &PlBacktrace::$bt['Geoloc'];
202 $bt->start($url);
203 }
204
205 // Fetch the geocoding data.
206 $rawData = file_get_contents($url);
207 if (!$rawData) {
208 if ($bt) {
209 $bt->stop(0, "Could not retrieve geocoded address from GoogleMaps.");
210 }
211 return null;
212 }
213
214 // Decode the JSON-encoded data, and check for their validity.
215 $data = json_decode($rawData, true);
216 if ($bt) {
217 $bt->stop(count($data), null, $data);
218 }
219
220 return $data;
221 }
222
223 // Extracts the most appropriate placemark from the JSON data fetched from
224 // Google Maps. Returns a Placemark array on success, and null otherwise. See
225 // http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured
226 // for details on the Placemark structure.
227 private function getPlacemarkFromJson(array $data) {
228 // Check for geocoding failures.
229 if (!isset($data['Status']['code']) || $data['Status']['code'] != 200) {
230 // TODO: handle non-200 codes in a better way, since the code might
231 // indicate a temporary error on Google's side.
232 return null;
233 }
234
235 // Check that at least one placemark was found.
236 if (count($data['Placemark']) == 0) {
237 return null;
238 }
239
240 // Extract the placemark with the best accuracy. This is not always the
241 // best result (since the same address may yield two different placemarks).
242 $result = $data['Placemark'][0];
243 foreach ($data['Placemark'] as $place) {
244 if ($place['AddressDetails']['Accuracy'] > $result['AddressDetails']['Accuracy']) {
245 $result = $place;
246 }
247 }
248
249 return $result;
250 }
251
252 // Fills the address with the geocoded data
253 private function fillAddressWithGeocoding(&$address, $geocodedData) {
254 // The geocoded address three is
255 // Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
256 // with all the possible shortcuts
257 // The address is formatted as xAL, or eXtensible Address Language, an international
258 // standard for address formatting.
259 // xAL documentation: http://www.oasis-open.org/committees/ciq/ciq.html#6
260 $address['geoloc'] = str_replace(", ", "\n", $geocodedData['address']);
261 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
262 $address['accuracy'] = $geocodedData['AddressDetails']['Accuracy'];
263 }
264
265 $currentPosition = $geocodedData['AddressDetails'];
266 if (isset($currentPosition['Country'])) {
267 $currentPosition = $currentPosition['Country'];
268 $address['countryId'] = $currentPosition['CountryNameCode'];
269 $address['country'] = $currentPosition['CountryName'];
270 }
271 if (isset($currentPosition['AdministrativeArea'])) {
272 $currentPosition = $currentPosition['AdministrativeArea'];
273 $address['administrativeAreaName'] = $currentPosition['AdministrativeAreaName'];
274 }
275 if (isset($currentPosition['SubAdministrativeArea'])) {
276 $currentPosition = $currentPosition['SubAdministrativeArea'];
277 $address['subAdministrativeAreaName'] = $currentPosition['SubAdministrativeAreaName'];
278 }
279 if (isset($currentPosition['Locality'])) {
280 $currentPosition = $currentPosition['Locality'];
281 $address['localityName'] = $currentPosition['LocalityName'];
282 }
283 if (isset($currentPosition['Thoroughfare'])) {
284 $address['thoroughfareName'] = $currentPosition['Thoroughfare']['ThoroughfareName'];
285 }
286 if (isset($currentPosition['PostalCode'])) {
287 $address['postalCode'] = $currentPosition['PostalCode']['PostalCodeNumber'];
288 }
289
290 // Gets coordinates.
291 if (isset($geocodedData['Point']['coordinates'][0])) {
292 $address['latitude'] = $geocodedData['Point']['coordinates'][0];
293 }
294 if (isset($geocodedData['Point']['coordinates'][1])) {
295 $address['longitude'] = $geocodedData['Point']['coordinates'][1];
296 }
297 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
298 $address['north'] = $geocodedData['ExtendedData']['LatLonBox']['north'];
299 }
300 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
301 $address['south'] = $geocodedData['ExtendedData']['LatLonBox']['south'];
302 }
303 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
304 $address['east'] = $geocodedData['ExtendedData']['LatLonBox']['east'];
305 }
306 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
307 $address['west'] = $geocodedData['ExtendedData']['LatLonBox']['west'];
308 }
309 }
310
311 // Formats the text of the geocoded address using the unused data and
312 // compares it to the given address. If they are too different, the user
313 // will be asked to choose between them.
314 private function formatAddress(&$address, $extraLines) {
315 $same = true;
316 if ($extraLines) {
317 $address['geoloc'] = $extraLines . "\n" . $address['geoloc'];
318 }
5a10ab14 319 $address['geocodedPostalText'] = $this->getPostalAddress($address['geoloc']);
4c906759
SJ
320 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
321 array("", "\n"), $address['geoloc']));
322 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
323 array("", "\n"), $address['text']));
324 $arrayGeoloc = explode("\n", $geoloc);
325 $arrayText = explode("\n", $text);
326 $countGeoloc = count($arrayGeoloc);
327 $countText = count($arrayText);
328
329 if (($countText > $countGeoloc) || ($countText < $countGeoloc - 1)
330 || (($countText == $countGeoloc - 1)
331 && ($arrayText[$countText - 1] == strtoupper($address['country'])))) {
332 $same = false;
333 } else {
334 for ($i = 0; $i < $countGeoloc && $i < $countText; ++$i) {
335 if (levenshtein($arrayText[$i], trim($arrayGeoloc[$i])) > 3) {
336 $same = false;
337 }
338 }
339 }
340 if ($same) {
341 $address['text'] = $address['geoloc'];
5a10ab14
SJ
342 $address['postalText'] = $address['geocodedPostalText'];
343 unset($address['geoloc'], $address['geocodedPostalText']);
4c906759
SJ
344 }
345 }
346
5a10ab14
SJ
347 // Returns the address formated for postal use.
348 // The main rules are (cf AFNOR XPZ 10-011):
349 // -everything in upper case;
350 // -if there are more then than 38 characters in a lign, split it;
351 // -if there are more then than 32 characters in the description of the "street", use abbreviations.
352 private function getPostalAddress($text) {
353 static $abbreviations = array(
354 "IMPASSE" => "IMP",
355 "RUE" => "R",
356 "AVENUE" => "AV",
357 "BOULEVARD" => "BVD",
358 "ROUTE" => "R",
359 "STREET" => "ST",
360 "ROAD" => "RD",
361 );
362
363 $text = strtoupper($text);
364 $arrayText = explode("\n", $text);
365 $postalText = "";
366
367 foreach ($arrayText as $i => $lign) {
368 $postalText .= (($i == 0) ? "" : "\n");
369 if (($length = strlen($lign)) > 32) {
370 $words = explode(" ", $lign);
371 $count = 0;
372 foreach ($words as $word) {
373 if (isset($abbreviations[$word])) {
374 $word = $abbreviations[$word];
375 }
376 if ($count + ($wordLength = strlen($word)) <= 38) {
377 $postalText .= (($count == 0) ? "" : " ") . $word;
378 $count += (($count == 0) ? 0 : 1) + $wordLength;
379 } else {
380 $postalText .= "\n" . $word;
381 $count = strlen($word);
382 }
383 }
384 } else {
385 $postalText .= $lign;
386 }
387 }
388 return $postalText;
389 }
390
4c906759
SJ
391 // Search for the lign from the given address that is the closest to the geocoded thoroughfareName
392 // and replaces the corresponding lign in the geocoded text by it.
393 static protected function fixStreetNumber(&$address)
394 {
395 if (isset($address['thoroughfareName'])) {
396 $thoroughfareName = $address['thoroughfareName'];
397 $thoroughfareToken = strtoupper(trim(preg_replace(array("/[,\"'#~:;_\-]/", "/\r\n/"),
398 array("", "\n"), $thoroughfareName)));
399 $geolocLines = explode("\n", $address['geoloc']);
400 $textLines = explode("\n", $address['text']);
401 $mindist = strlen($thoroughfareToken);
402 $minpos = 0;
403 $pos = 0;
404 foreach ($textLines as $i => $token) {
405 if (($l = levenshtein(strtoupper(trim(preg_replace(array("/[,\"'#~:;_\-]/", "/\r\n/"),
406 array("", "\n"), $token))),
407 $thoroughfareToken)) < $mindist) {
408 $mindist = $l;
409 $minpos = $i;
410 }
411 }
412 foreach ($geolocLines as $i => $line) {
413 if (strtoupper(trim($thoroughfareName)) == strtoupper(trim($line))) {
414 $pos = $i;
415 break;
416 }
417 }
418 $geolocLines[$pos] = $textLines[$minpos];
419 $address['geoloc'] = implode("\n", $geolocLines);
420 }
421 }
422}
423
424// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
425?>