]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/GeonamesPlugin.php
Shared cache key option for Geonames plugin, lets multi-instance sites share their...
[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 $cachePrefix = null; // Optional shared memcache prefix override
59                                 // to share lookups between local instances.
60
61     /**
62      * convert a name into a Location object
63      *
64      * @param string   $name      Name to convert
65      * @param string   $language  ISO code for anguage the name is in
66      * @param Location &$location Location object (may be null)
67      *
68      * @return boolean whether to continue (results in $location)
69      */
70
71     function onLocationFromName($name, $language, &$location)
72     {
73         $loc = $this->getCache(array('name' => $name,
74                                      'language' => $language));
75
76         if ($loc !== false) {
77             $location = $loc;
78             return false;
79         }
80
81         try {
82             $geonames = $this->getGeonames('search',
83                                            array('maxRows' => 1,
84                                                  'q' => $name,
85                                                  'lang' => $language,
86                                                  'type' => 'xml'));
87         } catch (Exception $e) {
88             $this->log(LOG_WARNING, "Error for $name: " . $e->getMessage());
89             return true;
90         }
91
92         if (count($geonames) == 0) {
93             // no results
94             $this->setCache(array('name' => $name,
95                                   'language' => $language),
96                             null);
97             return true;
98         }
99
100         $n = $geonames[0];
101
102         $location = new Location();
103
104         $location->lat              = $this->canonical($n->lat);
105         $location->lon              = $this->canonical($n->lng);
106         $location->names[$language] = (string)$n->name;
107         $location->location_id      = (string)$n->geonameId;
108         $location->location_ns      = self::LOCATION_NS;
109
110         $this->setCache(array('name' => $name,
111                               'language' => $language),
112                         $location);
113
114         // handled, don't continue processing!
115         return false;
116     }
117
118     /**
119      * convert an id into a Location object
120      *
121      * @param string   $id        Name to convert
122      * @param string   $ns        Name to convert
123      * @param string   $language  ISO code for language for results
124      * @param Location &$location Location object (may be null)
125      *
126      * @return boolean whether to continue (results in $location)
127      */
128
129     function onLocationFromId($id, $ns, $language, &$location)
130     {
131         if ($ns != self::LOCATION_NS) {
132             // It's not one of our IDs... keep processing
133             return true;
134         }
135
136         $loc = $this->getCache(array('id' => $id));
137
138         if ($loc !== false) {
139             $location = $loc;
140             return false;
141         }
142
143         try {
144             $geonames = $this->getGeonames('hierarchy',
145                                            array('geonameId' => $id,
146                                                  'lang' => $language));
147         } catch (Exception $e) {
148             $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
149             return false;
150         }
151
152         $parts = array();
153
154         foreach ($geonames as $level) {
155             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
156                 $parts[] = (string)$level->name;
157             }
158         }
159
160         $last = $geonames[count($geonames)-1];
161
162         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
163             $parts[] = (string)$last->name;
164         }
165
166         $location = new Location();
167
168         $location->location_id      = (string)$last->geonameId;
169         $location->location_ns      = self::LOCATION_NS;
170         $location->lat              = $this->canonical($last->lat);
171         $location->lon              = $this->canonical($last->lng);
172
173         $location->names[$language] = implode(', ', array_reverse($parts));
174
175         $this->setCache(array('id' => (string)$last->geonameId),
176                         $location);
177
178         // We're responsible for this namespace; nobody else
179         // can resolve it
180
181         return false;
182     }
183
184     /**
185      * convert a lat/lon pair into a Location object
186      *
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).
189      *
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)
194      *
195      * @return boolean whether to continue (results in $location)
196      */
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
276     function onLocationNameLanguage($location, $language, &$name)
277     {
278         if ($location->location_ns != self::LOCATION_NS) {
279             // It's not one of our IDs... keep processing
280             return true;
281         }
282
283         $id = $location->location_id;
284
285         $n = $this->getCache(array('id' => $id,
286                                    'language' => $language));
287
288         if ($n !== false) {
289             $name = $n;
290             return false;
291         }
292
293         try {
294             $geonames = $this->getGeonames('hierarchy',
295                                            array('geonameId' => $id,
296                                                  'lang' => $language));
297         } catch (Exception $e) {
298             $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
299             return false;
300         }
301
302         if (count($geonames) == 0) {
303             $this->setCache(array('id' => $id,
304                                   'language' => $language),
305                             null);
306             return false;
307         }
308
309         $parts = array();
310
311         foreach ($geonames as $level) {
312             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
313                 $parts[] = (string)$level->name;
314             }
315         }
316
317         $last = $geonames[count($geonames)-1];
318
319         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
320             $parts[] = (string)$last->name;
321         }
322
323         if (count($parts)) {
324             $name = implode(', ', array_reverse($parts));
325             $this->setCache(array('id' => $id,
326                                   'language' => $language),
327                             $name);
328         }
329
330         return false;
331     }
332
333     /**
334      * Human-readable URL for a location
335      *
336      * Given a location, we try to retrieve a geonames.org URL.
337      *
338      * @param Location $location Location to get the url for
339      * @param string   &$url     Place to put the url
340      *
341      * @return boolean whether to continue
342      */
343
344     function onLocationUrl($location, &$url)
345     {
346         if ($location->location_ns != self::LOCATION_NS) {
347             // It's not one of our IDs... keep processing
348             return true;
349         }
350
351         $url = 'http://www.geonames.org/' . $location->location_id;
352
353         // it's been filled, so don't process further.
354         return false;
355     }
356
357     /**
358      * Machine-readable name for a location
359      *
360      * Given a location, we try to retrieve a geonames.org URL.
361      *
362      * @param Location $location Location to get the url for
363      * @param string   &$url     Place to put the url
364      *
365      * @return boolean whether to continue
366      */
367
368     function onLocationRdfUrl($location, &$url)
369     {
370         if ($location->location_ns != self::LOCATION_NS) {
371             // It's not one of our IDs... keep processing
372             return true;
373         }
374
375         $url = 'http://sw.geonames.org/' . $location->location_id . '/';
376
377         // it's been filled, so don't process further.
378         return false;
379     }
380
381     function getCache($attrs)
382     {
383         $c = common_memcache();
384
385         if (empty($c)) {
386             return null;
387         }
388
389         $key = $this->cacheKey($attrs);
390
391         $value = $c->get($key);
392
393         return $value;
394     }
395
396     function setCache($attrs, $loc)
397     {
398         $c = common_memcache();
399
400         if (empty($c)) {
401             return null;
402         }
403
404         $key = $this->cacheKey($attrs);
405
406         $result = $c->set($key, $loc, 0, time() + $this->expiry);
407
408         return $result;
409     }
410
411     function cacheKey($attrs)
412     {
413         $key = 'geonames:' .
414                implode(',', array_keys($attrs)) . ':'.
415                common_keyize(implode(',', array_values($attrs)));
416         if ($this->cachePrefix) {
417             return $this->cachePrefix . ':' . $key;
418         } else {
419             return common_cache_key($key);
420         }
421     }
422
423     function wsUrl($method, $params)
424     {
425         if (!empty($this->username)) {
426             $params['username'] = $this->username;
427         }
428
429         if (!empty($this->token)) {
430             $params['token'] = $this->token;
431         }
432
433         $str = http_build_query($params, null, '&');
434
435         return 'http://'.$this->host.'/'.$method.'?'.$str;
436     }
437
438     function getGeonames($method, $params)
439     {
440         $client = HTTPClient::start();
441
442         $result = $client->get($this->wsUrl($method, $params));
443
444         if (!$result->isOk()) {
445             throw new Exception("HTTP error code " . $result->code);
446         }
447
448         $body = $result->getBody();
449
450         if (empty($body)) {
451             throw new Exception("Empty HTTP body in response");
452         }
453
454         // This will throw an exception if the XML is mal-formed
455
456         $document = new SimpleXMLElement($body);
457
458         // No children, usually no results
459
460         $children = $document->children();
461
462         if (count($children) == 0) {
463             return array();
464         }
465
466         if (isset($document->status)) {
467             throw new Exception("Error #".$document->status['value']." ('".$document->status['message']."')");
468         }
469
470         // Array of elements, >0 elements
471
472         return $document->geoname;
473     }
474
475     function onPluginVersion(&$versions)
476     {
477         $versions[] = array('name' => 'Geonames',
478                             'version' => STATUSNET_VERSION,
479                             'author' => 'Evan Prodromou',
480                             'homepage' => 'http://status.net/wiki/Plugin:Geonames',
481                             'rawdescription' =>
482                             _m('Uses <a href="http://geonames.org/">Geonames</a> service to get human-readable '.
483                                'names for locations based on user-provided lat/long pairs.'));
484         return true;
485     }
486
487     function canonical($coord)
488     {
489         $coord = rtrim($coord, "0");
490         $coord = rtrim($coord, ".");
491
492         return $coord;
493     }
494 }