]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/GeonamesPlugin.php
Merge branch 'master' of git@gitorious.org:statusnet/mainline
[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         $client = HTTPClient::start();
80
81         // XXX: break down a name by commas, narrow by each
82
83         $result = $client->get($this->wsUrl('search',
84                                             array('maxRows' => 1,
85                                                   'q' => $name,
86                                                   'lang' => $language,
87                                                   'type' => 'json')));
88
89         if (!$result->isOk()) {
90             $this->log(LOG_WARNING, "Error code " . $result->code .
91                        " from " . $this->host . " for $name");
92             return true;
93         }
94
95         $rj = json_decode($result->getBody());
96
97         if (count($rj->geonames) <= 0) {
98             $this->log(LOG_WARNING, "No results in response from " .
99                        $this->host . " for $name");
100             return true;
101         }
102
103         $n = $rj->geonames[0];
104
105         $location = new Location();
106
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;
112
113         $this->setCache(array('name' => $name,
114                               'language' => $language),
115                         $location);
116
117         // handled, don't continue processing!
118         return false;
119     }
120
121     /**
122      * convert an id into a Location object
123      *
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)
128      *
129      * @return boolean whether to continue (results in $location)
130      */
131
132     function onLocationFromId($id, $ns, $language, &$location)
133     {
134         if ($ns != self::LOCATION_NS) {
135             // It's not one of our IDs... keep processing
136             return true;
137         }
138
139         $loc = $this->getCache(array('id' => $id));
140
141         if (!empty($loc)) {
142             $location = $loc;
143             return false;
144         }
145
146         $client = HTTPClient::start();
147
148         $result = $client->get($this->wsUrl('hierarchyJSON',
149                                             array('geonameId' => $id,
150                                                   'lang' => $language)));
151
152         if (!$result->isOk()) {
153             $this->log(LOG_WARNING,
154                        "Error code " . $result->code .
155                        " from " . $this->host . " for ID $id");
156             return false;
157         }
158
159         $rj = json_decode($result->getBody());
160
161         if (count($rj->geonames) <= 0) {
162             $this->log(LOG_WARNING,
163                        "No results in response from " .
164                        $this->host . " for ID $id");
165             return false;
166         }
167
168         $parts = array();
169
170         foreach ($rj->geonames as $level) {
171             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
172                 $parts[] = $level->name;
173             }
174         }
175
176         $last = $rj->geonames[count($rj->geonames)-1];
177
178         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
179             $parts[] = $last->name;
180         }
181
182         $location = new Location();
183
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));
189
190         $this->setCache(array('id' => $last->geonameId),
191                         $location);
192
193         // We're responsible for this NAMESPACE; nobody else
194         // can resolve it
195
196         return false;
197     }
198
199     /**
200      * convert a lat/lon pair into a Location object
201      *
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).
204      *
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)
209      *
210      * @return boolean whether to continue (results in $location)
211      */
212
213     function onLocationFromLatLon($lat, $lon, $language, &$location)
214     {
215         $lat = rtrim($lat, "0");
216         $lon = rtrim($lon, "0");
217
218         $loc = $this->getCache(array('lat' => $lat,
219                                      'lon' => $lon));
220
221         if (!empty($loc)) {
222             $location = $loc;
223             return false;
224         }
225
226         $client = HTTPClient::start();
227
228         $result =
229           $client->get($this->wsUrl('findNearbyPlaceNameJSON',
230                                     array('lat' => $lat,
231                                           'lng' => $lon,
232                                           'lang' => $language)));
233
234         if (!$result->isOk()) {
235             $this->log(LOG_WARNING,
236                        "Error code " . $result->code .
237                        " from " . $this->host . " for coords $lat, $lon");
238             return true;
239         }
240
241         $rj = json_decode($result->getBody());
242
243         if (count($rj->geonames) <= 0) {
244             $this->log(LOG_WARNING,
245                        "No results in response from " .
246                        $this->host . " for coords $lat, $lon");
247             return true;
248         }
249
250         $n = $rj->geonames[0];
251
252         $parts = array();
253
254         $location = new Location();
255
256         $parts[] = $n->name;
257
258         if (!empty($n->adminName1)) {
259             $parts[] = $n->adminName1;
260         }
261
262         if (!empty($n->countryName)) {
263             $parts[] = $n->countryName;
264         }
265
266         $location->location_id = $n->geonameId;
267         $location->location_ns = self::LOCATION_NS;
268         $location->lat         = $lat;
269         $location->lon         = $lon;
270
271         $location->names[$language] = implode(', ', $parts);
272
273         $this->setCache(array('lat' => $lat,
274                               'lon' => $lon),
275                         $location);
276
277         // Success! We handled it, so no further processing
278
279         return false;
280     }
281
282     /**
283      * Human-readable name for a location
284      *
285      * Given a location, we try to retrieve a human-readable name
286      * in the target language.
287      *
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
291      *
292      * @return boolean whether to continue
293      */
294
295     function onLocationNameLanguage($location, $language, &$name)
296     {
297         if ($location->location_ns != self::LOCATION_NS) {
298             // It's not one of our IDs... keep processing
299             return true;
300         }
301
302         $n = $this->getCache(array('id' => $location->location_id,
303                                    'language' => $language));
304
305         if (!empty($n)) {
306             $name = $n;
307             return false;
308         }
309
310         $client = HTTPClient::start();
311
312         $result = $client->get($this->wsUrl('hierarchyJSON',
313                                             array('geonameId' => $location->location_id,
314                                                   'lang' => $language)));
315
316         if (!$result->isOk()) {
317             $this->log(LOG_WARNING,
318                        "Error code " . $result->code .
319                        " from " . $this->host . " for ID " . $location->location_id);
320             return false;
321         }
322
323         $rj = json_decode($result->getBody());
324
325         if (count($rj->geonames) <= 0) {
326             $this->log(LOG_WARNING,
327                        "No results " .
328                        " from " . $this->host . " for ID " . $location->location_id);
329             return false;
330         }
331
332         $parts = array();
333
334         foreach ($rj->geonames as $level) {
335             if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
336                 $parts[] = $level->name;
337             }
338         }
339
340         $last = $rj->geonames[count($rj->geonames)-1];
341
342         if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
343             $parts[] = $last->name;
344         }
345
346         if (count($parts)) {
347             $name = implode(', ', array_reverse($parts));
348             $this->setCache(array('id' => $location->location_id,
349                                   'language' => $language),
350                             $name);
351         }
352
353         return false;
354     }
355
356     /**
357      * Human-readable name for a location
358      *
359      * Given a location, we try to retrieve a geonames.org URL.
360      *
361      * @param Location $location Location to get the url for
362      * @param string   &$url     Place to put the url
363      *
364      * @return boolean whether to continue
365      */
366
367     function onLocationUrl($location, &$url)
368     {
369         if ($location->location_ns != self::LOCATION_NS) {
370             // It's not one of our IDs... keep processing
371             return true;
372         }
373
374         $url = 'http://www.geonames.org/' . $location->location_id;
375
376         // it's been filled, so don't process further.
377         return false;
378     }
379
380     /**
381      * Machine-readable name for a location
382      *
383      * Given a location, we try to retrieve a geonames.org URL.
384      *
385      * @param Location $location Location to get the url for
386      * @param string   &$url     Place to put the url
387      *
388      * @return boolean whether to continue
389      */
390
391     function onLocationRdfUrl($location, &$url)
392     {
393         if ($location->location_ns != self::LOCATION_NS) {
394             // It's not one of our IDs... keep processing
395             return true;
396         }
397
398         $url = 'http://sw.geonames.org/' . $location->location_id . '/';
399
400         // it's been filled, so don't process further.
401         return false;
402     }
403
404     function getCache($attrs)
405     {
406         $c = common_memcache();
407
408         if (empty($c)) {
409             return null;
410         }
411
412         $key = $this->cacheKey($attrs);
413
414         $value = $c->get($key);
415
416         return $value;
417     }
418
419     function setCache($attrs, $loc)
420     {
421         $c = common_memcache();
422
423         if (empty($c)) {
424             return null;
425         }
426
427         $key = $this->cacheKey($attrs);
428
429         $result = $c->set($key, $loc, 0, time() + $this->expiry);
430
431         return $result;
432     }
433
434     function cacheKey($attrs)
435     {
436         return common_cache_key('geonames:'.
437                                 implode(',', array_keys($attrs)) . ':'.
438                                 common_keyize(implode(',', array_values($attrs))));
439     }
440
441     function wsUrl($method, $params)
442     {
443         if (!empty($this->username)) {
444             $params['username'] = $this->username;
445         }
446
447         if (!empty($this->token)) {
448             $params['token'] = $this->token;
449         }
450
451         $str = http_build_query($params, null, '&');
452
453         return 'http://'.$this->host.'/'.$method.'?'.$str;
454     }
455 }