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