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());
90 if (count($geonames) == 0) {
92 $this->setCache(array('name' => $name,
93 'language' => $language),
100 $location = new Location();
102 $location->lat = $this->canonical($n->lat);
103 $location->lon = $this->canonical($n->lng);
104 $location->names[$language] = (string)$n->name;
105 $location->location_id = (string)$n->geonameId;
106 $location->location_ns = self::LOCATION_NS;
108 $this->setCache(array('name' => $name,
109 'language' => $language),
112 // handled, don't continue processing!
117 * convert an id into a Location object
119 * @param string $id Name to convert
120 * @param string $ns Name to convert
121 * @param string $language ISO code for language for results
122 * @param Location &$location Location object (may be null)
124 * @return boolean whether to continue (results in $location)
127 function onLocationFromId($id, $ns, $language, &$location)
129 if ($ns != self::LOCATION_NS) {
130 // It's not one of our IDs... keep processing
134 $loc = $this->getCache(array('id' => $id));
136 if ($loc !== false) {
142 $geonames = $this->getGeonames('hierarchy',
143 array('geonameId' => $id,
144 'lang' => $language));
145 } catch (Exception $e) {
146 $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
152 foreach ($geonames as $level) {
153 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
154 $parts[] = (string)$level->name;
158 $last = $geonames[count($geonames)-1];
160 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
161 $parts[] = (string)$last->name;
164 $location = new Location();
166 $location->location_id = (string)$last->geonameId;
167 $location->location_ns = self::LOCATION_NS;
168 $location->lat = $this->canonical($last->lat);
169 $location->lon = $this->canonical($last->lng);
171 $location->names[$language] = implode(', ', array_reverse($parts));
173 $this->setCache(array('id' => (string)$last->geonameId),
176 // We're responsible for this namespace; nobody else
183 * convert a lat/lon pair into a Location object
185 * Given a lat/lon, we try to find a Location that's around
186 * it or nearby. We prefer populated places (cities, towns, villages).
188 * @param string $lat Latitude
189 * @param string $lon Longitude
190 * @param string $language ISO code for language for results
191 * @param Location &$location Location object (may be null)
193 * @return boolean whether to continue (results in $location)
196 function onLocationFromLatLon($lat, $lon, $language, &$location)
198 // Make sure they're canonical
200 $lat = $this->canonical($lat);
201 $lon = $this->canonical($lon);
203 $loc = $this->getCache(array('lat' => $lat,
206 if ($loc !== false) {
212 $geonames = $this->getGeonames('findNearbyPlaceName',
215 'lang' => $language));
216 } catch (Exception $e) {
217 $this->log(LOG_WARNING, "Error for coords $lat, $lon: " . $e->getMessage());
221 if (count($geonames) == 0) {
223 $this->setCache(array('lat' => $lat,
233 $location = new Location();
235 $parts[] = (string)$n->name;
237 if (!empty($n->adminName1)) {
238 $parts[] = (string)$n->adminName1;
241 if (!empty($n->countryName)) {
242 $parts[] = (string)$n->countryName;
245 $location->location_id = (string)$n->geonameId;
246 $location->location_ns = self::LOCATION_NS;
247 $location->lat = $this->canonical($n->lat);
248 $location->lon = $this->canonical($n->lng);
250 $location->names[$language] = implode(', ', $parts);
252 $this->setCache(array('lat' => $lat,
256 // Success! We handled it, so no further processing
262 * Human-readable name for a location
264 * Given a location, we try to retrieve a human-readable name
265 * in the target language.
267 * @param Location $location Location to get the name for
268 * @param string $language ISO code for language to find name in
269 * @param string &$name Place to put the name
271 * @return boolean whether to continue
274 function onLocationNameLanguage($location, $language, &$name)
276 if ($location->location_ns != self::LOCATION_NS) {
277 // It's not one of our IDs... keep processing
281 $id = $location->location_id;
283 $n = $this->getCache(array('id' => $id,
284 'language' => $language));
292 $geonames = $this->getGeonames('hierarchy',
293 array('geonameId' => $id,
294 'lang' => $language));
295 } catch (Exception $e) {
296 $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
300 if (count($geonames) == 0) {
301 $this->setCache(array('id' => $id,
302 'language' => $language),
309 foreach ($geonames as $level) {
310 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
311 $parts[] = (string)$level->name;
315 $last = $geonames[count($geonames)-1];
317 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
318 $parts[] = (string)$last->name;
322 $name = implode(', ', array_reverse($parts));
323 $this->setCache(array('id' => $id,
324 'language' => $language),
332 * Human-readable URL for a location
334 * Given a location, we try to retrieve a geonames.org URL.
336 * @param Location $location Location to get the url for
337 * @param string &$url Place to put the url
339 * @return boolean whether to continue
342 function onLocationUrl($location, &$url)
344 if ($location->location_ns != self::LOCATION_NS) {
345 // It's not one of our IDs... keep processing
349 $url = 'http://www.geonames.org/' . $location->location_id;
351 // it's been filled, so don't process further.
356 * Machine-readable name for a location
358 * Given a location, we try to retrieve a geonames.org URL.
360 * @param Location $location Location to get the url for
361 * @param string &$url Place to put the url
363 * @return boolean whether to continue
366 function onLocationRdfUrl($location, &$url)
368 if ($location->location_ns != self::LOCATION_NS) {
369 // It's not one of our IDs... keep processing
373 $url = 'http://sw.geonames.org/' . $location->location_id . '/';
375 // it's been filled, so don't process further.
379 function getCache($attrs)
381 $c = common_memcache();
387 $key = $this->cacheKey($attrs);
389 $value = $c->get($key);
394 function setCache($attrs, $loc)
396 $c = common_memcache();
402 $key = $this->cacheKey($attrs);
404 $result = $c->set($key, $loc, 0, time() + $this->expiry);
409 function cacheKey($attrs)
411 return common_cache_key('geonames:'.
412 implode(',', array_keys($attrs)) . ':'.
413 common_keyize(implode(',', array_values($attrs))));
416 function wsUrl($method, $params)
418 if (!empty($this->username)) {
419 $params['username'] = $this->username;
422 if (!empty($this->token)) {
423 $params['token'] = $this->token;
426 $str = http_build_query($params, null, '&');
428 return 'http://'.$this->host.'/'.$method.'?'.$str;
431 function getGeonames($method, $params)
433 $client = HTTPClient::start();
435 $result = $client->get($this->wsUrl($method, $params));
437 if (!$result->isOk()) {
438 throw new Exception("HTTP error code " . $result->code);
441 $body = $result->getBody();
444 throw new Exception("Empty HTTP body in response");
447 // This will throw an exception if the XML is mal-formed
449 $document = new SimpleXMLElement($body);
451 // No children, usually no results
453 $children = $document->children();
455 if (count($children) == 0) {
459 if (isset($document->status)) {
460 throw new Exception("Error #".$document->status['value']." ('".$document->status['message']."')");
463 // Array of elements, >0 elements
465 return $document->geoname;
468 function onPluginVersion(&$versions)
470 $versions[] = array('name' => 'Geonames',
471 'version' => STATUSNET_VERSION,
472 'author' => 'Evan Prodromou',
473 'homepage' => 'http://status.net/wiki/Plugin:Geonames',
475 _m('Uses <a href="http://geonames.org/">Geonames</a> service to get human-readable '.
476 'names for locations based on user-provided lat/long pairs.'));
480 function canonical($coord)
482 $coord = rtrim($coord, "0");
483 $coord = rtrim($coord, ".");