Adds fields required for vcard in addresses.
[platal.git] / classes / gmapsgeocoder.php
CommitLineData
4c906759
SJ
1<?php
2/***************************************************************************
12262f13 3 * Copyright (C) 2003-2011 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
0f5f1b70
SJ
22// Implementation of a Geocoder using the Google Maps API v3. Please refer
23// to the following link for details:
24// http://code.google.com/apis/maps/documentation/geocoding/
4c906759 25//
0f5f1b70
SJ
26// It requires the properties gmaps_url to be defined in section Geocoder
27// in plat/al's configuration (platal.ini & platal.conf).
4c906759
SJ
28class GMapsGeocoder extends Geocoder {
29
30 // Maximum number of Geocoding calls to the Google Maps API.
31 const MAX_GMAPS_RPC_CALLS = 5;
32
26ba053e 33 public function getGeocodedAddress(Address $address, $defaultLanguage = null, $forceLanguage = false) {
4e7a3faa
SJ
34 $this->prepareAddress($address);
35 $textAddress = $this->getTextToGeocode($address->text);
2ffc0393 36 if (is_null($defaultLanguage)) {
0f5f1b70 37 $defaultLanguage = Platal::globals()->geocoder->gmaps_language;
2ffc0393 38 }
4c906759
SJ
39
40 // Try to geocode the full address.
2ffc0393
SJ
41 if (($geocodedData = $this->getPlacemarkForAddress($textAddress, $defaultLanguage))) {
42 $this->getUpdatedAddress($address, $geocodedData, null, $forceLanguage);
4e7a3faa 43 return;
4c906759
SJ
44 }
45
46 // If the full geocoding failed, try to geocode only the final part of the address.
47 // We start by geocoding everything but the first line, and continue until we get
48 // a result. To respect the limit of GMaps calls, we ignore the first few lines
49 // if there are too many address lines.
50 $addressLines = explode("\n", $textAddress);
51 $linesCount = count($addressLines);
52 for ($i = max(1, $linesCount - self::MAX_GMAPS_RPC_CALLS + 1); $i < $linesCount; ++$i) {
53 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
54 $toGeocode = implode("\n", array_slice($addressLines, $i));
2ffc0393
SJ
55 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode, $defaultLanguage))) {
56 $this->getUpdatedAddress($address, $geocodedData, $extraLines, $forceLanguage);
4e7a3faa 57 return;
4c906759
SJ
58 }
59 }
4c906759
SJ
60 }
61
26ba053e 62 public function stripGeocodingFromAddress(Address $address) {
0f5f1b70
SJ
63 $address->formatted_address = '';
64 $address->types = '';
65 $address->latitude = null;
66 $address->longitude = null;
67 $address->southwest_latitude = null;
68 $address->southwest_longitude = null;
69 $address->northeast_latitude = null;
70 $address->northeast_longitude = null;
71 $address->location_type = null;
72 $address->partial_match = false;
73f6c165 73 }
00e5200b 74
4c906759
SJ
75 // Updates the address with the geocoded information from Google Maps. Also
76 // cleans up the final informations.
26ba053e 77 private function getUpdatedAddress(Address $address, array $geocodedData, $extraLines, $forceLanguage) {
803612ae 78 $this->fillAddressWithGeocoding($address, $geocodedData, false);
2ffc0393 79 $this->formatAddress($address, $extraLines, $forceLanguage);
4c906759
SJ
80 }
81
82 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
83 // address, by querying the Google Maps API. Returns the array on success,
84 // and null otherwise.
2ffc0393 85 private function getPlacemarkForAddress($address, $defaultLanguage) {
803612ae 86 $url = $this->getGeocodingUrl($address, $defaultLanguage);
4c906759
SJ
87 $geoData = $this->getGeoJsonFromUrl($url);
88
0f5f1b70 89 return ($geoData ? $this->getPlacemarkFromJson($geoData, $url) : null);
4c906759
SJ
90 }
91
92 // Prepares address to be geocoded
26ba053e 93 private function prepareAddress(Address $address) {
4e7a3faa 94 $address->text = preg_replace('/\s*\n\s*/m', "\n", trim($address->text));
4c906759
SJ
95 }
96
97 // Builds the Google Maps geocoder url to fetch information about @p address.
98 // Returns the built url.
803612ae 99 private function getGeocodingUrl($address, $defaultLanguage) {
4c906759
SJ
100 global $globals;
101
102 $parameters = array(
0f5f1b70
SJ
103 'language' => $defaultLanguage,
104 'region' => $globals->geocoder->gmaps_region,
105 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
106 'address' => $address, // The queries address.
4c906759
SJ
107 );
108
0f5f1b70 109 return $globals->geocoder->gmaps_url . 'json?' . http_build_query($parameters);
4c906759
SJ
110 }
111
112 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
113 // Returns the json array on success, and null otherwise.
114 private function getGeoJsonFromUrl($url) {
115 global $globals;
116
117 // Prepare a backtrace object to log errors.
118 $bt = null;
119 if ($globals->debug & DEBUG_BT) {
120 if (!isset(PlBacktrace::$bt['Geoloc'])) {
121 new PlBacktrace('Geoloc');
122 }
123 $bt = &PlBacktrace::$bt['Geoloc'];
124 $bt->start($url);
125 }
126
127 // Fetch the geocoding data.
128 $rawData = file_get_contents($url);
129 if (!$rawData) {
130 if ($bt) {
4e7a3faa 131 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
4c906759
SJ
132 }
133 return null;
134 }
135
136 // Decode the JSON-encoded data, and check for their validity.
137 $data = json_decode($rawData, true);
138 if ($bt) {
139 $bt->stop(count($data), null, $data);
140 }
141
142 return $data;
143 }
144
145 // Extracts the most appropriate placemark from the JSON data fetched from
0f5f1b70
SJ
146 // Google Maps. Returns a Placemark array on success, and null otherwise.
147 // http://code.google.com/apis/maps/documentation/geocoding/#StatusCodes
148 private function getPlacemarkFromJson(array $data, $url) {
149 // Check for geocoding status.
150 $status = $data['status'];
151
152 // If no result, return null.
153 if ($status == 'ZERO_RESULTS') {
4c906759
SJ
154 return null;
155 }
156
0f5f1b70
SJ
157 // If there are results return the first one.
158 if ($status == 'OK') {
159 return $data['results'][0];
4c906759
SJ
160 }
161
0f5f1b70
SJ
162 // Report the error.
163 $mailer = new PlMailer('profile/geocoding.mail.tpl');
164 $mailer->assign('status', $status);
165 $mailer->assign('url', $url);
166 $mailer->send();
167 return null;
4c906759
SJ
168 }
169
170 // Fills the address with the geocoded data
26ba053e 171 private function fillAddressWithGeocoding(Address $address, $geocodedData, $isLocal) {
0f5f1b70
SJ
172 $address->types = implode(',', $geocodedData['types']);
173 $address->formatted_address = $geocodedData['formatted_address'];
174 $address->components = $geocodedData['address_components'];
175 $address->latitude = $geocodedData['geometry']['location']['lat'];
176 $address->longitude = $geocodedData['geometry']['location']['lng'];
177 $address->southwest_latitude = $geocodedData['geometry']['viewport']['southwest']['lat'];
178 $address->southwest_longitude = $geocodedData['geometry']['viewport']['southwest']['lng'];
179 $address->northeast_latitude = $geocodedData['geometry']['viewport']['northeast']['lat'];
180 $address->northeast_longitude = $geocodedData['geometry']['viewport']['northeast']['lng'];
181 $address->location_type = $geocodedData['geometry']['location_type'];
182 $address->partial_match = isset($geocodedData['partial_match']) ? true : false;
803612ae
SJ
183 }
184
185 // Formats the text of the geocoded address using the unused data and
186 // compares it to the given address. If they are too different, the user
187 // will be asked to choose between them.
26ba053e 188 private function formatAddress(Address $address, $extraLines, $forceLanguage)
803612ae 189 {
0f5f1b70
SJ
190 /* XXX: Check how to integrate this in the new geocoding system.
191 if (!$forceLanguage) {
2ffc0393 192 $languages = XDB::fetchOneCell('SELECT IF(ISNULL(gc1.belongsTo), gl1.language, gl2.language)
803612ae 193 FROM geoloc_countries AS gc1
2ffc0393 194 INNER JOIN geoloc_languages AS gl1 ON (gc1.iso_3166_1_a2 = gl1.iso_3166_1_a2)
803612ae 195 LEFT JOIN geoloc_countries AS gc2 ON (gc1.belongsTo = gc2.iso_3166_1_a2)
2ffc0393 196 LEFT JOIN geoloc_languages AS gl2 ON (gc2.iso_3166_1_a2 = gl2.iso_3166_1_a2)
803612ae
SJ
197 WHERE gc1.iso_3166_1_a2 = {?}',
198 $address->countryId);
199 $toGeocode = substr($address->text, strlen($extraLines));
200 foreach (explode(',', $languages) as $language) {
0f5f1b70 201 if ($language != Platal::globals()->geocoder->gmaps_language) {
803612ae 202 $geocodedData = $this->getPlacemarkForAddress($toGeocode, $language);
0f5f1b70
SJ
203 $this->fillAddressWithGeocoding($address, $geocodedData, true);
204 break;
803612ae
SJ
205 }
206 }
0f5f1b70 207 }*/
4e7a3faa 208 $address->text = str_replace("\n", "\r\n", $address->text);
5a10ab14
SJ
209 }
210
00e5200b
SJ
211 // Trims the name of the real country if it contains an ISO 3166-1 non-country
212 // item. For that purpose, we compare the last but one line of the address with
213 // all non-country items of ISO 3166-1.
4e7a3faa 214 private function getTextToGeocode($text)
00e5200b 215 {
1c305d4c 216 $res = XDB::iterator('SELECT countryEn, country
00e5200b
SJ
217 FROM geoloc_countries
218 WHERE belongsTo IS NOT NULL');
219 $countries = array();
220 foreach ($res as $item) {
221 $countries[] = $item[0];
222 $countries[] = $item[1];
223 }
4e7a3faa 224 $textLines = explode("\n", $text);
00e5200b
SJ
225 $countLines = count($textLines);
226 $needle = strtoupper(trim($textLines[$countLines - 2]));
227 $isPseudoCountry = false;
96c7ea54
SJ
228 if ($needle) {
229 foreach ($countries as $country) {
230 if (strtoupper($country) === $needle) {
231 $isPseudoCountry = true;
232 break;
233 }
00e5200b
SJ
234 }
235 }
236
237 if ($isPseudoCountry) {
02c4b93a 238 return implode("\n", array_slice($textLines, 0, -1));
00e5200b 239 }
4e7a3faa 240 return $text;
00e5200b 241 }
4c906759
SJ
242}
243
244// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
245?>