3e193e608f7d6dffe9e33148783b985003fe819a
[platal.git] / include / geocoding.inc.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 // 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.
25 abstract 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
30 // Cleans the address from its geocoded data
31 abstract public function stripGeocodingFromAddress(array $address);
32
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 XDB::execute('INSERT INTO ' . $databases[$area] . ' (name, country)
51 VALUES ({?}, {?})',
52 $address[$area . 'Name'], $address['countryId']);
53 $address[$area . 'Id'] = XDB::insertId();
54 } else {
55 $address[$area . 'Id'] = $res->fetchOneCell();
56 }
57 }
58 }
59
60 // Returns the part of the text preceeding the line with the postal code
61 // and the city name, within the limit of $limit number of lines.
62 static public function getFirstLines($text, $postalCode, $limit)
63 {
64 $textArray = explode("\n", $text);
65 for ($i = 0; $i < count($textArray); ++$i) {
66 if ($i > $limit || strpos($textLine, $postalCode) !== false) {
67 $limit = $i; break;
68 }
69 }
70 return implode("\n", array_slice($textArray, 0, $limit));
71 }
72
73 // Returns the number of non geocoded addresses for a user.
74 static public function countNonGeocoded($pid)
75 {
76 $res = XDB::query("SELECT COUNT(*)
77 FROM profile_addresses
78 WHERE pid = {?} AND FIND_IN_SET('home', type) AND accuracy = 0",
79 $pid);
80 return $res->fetchOneCell();
81 }
82 }
83
84 // Implementation of a Geocoder using the Google Maps API. Please refer to
85 // the following links for details:
86 // http://code.google.com/apis/maps/documentation/services.html#Geocoding
87 // http://code.google.com/intl/en/apis/maps/documentation/geocoding/
88 // http://code.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy
89 //
90 // It requires the properties gmaps_key and gmaps_url to be defined in section
91 // Geocoder in plat/al's configuration (platal.ini & platal.conf).
92 class GMapsGeocoder extends Geocoder {
93
94 // Maximum number of Geocoding calls to the Google Maps API.
95 const MAX_GMAPS_RPC_CALLS = 5;
96 // Maximum levenshtein distance authorized between input and geocoded text in a single line.
97 const MAX_LINE_DISTANCE = 5;
98 // Maximum levenshtein distance authorized between input and geocoded text in the whole text.
99 const MAX_TOTAL_DISTANCE = 6;
100
101 public function getGeocodedAddress(array $address) {
102 $address = $this->prepareAddress($address);
103 $textAddress = $this->getTextToGeocode($address);
104
105 // Try to geocode the full address.
106 if (($geocodedData = $this->getPlacemarkForAddress($textAddress))) {
107 return $this->getUpdatedAddress($address, $geocodedData, null);
108 }
109
110 // If the full geocoding failed, try to geocode only the final part of the address.
111 // We start by geocoding everything but the first line, and continue until we get
112 // a result. To respect the limit of GMaps calls, we ignore the first few lines
113 // if there are too many address lines.
114 $addressLines = explode("\n", $textAddress);
115 $linesCount = count($addressLines);
116 for ($i = max(1, $linesCount - self::MAX_GMAPS_RPC_CALLS + 1); $i < $linesCount; ++$i) {
117 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
118 $toGeocode = implode("\n", array_slice($addressLines, $i));
119 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode))) {
120 return $this->getUpdatedAddress($address, $geocodedData, $extraLines);
121 }
122 }
123
124 // No geocoding could be done, the initial address is returned as-is.
125 return $address;
126 }
127
128 public function stripGeocodingFromAddress(array $address) {
129 unset($address['geoloc'], $address['geoloc_choice'], $address['geocodedPostalText'],
130 $address['countryId'], $address['country'], $address['administrativeAreaName'],
131 $address['subAdministrativeAreaName'], $address['localityName'],
132 $address['thoroughfareName'], $address['postalCode']);
133 $address['accuracy'] = 0;
134 return $address;
135 }
136
137 // Updates the address with the geocoded information from Google Maps. Also
138 // cleans up the final informations.
139 private function getUpdatedAddress(array $address, array $geocodedData, $extraLines) {
140 $this->fillAddressWithGeocoding(&$address, $geocodedData);
141 $this->formatAddress($address, $extraLines);
142 return $address;
143 }
144
145 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
146 // address, by querying the Google Maps API. Returns the array on success,
147 // and null otherwise.
148 private function getPlacemarkForAddress($address) {
149 $url = $this->getGeocodingUrl($address);
150 $geoData = $this->getGeoJsonFromUrl($url);
151
152 return ($geoData ? $this->getPlacemarkFromJson($geoData) : null);
153 }
154
155 // Prepares address to be geocoded
156 private function prepareAddress($address) {
157 $address['text'] = preg_replace('/\s*\n\s*/m', "\n", trim($address['text']));
158 $address['postalText'] = $this->getPostalAddress($address['text']);
159 $address['updateTime'] = time();
160 unset($address['changed']);
161 return $address;
162 }
163
164 // Builds the Google Maps geocoder url to fetch information about @p address.
165 // Returns the built url.
166 private function getGeocodingUrl($address) {
167 global $globals;
168
169 $parameters = array(
170 'key' => $globals->geocoder->gmaps_key,
171 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
172 'hl' => 'fr', // Output langage.
173 'oe' => 'utf8', // Output encoding.
174 'output' => 'json', // Output format.
175 'gl' => 'fr', // Location preferences (addresses are in France by default).
176 'q' => $address, // The queries address.
177 );
178
179 return $globals->geocoder->gmaps_url . '?' . http_build_query($parameters);
180 }
181
182 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
183 // Returns the json array on success, and null otherwise.
184 private function getGeoJsonFromUrl($url) {
185 global $globals;
186
187 // Prepare a backtrace object to log errors.
188 $bt = null;
189 if ($globals->debug & DEBUG_BT) {
190 if (!isset(PlBacktrace::$bt['Geoloc'])) {
191 new PlBacktrace('Geoloc');
192 }
193 $bt = &PlBacktrace::$bt['Geoloc'];
194 $bt->start($url);
195 }
196
197 // Fetch the geocoding data.
198 $rawData = file_get_contents($url);
199 if (!$rawData) {
200 if ($bt) {
201 $bt->stop(0, "Could not retrieve geocoded address from GoogleMaps.");
202 }
203 return null;
204 }
205
206 // Decode the JSON-encoded data, and check for their validity.
207 $data = json_decode($rawData, true);
208 if ($bt) {
209 $bt->stop(count($data), null, $data);
210 }
211
212 return $data;
213 }
214
215 // Extracts the most appropriate placemark from the JSON data fetched from
216 // Google Maps. Returns a Placemark array on success, and null otherwise. See
217 // http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured
218 // for details on the Placemark structure.
219 private function getPlacemarkFromJson(array $data) {
220 // Check for geocoding failures.
221 if (!isset($data['Status']['code']) || $data['Status']['code'] != 200) {
222 // TODO: handle non-200 codes in a better way, since the code might
223 // indicate a temporary error on Google's side.
224 return null;
225 }
226
227 // Check that at least one placemark was found.
228 if (count($data['Placemark']) == 0) {
229 return null;
230 }
231
232 // Extract the placemark with the best accuracy. This is not always the
233 // best result (since the same address may yield two different placemarks).
234 $result = $data['Placemark'][0];
235 foreach ($data['Placemark'] as $place) {
236 if ($place['AddressDetails']['Accuracy'] > $result['AddressDetails']['Accuracy']) {
237 $result = $place;
238 }
239 }
240
241 return $result;
242 }
243
244 // Fills the address with the geocoded data
245 private function fillAddressWithGeocoding(&$address, $geocodedData) {
246 // The geocoded address three is
247 // Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
248 // with all the possible shortcuts
249 // The address is formatted as xAL, or eXtensible Address Language, an international
250 // standard for address formatting.
251 // xAL documentation: http://www.oasis-open.org/committees/ciq/ciq.html#6
252 $address['geoloc'] = str_replace(", ", "\n", $geocodedData['address']);
253 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
254 $address['accuracy'] = $geocodedData['AddressDetails']['Accuracy'];
255 }
256
257 $currentPosition = $geocodedData['AddressDetails'];
258 if (isset($currentPosition['Country'])) {
259 $currentPosition = $currentPosition['Country'];
260 $address['countryId'] = $currentPosition['CountryNameCode'];
261 $address['country'] = $currentPosition['CountryName'];
262 }
263 if (isset($currentPosition['AdministrativeArea'])) {
264 $currentPosition = $currentPosition['AdministrativeArea'];
265 $address['administrativeAreaName'] = $currentPosition['AdministrativeAreaName'];
266 }
267 if (isset($currentPosition['SubAdministrativeArea'])) {
268 $currentPosition = $currentPosition['SubAdministrativeArea'];
269 $address['subAdministrativeAreaName'] = $currentPosition['SubAdministrativeAreaName'];
270 }
271 if (isset($currentPosition['Locality'])) {
272 $currentPosition = $currentPosition['Locality'];
273 $address['localityName'] = $currentPosition['LocalityName'];
274 }
275 if (isset($currentPosition['Thoroughfare'])) {
276 $address['thoroughfareName'] = $currentPosition['Thoroughfare']['ThoroughfareName'];
277 }
278 if (isset($currentPosition['PostalCode'])) {
279 $address['postalCode'] = $currentPosition['PostalCode']['PostalCodeNumber'];
280 }
281
282 // Gets coordinates.
283 if (isset($geocodedData['Point']['coordinates'][0])) {
284 $address['latitude'] = $geocodedData['Point']['coordinates'][0];
285 }
286 if (isset($geocodedData['Point']['coordinates'][1])) {
287 $address['longitude'] = $geocodedData['Point']['coordinates'][1];
288 }
289 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
290 $address['north'] = $geocodedData['ExtendedData']['LatLonBox']['north'];
291 }
292 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
293 $address['south'] = $geocodedData['ExtendedData']['LatLonBox']['south'];
294 }
295 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
296 $address['east'] = $geocodedData['ExtendedData']['LatLonBox']['east'];
297 }
298 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
299 $address['west'] = $geocodedData['ExtendedData']['LatLonBox']['west'];
300 }
301 }
302
303 // Formats the text of the geocoded address using the unused data and
304 // compares it to the given address. If they are too different, the user
305 // will be asked to choose between them.
306 private function formatAddress(&$address, $extraLines) {
307 $same = true;
308 if ($extraLines) {
309 $address['geoloc'] = $extraLines . "\n" . $address['geoloc'];
310 }
311 $address['geocodedPostalText'] = $this->getPostalAddress($address['geoloc']);
312 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
313 array("", "\n"), $address['geoloc']));
314 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
315 array("", "\n"), $address['text']));
316 $arrayGeoloc = explode("\n", $geoloc);
317 $arrayText = explode("\n", $text);
318 $countGeoloc = count($arrayGeoloc);
319 $countText = count($arrayText);
320
321 $totalDistance = 0;
322 if (($countText > $countGeoloc) || ($countText < $countGeoloc - 1)
323 || (($countText == $countGeoloc - 1)
324 && ($arrayText[$countText - 1] == strtoupper($address['country'])))) {
325 $same = false;
326 } else {
327 for ($i = 0; $i < $countGeoloc && $i < $countText; ++$i) {
328 $lineDistance = levenshtein($arrayText[$i], trim($arrayGeoloc[$i]));
329 $totalDistance += $lineDistance;
330 if ($lineDistance > self::MAX_LINE_DISTANCE || $totalDistance > self::MAX_TOTAL_DISTANCE) {
331 $same = false;
332 break;
333 }
334 }
335 }
336
337 if ($same) {
338 unset($address['geoloc'], $address['geocodedPostalText']);
339 } else {
340 $address['geoloc'] = str_replace("\n", "\r\n", $address['geoloc']);
341 $address['geocodedPostalText'] = str_replace("\n", "\r\n", $address['geocodedPostalText']);
342 }
343 $address['text'] = str_replace("\n", "\r\n", $address['text']);
344 $address['postalText'] = str_replace("\n", "\r\n", $address['postalText']);
345 }
346
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
391 // Trims the name of the real country if it contains an ISO 3166-1 non-country
392 // item. For that purpose, we compare the last but one line of the address with
393 // all non-country items of ISO 3166-1.
394 private function getTextToGeocode($address)
395 {
396 $res = XDB::iterator('SELECT country, countryFR
397 FROM geoloc_countries
398 WHERE belongsTo IS NOT NULL');
399 $countries = array();
400 foreach ($res as $item) {
401 $countries[] = $item[0];
402 $countries[] = $item[1];
403 }
404 $textLines = explode("\n", $address['text']);
405 $countLines = count($textLines);
406 $needle = strtoupper(trim($textLines[$countLines - 2]));
407 $isPseudoCountry = false;
408 foreach ($countries as $country) {
409 if (strtoupper($country) == $needle) {
410 $isPseudoCountry = true;
411 break;
412 }
413 }
414
415 if ($isPseudoCountry) {
416 return implode("\n", array_slice($textLines, 0, -1));
417 }
418 return $address['text'];
419 }
420 }
421
422 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
423 ?>