]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/GeonamesPlugin.php
some formatting changes to make inblobs work
[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
59     /**
60      * convert a name into a Location object
61      *
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)
65      *
66      * @return boolean whether to continue (results in $location)
67      */
68
69     function onLocationFromName($name, $language, &$location)
70     {
71         $loc = $this->getCache(array('name' => $name,
72                                      'language' => $language));
73
74         if (!empty($loc)) {
75             $location = $loc;
76             return false;
77         }
78
79         try {
80             $geonames = $this->getGeonames('search',
81                                            array('maxRows' => 1,
82                                                  'q' => $name,
83                                                  'lang' => $language,
84                                                  'type' => 'xml'));
85         } catch (Exception $e) {
86             $this->log(LOG_WARNING, "Error for $name: " . $e->getMessage());
87             return true;
88         }
89
90         $n = $geonames[0];
91
92         $location = new Location();
93
94         $location->lat              = (string)$n->lat;
95         $location->lon              = (string)$n->lng;
96         $location->names[$language] = (string)$n->name;
97         $location->location_id      = (string)$n->geonameId;
98         $location->location_ns      = self::LOCATION_NS;
99
100         $this->setCache(array('name' => $name,
101                               'language' => $language),
102                         $location);
103
104         // handled, don't continue processing!
105         return false;
106     }
107
108     /**
109      * convert an id into a Location object
110      *
111      * @param string   $id        Name to convert
112      * @param string   $ns        Name to convert
113      * @param string   $language  ISO code for language for results
114      * @param Location &$location Location object (may be null)
115      *
116      * @return boolean whether to continue (results in $location)
117      */
118
119     function onLocationFromId($id, $ns, $language, &$location)
120     {
121         if ($ns != self::LOCATION_NS) {
122             // It's not one of our IDs... keep processing
123             return true;
124         }
125
126         $loc = $this->getCache(array('id' => $id));
127
128         if (!empty($loc)) {
129             $location = $loc;
130             return false;
131         }
132
133         try {
134             $geonames = $this->getGeonames('hierarchy',
135                                            array('geonameId' => $id,
136                                                  'lang' => $language));
137         } catch (Exception $e) {
138             $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
139             return false;
140         }
141
142         $parts = array();
143
144         foreach ($geonames as $level) {
145             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
146                 $parts[] = (string)$level->name;
147             }
148         }
149
150         $last = $geonames[count($geonames)-1];
151
152         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
153             $parts[] = (string)$last->name;
154         }
155
156         $location = new Location();
157
158         $location->location_id      = (string)$last->geonameId;
159         $location->location_ns      = self::LOCATION_NS;
160         $location->lat              = (string)$last->lat;
161         $location->lon              = (string)$last->lng;
162         $location->names[$language] = implode(', ', array_reverse($parts));
163
164         $this->setCache(array('id' => (string)$last->geonameId),
165                         $location);
166
167         // We're responsible for this namespace; nobody else
168         // can resolve it
169
170         return false;
171     }
172
173     /**
174      * convert a lat/lon pair into a Location object
175      *
176      * Given a lat/lon, we try to find a Location that's around
177      * it or nearby. We prefer populated places (cities, towns, villages).
178      *
179      * @param string   $lat       Latitude
180      * @param string   $lon       Longitude
181      * @param string   $language  ISO code for language for results
182      * @param Location &$location Location object (may be null)
183      *
184      * @return boolean whether to continue (results in $location)
185      */
186
187     function onLocationFromLatLon($lat, $lon, $language, &$location)
188     {
189         $lat = rtrim($lat, "0");
190         $lon = rtrim($lon, "0");
191
192         $loc = $this->getCache(array('lat' => $lat,
193                                      'lon' => $lon));
194
195         if (!empty($loc)) {
196             $location = $loc;
197             return false;
198         }
199
200         try {
201           $geonames = $this->getGeonames('findNearbyPlaceName',
202                                          array('lat' => $lat,
203                                                'lng' => $lon,
204                                                'lang' => $language));
205         } catch (Exception $e) {
206             $this->log(LOG_WARNING, "Error for coords $lat, $lon: " . $e->getMessage());
207             return true;
208         }
209
210         $n = $geonames[0];
211
212         $parts = array();
213
214         $location = new Location();
215
216         $parts[] = (string)$n->name;
217
218         if (!empty($n->adminName1)) {
219             $parts[] = (string)$n->adminName1;
220         }
221
222         if (!empty($n->countryName)) {
223             $parts[] = (string)$n->countryName;
224         }
225
226         $location->location_id = (string)$n->geonameId;
227         $location->location_ns = self::LOCATION_NS;
228         $location->lat         = (string)$lat;
229         $location->lon         = (string)$lon;
230
231         $location->names[$language] = implode(', ', $parts);
232
233         $this->setCache(array('lat' => $lat,
234                               'lon' => $lon),
235                         $location);
236
237         // Success! We handled it, so no further processing
238
239         return false;
240     }
241
242     /**
243      * Human-readable name for a location
244      *
245      * Given a location, we try to retrieve a human-readable name
246      * in the target language.
247      *
248      * @param Location $location Location to get the name for
249      * @param string   $language ISO code for language to find name in
250      * @param string   &$name    Place to put the name
251      *
252      * @return boolean whether to continue
253      */
254
255     function onLocationNameLanguage($location, $language, &$name)
256     {
257         if ($location->location_ns != self::LOCATION_NS) {
258             // It's not one of our IDs... keep processing
259             return true;
260         }
261
262         $id = $location->location_id;
263
264         $n = $this->getCache(array('id' => $id,
265                                    'language' => $language));
266
267         if (!empty($n)) {
268             $name = $n;
269             return false;
270         }
271
272         try {
273             $geonames = $this->getGeonames('hierarchy',
274                                            array('geonameId' => $id,
275                                                  'lang' => $language));
276         } catch (Exception $e) {
277             $this->log(LOG_WARNING, "Error for ID $id: " . $e->getMessage());
278             return false;
279         }
280
281         $parts = array();
282
283         foreach ($geonames as $level) {
284             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
285                 $parts[] = (string)$level->name;
286             }
287         }
288
289         $last = $geonames[count($geonames)-1];
290
291         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
292             $parts[] = (string)$last->name;
293         }
294
295         if (count($parts)) {
296             $name = implode(', ', array_reverse($parts));
297             $this->setCache(array('id' => $id,
298                                   'language' => $language),
299                             $name);
300         }
301
302         return false;
303     }
304
305     /**
306      * Human-readable URL for a location
307      *
308      * Given a location, we try to retrieve a geonames.org URL.
309      *
310      * @param Location $location Location to get the url for
311      * @param string   &$url     Place to put the url
312      *
313      * @return boolean whether to continue
314      */
315
316     function onLocationUrl($location, &$url)
317     {
318         if ($location->location_ns != self::LOCATION_NS) {
319             // It's not one of our IDs... keep processing
320             return true;
321         }
322
323         $url = 'http://www.geonames.org/' . $location->location_id;
324
325         // it's been filled, so don't process further.
326         return false;
327     }
328
329     /**
330      * Machine-readable name for a location
331      *
332      * Given a location, we try to retrieve a geonames.org URL.
333      *
334      * @param Location $location Location to get the url for
335      * @param string   &$url     Place to put the url
336      *
337      * @return boolean whether to continue
338      */
339
340     function onLocationRdfUrl($location, &$url)
341     {
342         if ($location->location_ns != self::LOCATION_NS) {
343             // It's not one of our IDs... keep processing
344             return true;
345         }
346
347         $url = 'http://sw.geonames.org/' . $location->location_id . '/';
348
349         // it's been filled, so don't process further.
350         return false;
351     }
352
353     function getCache($attrs)
354     {
355         $c = common_memcache();
356
357         if (empty($c)) {
358             return null;
359         }
360
361         $key = $this->cacheKey($attrs);
362
363         $value = $c->get($key);
364
365         return $value;
366     }
367
368     function setCache($attrs, $loc)
369     {
370         $c = common_memcache();
371
372         if (empty($c)) {
373             return null;
374         }
375
376         $key = $this->cacheKey($attrs);
377
378         $result = $c->set($key, $loc, 0, time() + $this->expiry);
379
380         return $result;
381     }
382
383     function cacheKey($attrs)
384     {
385         return common_cache_key('geonames:'.
386                                 implode(',', array_keys($attrs)) . ':'.
387                                 common_keyize(implode(',', array_values($attrs))));
388     }
389
390     function wsUrl($method, $params)
391     {
392         if (!empty($this->username)) {
393             $params['username'] = $this->username;
394         }
395
396         if (!empty($this->token)) {
397             $params['token'] = $this->token;
398         }
399
400         $str = http_build_query($params, null, '&');
401
402         return 'http://'.$this->host.'/'.$method.'?'.$str;
403     }
404
405     function getGeonames($method, $params)
406     {
407         $client = HTTPClient::start();
408
409         $result = $client->get($this->wsUrl($method, $params));
410
411         if (!$result->isOk()) {
412             throw new Exception("HTTP error code " . $result->code);
413         }
414
415         $document = new SimpleXMLElement($result->getBody());
416
417         if (empty($document)) {
418             throw new Exception("No results in response");
419         }
420
421         if (isset($document->status)) {
422             throw new Exception("Error #".$document->status['value']." ('".$document->status['message']."')");
423         }
424
425         // Array of elements
426
427         return $document->geoname;
428     }
429 }