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 $this->log(LOG_WARNING, "Error code " . $result->code .
91 " from " . $this->host . " for $name");
95 $rj = json_decode($result->getBody());
97 if (count($rj->geonames) <= 0) {
98 $this->log(LOG_WARNING, "No results in response from " .
99 $this->host . " for $name");
103 $n = $rj->geonames[0];
105 $location = new Location();
107 $location->lat = $n->lat;
108 $location->lon = $n->lng;
109 $location->names[$language] = $n->name;
110 $location->location_id = $n->geonameId;
111 $location->location_ns = self::LOCATION_NS;
113 $this->setCache(array('name' => $name,
114 'language' => $language),
117 // handled, don't continue processing!
122 * convert an id into a Location object
124 * @param string $id Name to convert
125 * @param string $ns Name to convert
126 * @param string $language ISO code for language for results
127 * @param Location &$location Location object (may be null)
129 * @return boolean whether to continue (results in $location)
132 function onLocationFromId($id, $ns, $language, &$location)
134 if ($ns != self::LOCATION_NS) {
135 // It's not one of our IDs... keep processing
139 $loc = $this->getCache(array('id' => $id));
146 $client = HTTPClient::start();
148 $result = $client->get($this->wsUrl('hierarchyJSON',
149 array('geonameId' => $id,
150 'lang' => $language)));
152 if (!$result->isOk()) {
153 $this->log(LOG_WARNING,
154 "Error code " . $result->code .
155 " from " . $this->host . " for ID $id");
159 $rj = json_decode($result->getBody());
161 if (count($rj->geonames) <= 0) {
162 $this->log(LOG_WARNING,
163 "No results in response from " .
164 $this->host . " for ID $id");
170 foreach ($rj->geonames as $level) {
171 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
172 $parts[] = $level->name;
176 $last = $rj->geonames[count($rj->geonames)-1];
178 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
179 $parts[] = $last->name;
182 $location = new Location();
184 $location->location_id = $last->geonameId;
185 $location->location_ns = self::LOCATION_NS;
186 $location->lat = $last->lat;
187 $location->lon = $last->lng;
188 $location->names[$language] = implode(', ', array_reverse($parts));
190 $this->setCache(array('id' => $last->geonameId),
193 // We're responsible for this NAMESPACE; nobody else
200 * convert a lat/lon pair into a Location object
202 * Given a lat/lon, we try to find a Location that's around
203 * it or nearby. We prefer populated places (cities, towns, villages).
205 * @param string $lat Latitude
206 * @param string $lon Longitude
207 * @param string $language ISO code for language for results
208 * @param Location &$location Location object (may be null)
210 * @return boolean whether to continue (results in $location)
213 function onLocationFromLatLon($lat, $lon, $language, &$location)
215 $lat = rtrim($lat, "0");
216 $lon = rtrim($lon, "0");
218 $loc = $this->getCache(array('lat' => $lat,
226 $client = HTTPClient::start();
229 $client->get($this->wsUrl('findNearbyPlaceNameJSON',
232 'lang' => $language)));
234 if (!$result->isOk()) {
235 $this->log(LOG_WARNING,
236 "Error code " . $result->code .
237 " from " . $this->host . " for coords $lat, $lon");
241 $rj = json_decode($result->getBody());
243 if (count($rj->geonames) <= 0) {
244 $this->log(LOG_WARNING,
245 "No results in response from " .
246 $this->host . " for coords $lat, $lon");
250 $n = $rj->geonames[0];
254 $location = new Location();
258 if (!empty($n->adminName1)) {
259 $parts[] = $n->adminName1;
262 if (!empty($n->countryName)) {
263 $parts[] = $n->countryName;
266 $location->location_id = $n->geonameId;
267 $location->location_ns = self::LOCATION_NS;
268 $location->lat = $lat;
269 $location->lon = $lon;
271 $location->names[$language] = implode(', ', $parts);
273 $this->setCache(array('lat' => $lat,
277 // Success! We handled it, so no further processing
283 * Human-readable name for a location
285 * Given a location, we try to retrieve a human-readable name
286 * in the target language.
288 * @param Location $location Location to get the name for
289 * @param string $language ISO code for language to find name in
290 * @param string &$name Place to put the name
292 * @return boolean whether to continue
295 function onLocationNameLanguage($location, $language, &$name)
297 if ($location->location_ns != self::LOCATION_NS) {
298 // It's not one of our IDs... keep processing
302 $n = $this->getCache(array('id' => $location->location_id,
303 'language' => $language));
310 $client = HTTPClient::start();
312 $result = $client->get($this->wsUrl('hierarchyJSON',
313 array('geonameId' => $location->location_id,
314 'lang' => $language)));
316 if (!$result->isOk()) {
317 $this->log(LOG_WARNING,
318 "Error code " . $result->code .
319 " from " . $this->host . " for ID " . $location->location_id);
323 $rj = json_decode($result->getBody());
325 if (count($rj->geonames) <= 0) {
326 $this->log(LOG_WARNING,
328 " from " . $this->host . " for ID " . $location->location_id);
334 foreach ($rj->geonames as $level) {
335 if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
336 $parts[] = $level->name;
340 $last = $rj->geonames[count($rj->geonames)-1];
342 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
343 $parts[] = $last->name;
347 $name = implode(', ', array_reverse($parts));
348 $this->setCache(array('id' => $location->location_id,
349 'language' => $language),
357 * Human-readable name for a location
359 * Given a location, we try to retrieve a geonames.org URL.
361 * @param Location $location Location to get the url for
362 * @param string &$url Place to put the url
364 * @return boolean whether to continue
367 function onLocationUrl($location, &$url)
369 if ($location->location_ns != self::LOCATION_NS) {
370 // It's not one of our IDs... keep processing
374 $url = 'http://www.geonames.org/' . $location->location_id;
376 // it's been filled, so don't process further.
381 * Machine-readable name for a location
383 * Given a location, we try to retrieve a geonames.org URL.
385 * @param Location $location Location to get the url for
386 * @param string &$url Place to put the url
388 * @return boolean whether to continue
391 function onLocationRdfUrl($location, &$url)
393 if ($location->location_ns != self::LOCATION_NS) {
394 // It's not one of our IDs... keep processing
398 $url = 'http://sw.geonames.org/' . $location->location_id . '/';
400 // it's been filled, so don't process further.
404 function getCache($attrs)
406 $c = common_memcache();
412 $key = $this->cacheKey($attrs);
414 $value = $c->get($key);
419 function setCache($attrs, $loc)
421 $c = common_memcache();
427 $key = $this->cacheKey($attrs);
429 $result = $c->set($key, $loc, 0, time() + $this->expiry);
434 function cacheKey($attrs)
436 return common_cache_key('geonames:'.
437 implode(',', array_keys($attrs)) . ':'.
438 common_keyize(implode(',', array_values($attrs))));
441 function wsUrl($method, $params)
443 if (!empty($this->username)) {
444 $params['username'] = $this->username;
447 if (!empty($this->token)) {
448 $params['token'] = $this->token;
451 $str = http_build_query($params, null, '&');
453 return 'http://'.$this->host.'/'.$method.'?'.$str;