Do not force addresses to be translated into French.
[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->geocodedPostalText = null;
68 $address->geoloc_choice = null;
69 $address->countryId = null;
70 $address->country = null;
71 $address->administrativeAreaName = null;
72 $address->subAdministrativeAreaName = null;
73 $address->localityName = null;
74 $address->thoroughfareName = null;
75 $address->postalCode = null;
76 $address->accuracy = 0;
77 }
78
79 // Updates the address with the geocoded information from Google Maps. Also
80 // cleans up the final informations.
81 private function getUpdatedAddress(Address &$address, array $geocodedData, $extraLines) {
82 $this->fillAddressWithGeocoding($address, $geocodedData);
83 $this->formatAddress($address, $extraLines);
84 }
85
86 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
87 // address, by querying the Google Maps API. Returns the array on success,
88 // and null otherwise.
89 private function getPlacemarkForAddress($address) {
90 $url = $this->getGeocodingUrl($address);
91 $geoData = $this->getGeoJsonFromUrl($url);
92
93 return ($geoData ? $this->getPlacemarkFromJson($geoData) : null);
94 }
95
96 // Prepares address to be geocoded
97 private function prepareAddress(Address &$address) {
98 $address->text = preg_replace('/\s*\n\s*/m', "\n", trim($address->text));
99 $address->postalText = $this->getPostalAddress($address->text);
100 }
101
102 // Builds the Google Maps geocoder url to fetch information about @p address.
103 // Returns the built url.
104 private function getGeocodingUrl($address) {
105 global $globals;
106
107 $parameters = array(
108 'key' => $globals->geocoder->gmaps_key,
109 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
110 'oe' => 'utf8', // Output encoding.
111 'output' => 'json', // Output format.
112 'gl' => 'fr', // Location preferences (addresses are in France by default).
113 'q' => $address, // The queries address.
114 );
115
116 return $globals->geocoder->gmaps_url . '?' . http_build_query($parameters);
117 }
118
119 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
120 // Returns the json array on success, and null otherwise.
121 private function getGeoJsonFromUrl($url) {
122 global $globals;
123
124 // Prepare a backtrace object to log errors.
125 $bt = null;
126 if ($globals->debug & DEBUG_BT) {
127 if (!isset(PlBacktrace::$bt['Geoloc'])) {
128 new PlBacktrace('Geoloc');
129 }
130 $bt = &PlBacktrace::$bt['Geoloc'];
131 $bt->start($url);
132 }
133
134 // Fetch the geocoding data.
135 $rawData = file_get_contents($url);
136 if (!$rawData) {
137 if ($bt) {
138 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
139 }
140 return null;
141 }
142
143 // Decode the JSON-encoded data, and check for their validity.
144 $data = json_decode($rawData, true);
145 if ($bt) {
146 $bt->stop(count($data), null, $data);
147 }
148
149 return $data;
150 }
151
152 // Extracts the most appropriate placemark from the JSON data fetched from
153 // Google Maps. Returns a Placemark array on success, and null otherwise. See
154 // http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured
155 // for details on the Placemark structure.
156 private function getPlacemarkFromJson(array $data) {
157 // Check for geocoding failures.
158 if (!isset($data['Status']['code']) || $data['Status']['code'] != 200) {
159 // TODO: handle non-200 codes in a better way, since the code might
160 // indicate a temporary error on Google's side.
161 return null;
162 }
163
164 // Check that at least one placemark was found.
165 if (count($data['Placemark']) == 0) {
166 return null;
167 }
168
169 // Extract the placemark with the best accuracy. This is not always the
170 // best result (since the same address may yield two different placemarks).
171 $result = $data['Placemark'][0];
172 foreach ($data['Placemark'] as $place) {
173 if ($place['AddressDetails']['Accuracy'] > $result['AddressDetails']['Accuracy']) {
174 $result = $place;
175 }
176 }
177
178 return $result;
179 }
180
181 // Fills the address with the geocoded data
182 private function fillAddressWithGeocoding(Address &$address, $geocodedData) {
183 // The geocoded address three is
184 // Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
185 // with all the possible shortcuts
186 // The address is formatted as xAL, or eXtensible Address Language, an international
187 // standard for address formatting.
188 // xAL documentation: http://www.oasis-open.org/committees/ciq/ciq.html#6
189 $address->geocodedText = str_replace(', ', "\n", $geocodedData['address']);
190 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
191 $address->accuracy = $geocodedData['AddressDetails']['Accuracy'];
192 }
193
194 $currentPosition = $geocodedData['AddressDetails'];
195 if (isset($currentPosition['Country'])) {
196 $currentPosition = $currentPosition['Country'];
197 $address->countryId = $currentPosition['CountryNameCode'];
198 $address->country = $currentPosition['CountryName'];
199 }
200 if (isset($currentPosition['AdministrativeArea'])) {
201 $currentPosition = $currentPosition['AdministrativeArea'];
202 $address->administrativeAreaName = $currentPosition['AdministrativeAreaName'];
203 }
204 if (isset($currentPosition['SubAdministrativeArea'])) {
205 $currentPosition = $currentPosition['SubAdministrativeArea'];
206 $address->subAdministrativeAreaName = $currentPosition['SubAdministrativeAreaName'];
207 }
208 if (isset($currentPosition['Locality'])) {
209 $currentPosition = $currentPosition['Locality'];
210 $address->localityName = $currentPosition['LocalityName'];
211 }
212 if (isset($currentPosition['Thoroughfare'])) {
213 $address->thoroughfareName = $currentPosition['Thoroughfare']['ThoroughfareName'];
214 }
215 if (isset($currentPosition['PostalCode'])) {
216 $address->postalCode = $currentPosition['PostalCode']['PostalCodeNumber'];
217 }
218
219 // Gets coordinates.
220 if (isset($geocodedData['Point']['coordinates'][0])) {
221 $address->latitude = $geocodedData['Point']['coordinates'][0];
222 }
223 if (isset($geocodedData['Point']['coordinates'][1])) {
224 $address->longitude = $geocodedData['Point']['coordinates'][1];
225 }
226 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
227 $address->north = $geocodedData['ExtendedData']['LatLonBox']['north'];
228 }
229 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
230 $address->south = $geocodedData['ExtendedData']['LatLonBox']['south'];
231 }
232 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
233 $address->east = $geocodedData['ExtendedData']['LatLonBox']['east'];
234 }
235 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
236 $address->west = $geocodedData['ExtendedData']['LatLonBox']['west'];
237 }
238 }
239
240 // Formats the text of the geocoded address using the unused data and
241 // compares it to the given address. If they are too different, the user
242 // will be asked to choose between them.
243 private function formatAddress(Address &$address, $extraLines) {
244 $same = true;
245 if ($extraLines) {
246 $address->geocodedText = $extraLines . "\n" . $address->geocodedText;
247 }
248 $address->geocodedPostalText = $this->getPostalAddress($address->geocodedText);
249 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
250 array('', "\n"), $address->geocodedText));
251 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
252 array('', "\n"), $address->text));
253 $arrayGeoloc = explode("\n", $geoloc);
254 $arrayText = explode("\n", $text);
255 $countGeoloc = count($arrayGeoloc);
256 $countText = count($arrayText);
257
258 $totalDistance = 0;
259 if (($countText > $countGeoloc) || ($countText < $countGeoloc - 1)
260 || (($countText == $countGeoloc - 1)
261 && ($arrayText[$countText - 1] == strtoupper($address->country)))) {
262 $same = false;
263 } else {
264 for ($i = 0; $i < $countGeoloc && $i < $countText; ++$i) {
265 $lineDistance = levenshtein($arrayText[$i], trim($arrayGeoloc[$i]));
266 $totalDistance += $lineDistance;
267 if ($lineDistance > self::MAX_LINE_DISTANCE || $totalDistance > self::MAX_TOTAL_DISTANCE) {
268 $same = false;
269 break;
270 }
271 }
272 }
273
274 if ($same) {
275 $address->geocodedText = null;
276 $address->geocodedPostalText = null;
277 } else {
278 $address->geocodedText = str_replace("\n", "\r\n", $address->geocodedText);
279 $address->geocodedPostalText = str_replace("\n", "\r\n", $address->geocodedPostalText);
280 }
281 $address->text = str_replace("\n", "\r\n", $address->text);
282 $address->postalText = str_replace("\n", "\r\n", $address->postalText);
283 }
284
285 // Returns the address formated for postal use.
286 // The main rules are (cf AFNOR XPZ 10-011):
287 // -everything in upper case;
288 // -if there are more then than 38 characters in a line, split it;
289 // -if there are more then than 32 characters in the description of the "street", use abbreviations.
290 private function getPostalAddress($text) {
291 static $abbreviations = array(
292 'IMPASSE' => 'IMP',
293 'RUE' => 'R',
294 'AVENUE' => 'AV',
295 'BOULEVARD' => 'BVD',
296 'ROUTE' => 'R',
297 'STREET' => 'ST',
298 'ROAD' => 'RD',
299 );
300
301 $text = strtoupper($text);
302 $arrayText = explode("\n", $text);
303 $postalText = '';
304
305 foreach ($arrayText as $i => $line) {
306 $postalText .= (($i == 0) ? '' : "\n");
307 if (($length = strlen($line)) > 32) {
308 $words = explode(' ', $line);
309 $count = 0;
310 foreach ($words as $word) {
311 if (isset($abbreviations[$word])) {
312 $word = $abbreviations[$word];
313 }
314 if ($count + ($wordLength = strlen($word)) <= 38) {
315 $postalText .= (($count == 0) ? '' : ' ') . $word;
316 $count += (($count == 0) ? 0 : 1) + $wordLength;
317 } else {
318 $postalText .= "\n" . $word;
319 $count = strlen($word);
320 }
321 }
322 } else {
323 $postalText .= $line;
324 }
325 }
326 return $postalText;
327 }
328
329 // Trims the name of the real country if it contains an ISO 3166-1 non-country
330 // item. For that purpose, we compare the last but one line of the address with
331 // all non-country items of ISO 3166-1.
332 private function getTextToGeocode($text)
333 {
334 $res = XDB::iterator('SELECT country, countryFR
335 FROM geoloc_countries
336 WHERE belongsTo IS NOT NULL');
337 $countries = array();
338 foreach ($res as $item) {
339 $countries[] = $item[0];
340 $countries[] = $item[1];
341 }
342 $textLines = explode("\n", $text);
343 $countLines = count($textLines);
344 $needle = strtoupper(trim($textLines[$countLines - 2]));
345 $isPseudoCountry = false;
346 foreach ($countries as $country) {
347 if (strtoupper($country) == $needle) {
348 $isPseudoCountry = true;
349 break;
350 }
351 }
352
353 if ($isPseudoCountry) {
354 return implode("\n", array_slice($textLines, 0, -1));
355 }
356 return $text;
357 }
358 }
359
360 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
361 ?>