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;
59 * convert a name into a Location object
61 * @param string $name Name to convert
62 * @param string $language ISO code for anguage the name is in
63 * @param Location &$location Location object (may be null)
65 * @return boolean whether to continue (results in $location)
68 function onLocationFromName($name, $language, &$location)
70 $loc = $this->getCache(array('name' => $name,
71 'language' => $language));
78 $client = HTTPClient::start();
80 // XXX: break down a name by commas, narrow by each
82 $result = $client->get($this->wsUrl('search',
88 if ($result->isOk()) {
89 $rj = json_decode($result->getBody());
90 if (count($rj->geonames) > 0) {
91 $n = $rj->geonames[0];
93 $location = new Location();
95 $location->lat = $n->lat;
96 $location->lon = $n->lng;
97 $location->names[$language] = $n->name;
98 $location->location_id = $n->geonameId;
99 $location->location_ns = self::LOCATION_NS;
101 $this->setCache(array('name' => $name,
102 'language' => $language),
105 // handled, don't continue processing!
110 // Continue processing; we don't have the answer
115 * convert an id into a Location object
117 * @param string $id Name to convert
118 * @param string $ns Name to convert
119 * @param string $language ISO code for language for results
120 * @param Location &$location Location object (may be null)
122 * @return boolean whether to continue (results in $location)
125 function onLocationFromId($id, $ns, $language, &$location)
127 if ($ns != self::LOCATION_NS) {
128 // It's not one of our IDs... keep processing
132 $loc = $this->getCache(array('id' => $id));
139 $client = HTTPClient::start();
141 $result = $client->get($this->wsUrl('hierarchyJSON',
142 array('geonameId' => $id,
143 'lang' => $language)));
145 if ($result->isOk()) {
147 $rj = json_decode($result->getBody());
149 if (count($rj->geonames) > 0) {
153 foreach ($rj->geonames as $level) {
154 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
155 $parts[] = $level->name;
159 $last = $rj->geonames[count($rj->geonames)-1];
161 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
162 $parts[] = $last->name;
165 $location = new Location();
167 $location->location_id = $last->geonameId;
168 $location->location_ns = self::LOCATION_NS;
169 $location->lat = $last->lat;
170 $location->lon = $last->lng;
171 $location->names[$language] = implode(', ', array_reverse($parts));
173 $this->setCache(array('id' => $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 $loc = $this->getCache(array('lat' => $lat,
208 $client = HTTPClient::start();
211 $client->get($this->wsUrl('findNearbyPlaceNameJSON',
214 'lang' => $language)));
216 if ($result->isOk()) {
218 $rj = json_decode($result->getBody());
220 if (count($rj->geonames) > 0) {
222 $n = $rj->geonames[0];
226 $location = new Location();
230 if (!empty($n->adminName1)) {
231 $parts[] = $n->adminName1;
234 if (!empty($n->countryName)) {
235 $parts[] = $n->countryName;
238 $location->location_id = $n->geonameId;
239 $location->location_ns = self::LOCATION_NS;
240 $location->lat = $lat;
241 $location->lon = $lon;
243 $location->names[$language] = implode(', ', $parts);
245 $this->setCache(array('lat' => $lat,
249 // Success! We handled it, so no further processing
255 // For some reason we don't know, so pass.
261 * Human-readable name for a location
263 * Given a location, we try to retrieve a human-readable name
264 * in the target language.
266 * @param Location $location Location to get the name for
267 * @param string $language ISO code for language to find name in
268 * @param string &$name Place to put the name
270 * @return boolean whether to continue
273 function onLocationNameLanguage($location, $language, &$name)
275 if ($location->location_ns != self::LOCATION_NS) {
276 // It's not one of our IDs... keep processing
280 $n = $this->getCache(array('id' => $location->location_id,
281 'language' => $language));
288 $client = HTTPClient::start();
290 $result = $client->get($this->wsUrl('hierarchyJSON',
291 array('geonameId' => $location->location_id,
292 'lang' => $language)));
294 if ($result->isOk()) {
296 $rj = json_decode($result->getBody());
298 if (count($rj->geonames) > 0) {
302 foreach ($rj->geonames as $level) {
303 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
304 $parts[] = $level->name;
308 $last = $rj->geonames[count($rj->geonames)-1];
310 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
311 $parts[] = $last->name;
315 $name = implode(', ', array_reverse($parts));
316 $this->setCache(array('id' => $location->location_id,
317 'language' => $language),
328 * Human-readable name for a location
330 * Given a location, we try to retrieve a geonames.org URL.
332 * @param Location $location Location to get the url for
333 * @param string &$url Place to put the url
335 * @return boolean whether to continue
338 function onLocationUrl($location, &$url)
340 if ($location->location_ns != self::LOCATION_NS) {
341 // It's not one of our IDs... keep processing
345 $url = 'http://www.geonames.org/' . $location->location_id;
347 // it's been filled, so don't process further.
352 * Machine-readable name for a location
354 * Given a location, we try to retrieve a geonames.org URL.
356 * @param Location $location Location to get the url for
357 * @param string &$url Place to put the url
359 * @return boolean whether to continue
362 function onLocationRdfUrl($location, &$url)
364 if ($location->location_ns != self::LOCATION_NS) {
365 // It's not one of our IDs... keep processing
369 $url = 'http://sw.geonames.org/' . $location->location_id . '/';
371 // it's been filled, so don't process further.
375 function getCache($attrs)
377 $c = common_memcache();
383 return $c->get($this->cacheKey($attrs));
386 function setCache($attrs, $loc)
388 $c = common_memcache();
394 $c->set($this->cacheKey($attrs), $loc);
397 function clearCache($attrs)
399 $c = common_memcache();
405 $c->delete($this->cacheKey($attrs));
408 function cacheKey($attrs)
410 return common_cache_key('geonames:'.
411 implode(',', array_keys($attrs)) . ':'.
412 common_keyize(implode(',', array_values($attrs))));
415 function wsUrl($method, $params)
417 if (!empty($this->username)) {
418 $params['username'] = $this->username;
421 if (!empty($this->token)) {
422 $params['token'] = $this->token;
425 $str = http_build_query($params);
427 return 'http://'.$this->host.'/'.$method.'?'.$str;