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));
79 $client = HTTPClient::start();
81 // XXX: break down a name by commas, narrow by each
83 $result = $client->get($this->wsUrl('search',
89 if ($result->isOk()) {
90 $rj = json_decode($result->getBody());
91 if (count($rj->geonames) > 0) {
92 $n = $rj->geonames[0];
94 $location = new Location();
96 $location->lat = $n->lat;
97 $location->lon = $n->lng;
98 $location->names[$language] = $n->name;
99 $location->location_id = $n->geonameId;
100 $location->location_ns = self::LOCATION_NS;
102 $this->setCache(array('name' => $name,
103 'language' => $language),
106 // handled, don't continue processing!
111 // Continue processing; we don't have the answer
116 * convert an id into a Location object
118 * @param string $id Name to convert
119 * @param string $ns Name to convert
120 * @param string $language ISO code for language for results
121 * @param Location &$location Location object (may be null)
123 * @return boolean whether to continue (results in $location)
126 function onLocationFromId($id, $ns, $language, &$location)
128 if ($ns != self::LOCATION_NS) {
129 // It's not one of our IDs... keep processing
133 $loc = $this->getCache(array('id' => $id));
140 $client = HTTPClient::start();
142 $result = $client->get($this->wsUrl('hierarchyJSON',
143 array('geonameId' => $id,
144 'lang' => $language)));
146 if ($result->isOk()) {
148 $rj = json_decode($result->getBody());
150 if (count($rj->geonames) > 0) {
154 foreach ($rj->geonames as $level) {
155 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
156 $parts[] = $level->name;
160 $last = $rj->geonames[count($rj->geonames)-1];
162 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
163 $parts[] = $last->name;
166 $location = new Location();
168 $location->location_id = $last->geonameId;
169 $location->location_ns = self::LOCATION_NS;
170 $location->lat = $last->lat;
171 $location->lon = $last->lng;
172 $location->names[$language] = implode(', ', array_reverse($parts));
174 $this->setCache(array('id' => $last->geonameId),
179 // We're responsible for this NAMESPACE; nobody else
186 * convert a lat/lon pair into a Location object
188 * Given a lat/lon, we try to find a Location that's around
189 * it or nearby. We prefer populated places (cities, towns, villages).
191 * @param string $lat Latitude
192 * @param string $lon Longitude
193 * @param string $language ISO code for language for results
194 * @param Location &$location Location object (may be null)
196 * @return boolean whether to continue (results in $location)
199 function onLocationFromLatLon($lat, $lon, $language, &$location)
201 $lat = rtrim($lat, "0");
202 $lon = rtrim($lon, "0");
204 $loc = $this->getCache(array('lat' => $lat,
212 $client = HTTPClient::start();
215 $client->get($this->wsUrl('findNearbyPlaceNameJSON',
218 'lang' => $language)));
220 if ($result->isOk()) {
222 $rj = json_decode($result->getBody());
224 if (count($rj->geonames) > 0) {
226 $n = $rj->geonames[0];
230 $location = new Location();
234 if (!empty($n->adminName1)) {
235 $parts[] = $n->adminName1;
238 if (!empty($n->countryName)) {
239 $parts[] = $n->countryName;
242 $location->location_id = $n->geonameId;
243 $location->location_ns = self::LOCATION_NS;
244 $location->lat = $lat;
245 $location->lon = $lon;
247 $location->names[$language] = implode(', ', $parts);
249 $this->setCache(array('lat' => $lat,
253 // Success! We handled it, so no further processing
259 // For some reason we don't know, so pass.
265 * Human-readable name for a location
267 * Given a location, we try to retrieve a human-readable name
268 * in the target language.
270 * @param Location $location Location to get the name for
271 * @param string $language ISO code for language to find name in
272 * @param string &$name Place to put the name
274 * @return boolean whether to continue
277 function onLocationNameLanguage($location, $language, &$name)
279 if ($location->location_ns != self::LOCATION_NS) {
280 // It's not one of our IDs... keep processing
284 $n = $this->getCache(array('id' => $location->location_id,
285 'language' => $language));
292 $client = HTTPClient::start();
294 $result = $client->get($this->wsUrl('hierarchyJSON',
295 array('geonameId' => $location->location_id,
296 'lang' => $language)));
298 if ($result->isOk()) {
300 $rj = json_decode($result->getBody());
302 if (count($rj->geonames) > 0) {
306 foreach ($rj->geonames as $level) {
307 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
308 $parts[] = $level->name;
312 $last = $rj->geonames[count($rj->geonames)-1];
314 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
315 $parts[] = $last->name;
319 $name = implode(', ', array_reverse($parts));
320 $this->setCache(array('id' => $location->location_id,
321 'language' => $language),
332 * Human-readable name 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);
428 return 'http://'.$this->host.'/'.$method.'?'.$str;