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