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