3 * StatusNet, the distributed open-source microblogging tool
5 * Plugin to convert string locations to Geonames IDs and vice versa
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @copyright 2009 StatusNet Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
35 * Plugin to convert string locations to Geonames IDs and vice versa
37 * This handles most of the events that Location class emits. It uses
38 * the geonames.org Web service to convert names like 'Montreal, Quebec, Canada'
39 * into IDs and lat/lon pairs.
43 * @author Evan Prodromou <evan@status.net>
44 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45 * @link http://status.net/
50 class GeonamesPlugin extends Plugin
52 const LOCATION_NS = 1;
54 public $host = 'ws.geonames.org';
55 public $username = null;
57 public $expiry = 7776000; // 90-day expiry
60 * convert a name into a Location object
62 * @param string $name Name to convert
63 * @param string $language ISO code for anguage the name is in
64 * @param Location &$location Location object (may be null)
66 * @return boolean whether to continue (results in $location)
69 function onLocationFromName($name, $language, &$location)
71 $loc = $this->getCache(array('name' => $name,
72 'language' => $language));
80 $geonames = $this->getGeonames('search',
85 } catch (Exception $e) {
86 $this->log(LOG_WARNING, "Error for $name: " . $e->getMessage());
92 $location = new Location();
94 $location->lat = (string)$n->lat;
95 $location->lon = (string)$n->lng;
96 $location->names[$language] = (string)$n->name;
97 $location->location_id = (string)$n->geonameId;
98 $location->location_ns = self::LOCATION_NS;
100 $this->setCache(array('name' => $name,
101 'language' => $language),
104 // handled, don't continue processing!
109 * convert an id into a Location object
111 * @param string $id Name to convert
112 * @param string $ns Name to convert
113 * @param string $language ISO code for language for results
114 * @param Location &$location Location object (may be null)
116 * @return boolean whether to continue (results in $location)
119 function onLocationFromId($id, $ns, $language, &$location)
121 if ($ns != self::LOCATION_NS) {
122 // It's not one of our IDs... keep processing
126 $loc = $this->getCache(array('id' => $id));
134 $geonames = $this->getGeonames('hierarchy',
135 array('geonameId' => $id,
136 'lang' => $language));
137 } catch (Exception $e) {
138 $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
144 foreach ($geonames as $level) {
145 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
146 $parts[] = (string)$level->name;
150 $last = $geonames[count($geonames)-1];
152 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
153 $parts[] = (string)$last->name;
156 $location = new Location();
158 $location->location_id = (string)$last->geonameId;
159 $location->location_ns = self::LOCATION_NS;
160 $location->lat = (string)$last->lat;
161 $location->lon = (string)$last->lng;
162 $location->names[$language] = implode(', ', array_reverse($parts));
164 $this->setCache(array('id' => (string)$last->geonameId),
167 // We're responsible for this namespace; nobody else
174 * convert a lat/lon pair into a Location object
176 * Given a lat/lon, we try to find a Location that's around
177 * it or nearby. We prefer populated places (cities, towns, villages).
179 * @param string $lat Latitude
180 * @param string $lon Longitude
181 * @param string $language ISO code for language for results
182 * @param Location &$location Location object (may be null)
184 * @return boolean whether to continue (results in $location)
187 function onLocationFromLatLon($lat, $lon, $language, &$location)
189 $lat = rtrim($lat, "0");
190 $lon = rtrim($lon, "0");
192 $loc = $this->getCache(array('lat' => $lat,
201 $geonames = $this->getGeonames('findNearbyPlaceName',
204 'lang' => $language));
205 } catch (Exception $e) {
206 $this->log(LOG_WARNING, "Error for coords $lat, $lon: " . $e->getMessage());
214 $location = new Location();
216 $parts[] = (string)$n->name;
218 if (!empty($n->adminName1)) {
219 $parts[] = (string)$n->adminName1;
222 if (!empty($n->countryName)) {
223 $parts[] = (string)$n->countryName;
226 $location->location_id = (string)$n->geonameId;
227 $location->location_ns = self::LOCATION_NS;
228 $location->lat = (string)$lat;
229 $location->lon = (string)$lon;
231 $location->names[$language] = implode(', ', $parts);
233 $this->setCache(array('lat' => $lat,
237 // Success! We handled it, so no further processing
243 * Human-readable name for a location
245 * Given a location, we try to retrieve a human-readable name
246 * in the target language.
248 * @param Location $location Location to get the name for
249 * @param string $language ISO code for language to find name in
250 * @param string &$name Place to put the name
252 * @return boolean whether to continue
255 function onLocationNameLanguage($location, $language, &$name)
257 if ($location->location_ns != self::LOCATION_NS) {
258 // It's not one of our IDs... keep processing
262 $id = $location->location_id;
264 $n = $this->getCache(array('id' => $id,
265 'language' => $language));
273 $geonames = $this->getGeonames('hierarchy',
274 array('geonameId' => $id,
275 'lang' => $language));
276 } catch (Exception $e) {
277 $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
283 foreach ($geonames as $level) {
284 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
285 $parts[] = (string)$level->name;
289 $last = $geonames[count($geonames)-1];
291 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
292 $parts[] = (string)$last->name;
296 $name = implode(', ', array_reverse($parts));
297 $this->setCache(array('id' => $id,
298 'language' => $language),
306 * Human-readable URL for a location
308 * Given a location, we try to retrieve a geonames.org URL.
310 * @param Location $location Location to get the url for
311 * @param string &$url Place to put the url
313 * @return boolean whether to continue
316 function onLocationUrl($location, &$url)
318 if ($location->location_ns != self::LOCATION_NS) {
319 // It's not one of our IDs... keep processing
323 $url = 'http://www.geonames.org/' . $location->location_id;
325 // it's been filled, so don't process further.
330 * Machine-readable name for a location
332 * Given a location, we try to retrieve a geonames.org URL.
334 * @param Location $location Location to get the url for
335 * @param string &$url Place to put the url
337 * @return boolean whether to continue
340 function onLocationRdfUrl($location, &$url)
342 if ($location->location_ns != self::LOCATION_NS) {
343 // It's not one of our IDs... keep processing
347 $url = 'http://sw.geonames.org/' . $location->location_id . '/';
349 // it's been filled, so don't process further.
353 function getCache($attrs)
355 $c = common_memcache();
361 $key = $this->cacheKey($attrs);
363 $value = $c->get($key);
368 function setCache($attrs, $loc)
370 $c = common_memcache();
376 $key = $this->cacheKey($attrs);
378 $result = $c->set($key, $loc, 0, time() + $this->expiry);
383 function cacheKey($attrs)
385 return common_cache_key('geonames:'.
386 implode(',', array_keys($attrs)) . ':'.
387 common_keyize(implode(',', array_values($attrs))));
390 function wsUrl($method, $params)
392 if (!empty($this->username)) {
393 $params['username'] = $this->username;
396 if (!empty($this->token)) {
397 $params['token'] = $this->token;
400 $str = http_build_query($params, null, '&');
402 return 'http://'.$this->host.'/'.$method.'?'.$str;
405 function getGeonames($method, $params)
407 $client = HTTPClient::start();
409 $result = $client->get($this->wsUrl($method, $params));
411 if (!$result->isOk()) {
412 throw new Exception("HTTP error code " . $result->code);
415 $document = new SimpleXMLElement($result->getBody());
417 if (empty($document)) {
418 throw new Exception("No results in response");
421 if (isset($document->status)) {
422 throw new Exception("Error #".$document->status['value']." ('".$document->status['message']."')");
427 return $document->geoname;
430 function onPluginVersion(&$versions)
432 $versions[] = array('name' => 'Geonames',
433 'version' => STATUSNET_VERSION,
434 'author' => 'Evan Prodromou',
435 'homepage' => 'http://status.net/wiki/Plugin:Geonames',
437 _m('Uses <a href="http://geonames.org/">Geonames</a> service to get human-readable '.
438 'names for locations based on user-provided lat/long pairs.'));