]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/GeonamesPlugin.php
Merge branch 'sitemap' of gitorious.org:~evan/statusnet/evans-mainline into sitemap
[quix0rs-gnu-social.git] / plugins / GeonamesPlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Plugin to convert string locations to Geonames IDs and vice versa
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  Action
23  * @package   StatusNet
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/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 /**
35  * Plugin to convert string locations to Geonames IDs and vice versa
36  *
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.
40  *
41  * @category Plugin
42  * @package  StatusNet
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/
46  *
47  * @seeAlso  Location
48  */
49
50 class GeonamesPlugin extends Plugin
51 {
52     const LOCATION_NS = 1;
53
54     public $host     = 'ws.geonames.org';
55     public $username = null;
56     public $token    = null;
57     public $expiry   = 7776000; // 90-day expiry
58     public $timeout  = 2;       // Web service timeout in seconds.
59     public $timeoutWindow = 60; // Further lookups in this process will be disabled for N seconds after a timeout.
60     public $cachePrefix = null; // Optional shared memcache prefix override
61                                 // to share lookups between local instances.
62
63     protected $lastTimeout = null; // timestamp of last web service timeout
64
65     /**
66      * convert a name into a Location object
67      *
68      * @param string   $name      Name to convert
69      * @param string   $language  ISO code for anguage the name is in
70      * @param Location &$location Location object (may be null)
71      *
72      * @return boolean whether to continue (results in $location)
73      */
74
75     function onLocationFromName($name, $language, &$location)
76     {
77         $loc = $this->getCache(array('name' => $name,
78                                      'language' => $language));
79
80         if ($loc !== false) {
81             $location = $loc;
82             return false;
83         }
84
85         try {
86             $geonames = $this->getGeonames('search',
87                                            array('maxRows' => 1,
88                                                  'q' => $name,
89                                                  'lang' => $language,
90                                                  'type' => 'xml'));
91         } catch (Exception $e) {
92             $this->log(LOG_WARNING, "Error for $name: " . $e->getMessage());
93             return true;
94         }
95
96         if (count($geonames) == 0) {
97             // no results
98             $this->setCache(array('name' => $name,
99                                   'language' => $language),
100                             null);
101             return true;
102         }
103
104         $n = $geonames[0];
105
106         $location = new Location();
107
108         $location->lat              = $this->canonical($n->lat);
109         $location->lon              = $this->canonical($n->lng);
110         $location->names[$language] = (string)$n->name;
111         $location->location_id      = (string)$n->geonameId;
112         $location->location_ns      = self::LOCATION_NS;
113
114         $this->setCache(array('name' => $name,
115                               'language' => $language),
116                         $location);
117
118         // handled, don't continue processing!
119         return false;
120     }
121
122     /**
123      * convert an id into a Location object
124      *
125      * @param string   $id        Name to convert
126      * @param string   $ns        Name to convert
127      * @param string   $language  ISO code for language for results
128      * @param Location &$location Location object (may be null)
129      *
130      * @return boolean whether to continue (results in $location)
131      */
132
133     function onLocationFromId($id, $ns, $language, &$location)
134     {
135         if ($ns != self::LOCATION_NS) {
136             // It's not one of our IDs... keep processing
137             return true;
138         }
139
140         $loc = $this->getCache(array('id' => $id));
141
142         if ($loc !== false) {
143             $location = $loc;
144             return false;
145         }
146
147         try {
148             $geonames = $this->getGeonames('hierarchy',
149                                            array('geonameId' => $id,
150                                                  'lang' => $language));
151         } catch (Exception $e) {
152             $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
153             return false;
154         }
155
156         $parts = array();
157
158         foreach ($geonames as $level) {
159             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
160                 $parts[] = (string)$level->name;
161             }
162         }
163
164         $last = $geonames[count($geonames)-1];
165
166         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
167             $parts[] = (string)$last->name;
168         }
169
170         $location = new Location();
171
172         $location->location_id      = (string)$last->geonameId;
173         $location->location_ns      = self::LOCATION_NS;
174         $location->lat              = $this->canonical($last->lat);
175         $location->lon              = $this->canonical($last->lng);
176
177         $location->names[$language] = implode(', ', array_reverse($parts));
178
179         $this->setCache(array('id' => (string)$last->geonameId),
180                         $location);
181
182         // We're responsible for this namespace; nobody else
183         // can resolve it
184
185         return false;
186     }
187
188     /**
189      * convert a lat/lon pair into a Location object
190      *
191      * Given a lat/lon, we try to find a Location that's around
192      * it or nearby. We prefer populated places (cities, towns, villages).
193      *
194      * @param string   $lat       Latitude
195      * @param string   $lon       Longitude
196      * @param string   $language  ISO code for language for results
197      * @param Location &$location Location object (may be null)
198      *
199      * @return boolean whether to continue (results in $location)
200      */
201
202     function onLocationFromLatLon($lat, $lon, $language, &$location)
203     {
204         // Make sure they're canonical
205
206         $lat = $this->canonical($lat);
207         $lon = $this->canonical($lon);
208
209         $loc = $this->getCache(array('lat' => $lat,
210                                      'lon' => $lon));
211
212         if ($loc !== false) {
213             $location = $loc;
214             return false;
215         }
216
217         try {
218           $geonames = $this->getGeonames('findNearbyPlaceName',
219                                          array('lat' => $lat,
220                                                'lng' => $lon,
221                                                'lang' => $language));
222         } catch (Exception $e) {
223             $this->log(LOG_WARNING, "Error for coords $lat, $lon: " . $e->getMessage());
224             return true;
225         }
226
227         if (count($geonames) == 0) {
228             // no results
229             $this->setCache(array('lat' => $lat,
230                                   'lon' => $lon),
231                             null);
232             return true;
233         }
234
235         $n = $geonames[0];
236
237         $parts = array();
238
239         $location = new Location();
240
241         $parts[] = (string)$n->name;
242
243         if (!empty($n->adminName1)) {
244             $parts[] = (string)$n->adminName1;
245         }
246
247         if (!empty($n->countryName)) {
248             $parts[] = (string)$n->countryName;
249         }
250
251         $location->location_id = (string)$n->geonameId;
252         $location->location_ns = self::LOCATION_NS;
253         $location->lat         = $this->canonical($n->lat);
254         $location->lon         = $this->canonical($n->lng);
255
256         $location->names[$language] = implode(', ', $parts);
257
258         $this->setCache(array('lat' => $lat,
259                               'lon' => $lon),
260                         $location);
261
262         // Success! We handled it, so no further processing
263
264         return false;
265     }
266
267     /**
268      * Human-readable name for a location
269      *
270      * Given a location, we try to retrieve a human-readable name
271      * in the target language.
272      *
273      * @param Location $location Location to get the name for
274      * @param string   $language ISO code for language to find name in
275      * @param string   &$name    Place to put the name
276      *
277      * @return boolean whether to continue
278      */
279
280     function onLocationNameLanguage($location, $language, &$name)
281     {
282         if ($location->location_ns != self::LOCATION_NS) {
283             // It's not one of our IDs... keep processing
284             return true;
285         }
286
287         $id = $location->location_id;
288
289         $n = $this->getCache(array('id' => $id,
290                                    'language' => $language));
291
292         if ($n !== false) {
293             $name = $n;
294             return false;
295         }
296
297         try {
298             $geonames = $this->getGeonames('hierarchy',
299                                            array('geonameId' => $id,
300                                                  'lang' => $language));
301         } catch (Exception $e) {
302             $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
303             return false;
304         }
305
306         if (count($geonames) == 0) {
307             $this->setCache(array('id' => $id,
308                                   'language' => $language),
309                             null);
310             return false;
311         }
312
313         $parts = array();
314
315         foreach ($geonames as $level) {
316             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
317                 $parts[] = (string)$level->name;
318             }
319         }
320
321         $last = $geonames[count($geonames)-1];
322
323         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
324             $parts[] = (string)$last->name;
325         }
326
327         if (count($parts)) {
328             $name = implode(', ', array_reverse($parts));
329             $this->setCache(array('id' => $id,
330                                   'language' => $language),
331                             $name);
332         }
333
334         return false;
335     }
336
337     /**
338      * Human-readable URL for a location
339      *
340      * Given a location, we try to retrieve a geonames.org URL.
341      *
342      * @param Location $location Location to get the url for
343      * @param string   &$url     Place to put the url
344      *
345      * @return boolean whether to continue
346      */
347
348     function onLocationUrl($location, &$url)
349     {
350         if ($location->location_ns != self::LOCATION_NS) {
351             // It's not one of our IDs... keep processing
352             return true;
353         }
354
355         $url = 'http://www.geonames.org/' . $location->location_id;
356
357         // it's been filled, so don't process further.
358         return false;
359     }
360
361     /**
362      * Machine-readable name for a location
363      *
364      * Given a location, we try to retrieve a geonames.org URL.
365      *
366      * @param Location $location Location to get the url for
367      * @param string   &$url     Place to put the url
368      *
369      * @return boolean whether to continue
370      */
371
372     function onLocationRdfUrl($location, &$url)
373     {
374         if ($location->location_ns != self::LOCATION_NS) {
375             // It's not one of our IDs... keep processing
376             return true;
377         }
378
379         $url = 'http://sw.geonames.org/' . $location->location_id . '/';
380
381         // it's been filled, so don't process further.
382         return false;
383     }
384
385     function getCache($attrs)
386     {
387         $c = common_memcache();
388
389         if (empty($c)) {
390             return null;
391         }
392
393         $key = $this->cacheKey($attrs);
394
395         $value = $c->get($key);
396
397         return $value;
398     }
399
400     function setCache($attrs, $loc)
401     {
402         $c = common_memcache();
403
404         if (empty($c)) {
405             return null;
406         }
407
408         $key = $this->cacheKey($attrs);
409
410         $result = $c->set($key, $loc, 0, time() + $this->expiry);
411
412         return $result;
413     }
414
415     function cacheKey($attrs)
416     {
417         $key = 'geonames:' .
418                implode(',', array_keys($attrs)) . ':'.
419                common_keyize(implode(',', array_values($attrs)));
420         if ($this->cachePrefix) {
421             return $this->cachePrefix . ':' . $key;
422         } else {
423             return common_cache_key($key);
424         }
425     }
426
427     function wsUrl($method, $params)
428     {
429         if (!empty($this->username)) {
430             $params['username'] = $this->username;
431         }
432
433         if (!empty($this->token)) {
434             $params['token'] = $this->token;
435         }
436
437         $str = http_build_query($params, null, '&');
438
439         return 'http://'.$this->host.'/'.$method.'?'.$str;
440     }
441
442     function getGeonames($method, $params)
443     {
444         if ($this->lastTimeout && (time() - $this->lastTimeout < $this->timeoutWindow)) {
445             throw new Exception("skipping due to recent web service timeout");
446         }
447
448         $client = HTTPClient::start();
449         $client->setConfig('connect_timeout', $this->timeout);
450         $client->setConfig('timeout', $this->timeout);
451
452         try {
453             $result = $client->get($this->wsUrl($method, $params));
454         } catch (Exception $e) {
455             common_log(LOG_ERR, __METHOD__ . ": " . $e->getMessage());
456             $this->lastTimeout = time();
457             throw $e;
458         }
459
460         if (!$result->isOk()) {
461             throw new Exception("HTTP error code " . $result->getStatus());
462         }
463
464         $body = $result->getBody();
465
466         if (empty($body)) {
467             throw new Exception("Empty HTTP body in response");
468         }
469
470         // This will throw an exception if the XML is mal-formed
471
472         $document = new SimpleXMLElement($body);
473
474         // No children, usually no results
475
476         $children = $document->children();
477
478         if (count($children) == 0) {
479             return array();
480         }
481
482         if (isset($document->status)) {
483             throw new Exception("Error #".$document->status['value']." ('".$document->status['message']."')");
484         }
485
486         // Array of elements, >0 elements
487
488         return $document->geoname;
489     }
490
491     function onPluginVersion(&$versions)
492     {
493         $versions[] = array('name' => 'Geonames',
494                             'version' => STATUSNET_VERSION,
495                             'author' => 'Evan Prodromou',
496                             'homepage' => 'http://status.net/wiki/Plugin:Geonames',
497                             'rawdescription' =>
498                             _m('Uses <a href="http://geonames.org/">Geonames</a> service to get human-readable '.
499                                'names for locations based on user-provided lat/long pairs.'));
500         return true;
501     }
502
503     function canonical($coord)
504     {
505         $coord = rtrim($coord, "0");
506         $coord = rtrim($coord, ".");
507
508         return $coord;
509     }
510 }