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
58 public $cachePrefix = null; // Optional shared memcache prefix override
59 // to share lookups between local instances.
62 * convert a name into a Location object
64 * @param string $name Name to convert
65 * @param string $language ISO code for anguage the name is in
66 * @param Location &$location Location object (may be null)
68 * @return boolean whether to continue (results in $location)
71 function onLocationFromName($name, $language, &$location)
73 $loc = $this->getCache(array('name' => $name,
74 'language' => $language));
82 $geonames = $this->getGeonames('search',
87 } catch (Exception $e) {
88 $this->log(LOG_WARNING, "Error for $name: " . $e->getMessage());
92 if (count($geonames) == 0) {
94 $this->setCache(array('name' => $name,
95 'language' => $language),
102 $location = new Location();
104 $location->lat = $this->canonical($n->lat);
105 $location->lon = $this->canonical($n->lng);
106 $location->names[$language] = (string)$n->name;
107 $location->location_id = (string)$n->geonameId;
108 $location->location_ns = self::LOCATION_NS;
110 $this->setCache(array('name' => $name,
111 'language' => $language),
114 // handled, don't continue processing!
119 * convert an id into a Location object
121 * @param string $id Name to convert
122 * @param string $ns Name to convert
123 * @param string $language ISO code for language for results
124 * @param Location &$location Location object (may be null)
126 * @return boolean whether to continue (results in $location)
129 function onLocationFromId($id, $ns, $language, &$location)
131 if ($ns != self::LOCATION_NS) {
132 // It's not one of our IDs... keep processing
136 $loc = $this->getCache(array('id' => $id));
138 if ($loc !== false) {
144 $geonames = $this->getGeonames('hierarchy',
145 array('geonameId' => $id,
146 'lang' => $language));
147 } catch (Exception $e) {
148 $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
154 foreach ($geonames as $level) {
155 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
156 $parts[] = (string)$level->name;
160 $last = $geonames[count($geonames)-1];
162 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
163 $parts[] = (string)$last->name;
166 $location = new Location();
168 $location->location_id = (string)$last->geonameId;
169 $location->location_ns = self::LOCATION_NS;
170 $location->lat = $this->canonical($last->lat);
171 $location->lon = $this->canonical($last->lng);
173 $location->names[$language] = implode(', ', array_reverse($parts));
175 $this->setCache(array('id' => (string)$last->geonameId),
178 // We're responsible for this namespace; nobody else
185 * convert a lat/lon pair into a Location object
187 * Given a lat/lon, we try to find a Location that's around
188 * it or nearby. We prefer populated places (cities, towns, villages).
190 * @param string $lat Latitude
191 * @param string $lon Longitude
192 * @param string $language ISO code for language for results
193 * @param Location &$location Location object (may be null)
195 * @return boolean whether to continue (results in $location)
198 function onLocationFromLatLon($lat, $lon, $language, &$location)
200 // Make sure they're canonical
202 $lat = $this->canonical($lat);
203 $lon = $this->canonical($lon);
205 $loc = $this->getCache(array('lat' => $lat,
208 if ($loc !== false) {
214 $geonames = $this->getGeonames('findNearbyPlaceName',
217 'lang' => $language));
218 } catch (Exception $e) {
219 $this->log(LOG_WARNING, "Error for coords $lat, $lon: " . $e->getMessage());
223 if (count($geonames) == 0) {
225 $this->setCache(array('lat' => $lat,
235 $location = new Location();
237 $parts[] = (string)$n->name;
239 if (!empty($n->adminName1)) {
240 $parts[] = (string)$n->adminName1;
243 if (!empty($n->countryName)) {
244 $parts[] = (string)$n->countryName;
247 $location->location_id = (string)$n->geonameId;
248 $location->location_ns = self::LOCATION_NS;
249 $location->lat = $this->canonical($n->lat);
250 $location->lon = $this->canonical($n->lng);
252 $location->names[$language] = implode(', ', $parts);
254 $this->setCache(array('lat' => $lat,
258 // Success! We handled it, so no further processing
264 * Human-readable name for a location
266 * Given a location, we try to retrieve a human-readable name
267 * in the target language.
269 * @param Location $location Location to get the name for
270 * @param string $language ISO code for language to find name in
271 * @param string &$name Place to put the name
273 * @return boolean whether to continue
276 function onLocationNameLanguage($location, $language, &$name)
278 if ($location->location_ns != self::LOCATION_NS) {
279 // It's not one of our IDs... keep processing
283 $id = $location->location_id;
285 $n = $this->getCache(array('id' => $id,
286 'language' => $language));
294 $geonames = $this->getGeonames('hierarchy',
295 array('geonameId' => $id,
296 'lang' => $language));
297 } catch (Exception $e) {
298 $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
302 if (count($geonames) == 0) {
303 $this->setCache(array('id' => $id,
304 'language' => $language),
311 foreach ($geonames as $level) {
312 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
313 $parts[] = (string)$level->name;
317 $last = $geonames[count($geonames)-1];
319 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
320 $parts[] = (string)$last->name;
324 $name = implode(', ', array_reverse($parts));
325 $this->setCache(array('id' => $id,
326 'language' => $language),
334 * Human-readable URL for a location
336 * Given a location, we try to retrieve a geonames.org URL.
338 * @param Location $location Location to get the url for
339 * @param string &$url Place to put the url
341 * @return boolean whether to continue
344 function onLocationUrl($location, &$url)
346 if ($location->location_ns != self::LOCATION_NS) {
347 // It's not one of our IDs... keep processing
351 $url = 'http://www.geonames.org/' . $location->location_id;
353 // it's been filled, so don't process further.
358 * Machine-readable name for a location
360 * Given a location, we try to retrieve a geonames.org URL.
362 * @param Location $location Location to get the url for
363 * @param string &$url Place to put the url
365 * @return boolean whether to continue
368 function onLocationRdfUrl($location, &$url)
370 if ($location->location_ns != self::LOCATION_NS) {
371 // It's not one of our IDs... keep processing
375 $url = 'http://sw.geonames.org/' . $location->location_id . '/';
377 // it's been filled, so don't process further.
381 function getCache($attrs)
383 $c = common_memcache();
389 $key = $this->cacheKey($attrs);
391 $value = $c->get($key);
396 function setCache($attrs, $loc)
398 $c = common_memcache();
404 $key = $this->cacheKey($attrs);
406 $result = $c->set($key, $loc, 0, time() + $this->expiry);
411 function cacheKey($attrs)
414 implode(',', array_keys($attrs)) . ':'.
415 common_keyize(implode(',', array_values($attrs)));
416 if ($this->cachePrefix) {
417 return $this->cachePrefix . ':' . $key;
419 return common_cache_key($key);
423 function wsUrl($method, $params)
425 if (!empty($this->username)) {
426 $params['username'] = $this->username;
429 if (!empty($this->token)) {
430 $params['token'] = $this->token;
433 $str = http_build_query($params, null, '&');
435 return 'http://'.$this->host.'/'.$method.'?'.$str;
438 function getGeonames($method, $params)
440 $client = HTTPClient::start();
442 $result = $client->get($this->wsUrl($method, $params));
444 if (!$result->isOk()) {
445 throw new Exception("HTTP error code " . $result->code);
448 $body = $result->getBody();
451 throw new Exception("Empty HTTP body in response");
454 // This will throw an exception if the XML is mal-formed
456 $document = new SimpleXMLElement($body);
458 // No children, usually no results
460 $children = $document->children();
462 if (count($children) == 0) {
466 if (isset($document->status)) {
467 throw new Exception("Error #".$document->status['value']." ('".$document->status['message']."')");
470 // Array of elements, >0 elements
472 return $document->geoname;
475 function onPluginVersion(&$versions)
477 $versions[] = array('name' => 'Geonames',
478 'version' => STATUSNET_VERSION,
479 'author' => 'Evan Prodromou',
480 'homepage' => 'http://status.net/wiki/Plugin:Geonames',
482 _m('Uses <a href="http://geonames.org/">Geonames</a> service to get human-readable '.
483 'names for locations based on user-provided lat/long pairs.'));
487 function canonical($coord)
489 $coord = rtrim($coord, "0");
490 $coord = rtrim($coord, ".");