]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/GeonamesPlugin.php
use caching in geonames plugin
[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     /**
55      * convert a name into a Location object
56      *
57      * @param string   $name      Name to convert
58      * @param string   $language  ISO code for anguage the name is in
59      * @param Location &$location Location object (may be null)
60      *
61      * @return boolean whether to continue (results in $location)
62      */
63
64     function onLocationFromName($name, $language, &$location)
65     {
66         $loc = $this->getCache(array('name' => $name,
67                                      'language' => $language));
68
69         if (!empty($loc)) {
70             $location = $loc;
71             return false;
72         }
73
74         $client = HTTPClient::start();
75
76         // XXX: break down a name by commas, narrow by each
77
78         $str = http_build_query(array('maxRows' => 1,
79                                       'q' => $name,
80                                       'lang' => $language,
81                                       'type' => 'json'));
82
83         $result = $client->get('http://ws.geonames.org/search?'.$str);
84
85         if ($result->isOk()) {
86             $rj = json_decode($result->getBody());
87             if (count($rj->geonames) > 0) {
88                 $n = $rj->geonames[0];
89
90                 $location = new Location();
91
92                 $location->lat              = $n->lat;
93                 $location->lon              = $n->lng;
94                 $location->names[$language] = $n->name;
95                 $location->location_id      = $n->geonameId;
96                 $location->location_ns      = self::LOCATION_NS;
97
98                 $this->setCache(array('name' => $name,
99                                      'language' => $language),
100                                 $location);
101
102                 // handled, don't continue processing!
103                 return false;
104             }
105         }
106
107         // Continue processing; we don't have the answer
108         return true;
109     }
110
111     /**
112      * convert an id into a Location object
113      *
114      * @param string   $id        Name to convert
115      * @param string   $ns        Name to convert
116      * @param string   $language  ISO code for language for results
117      * @param Location &$location Location object (may be null)
118      *
119      * @return boolean whether to continue (results in $location)
120      */
121
122     function onLocationFromId($id, $ns, $language, &$location)
123     {
124         if ($ns != self::LOCATION_NS) {
125             // It's not one of our IDs... keep processing
126             return true;
127         }
128
129         $loc = $this->getCache(array('id' => $id));
130
131         if (!empty($loc)) {
132             $location = $loc;
133             return false;
134         }
135
136         $client = HTTPClient::start();
137
138         $str = http_build_query(array('geonameId' => $id,
139                                       'lang' => $language));
140
141         $result = $client->get('http://ws.geonames.org/hierarchyJSON?'.$str);
142
143         if ($result->isOk()) {
144
145             $rj = json_decode($result->getBody());
146
147             if (count($rj->geonames) > 0) {
148
149                 $parts = array();
150
151                 foreach ($rj->geonames as $level) {
152                     if (in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
153                         $parts[] = $level->name;
154                     }
155                 }
156
157                 $last = $rj->geonames[count($rj->geonames)-1];
158
159                 if (!in_array($level->fcode, array('PCLI', 'ADM1', 'PPL'))) {
160                     $parts[] = $last->name;
161                 }
162
163                 $location = new Location();
164
165                 $location->location_id      = $last->geonameId;
166                 $location->location_ns      = self::LOCATION_NS;
167                 $location->lat              = $last->lat;
168                 $location->lon              = $last->lng;
169                 $location->names[$language] = implode(', ', array_reverse($parts));
170
171                 $this->setCache(array('id' => $last->geonameId),
172                                 $location);
173             }
174         }
175
176         // We're responsible for this NAMESPACE; nobody else
177         // can resolve it
178
179         return false;
180     }
181
182     /**
183      * convert a lat/lon pair into a Location object
184      *
185      * Given a lat/lon, we try to find a Location that's around
186      * it or nearby. We prefer populated places (cities, towns, villages).
187      *
188      * @param string   $lat       Latitude
189      * @param string   $lon       Longitude
190      * @param string   $language  ISO code for language for results
191      * @param Location &$location Location object (may be null)
192      *
193      * @return boolean whether to continue (results in $location)
194      */
195
196     function onLocationFromLatLon($lat, $lon, $language, &$location)
197     {
198         $loc = $this->getCache(array('lat' => $lat,
199                                      'lon' => $lon));
200
201         if (!empty($loc)) {
202             $location = $loc;
203             return false;
204         }
205
206         $client = HTTPClient::start();
207
208         $str = http_build_query(array('lat' => $lat,
209                                       'lng' => $lon,
210                                       'lang' => $language));
211
212         $result =
213           $client->get('http://ws.geonames.org/findNearbyPlaceNameJSON?'.$str);
214
215         if ($result->isOk()) {
216
217             $rj = json_decode($result->getBody());
218
219             if (count($rj->geonames) > 0) {
220
221                 $n = $rj->geonames[0];
222
223                 $parts = array();
224
225                 $location = new Location();
226
227                 $parts[] = $n->name;
228
229                 if (!empty($n->adminName1)) {
230                     $parts[] = $n->adminName1;
231                 }
232
233                 if (!empty($n->countryName)) {
234                     $parts[] = $n->countryName;
235                 }
236
237                 $location->location_id = $n->geonameId;
238                 $location->location_ns = self::LOCATION_NS;
239                 $location->lat         = $lat;
240                 $location->lon         = $lon;
241
242                 $location->names[$language] = implode(', ', $parts);
243
244                 $this->setCache(array('lat' => $lat,
245                                       'lon' => $lon),
246                                 $location);
247
248                 // Success! We handled it, so no further processing
249
250                 return false;
251             }
252         }
253
254         // For some reason we don't know, so pass.
255
256         return true;
257     }
258
259     /**
260      * Human-readable name for a location
261      *
262      * Given a location, we try to retrieve a human-readable name
263      * in the target language.
264      *
265      * @param Location $location Location to get the name for
266      * @param string   $language ISO code for language to find name in
267      * @param string   &$name    Place to put the name
268      *
269      * @return boolean whether to continue
270      */
271
272     function onLocationNameLanguage($location, $language, &$name)
273     {
274         if ($location->location_ns != self::LOCATION_NS) {
275             // It's not one of our IDs... keep processing
276             return true;
277         }
278
279         $n = $this->getCache(array('id' => $location->location_id,
280                                    'language' => $language));
281
282         if (!empty($n)) {
283             $name = $n;
284             return false;
285         }
286
287         $client = HTTPClient::start();
288
289         $str = http_build_query(array('geonameId' => $location->location_id,
290                                       'lang' => $language));
291
292         $result = $client->get('http://ws.geonames.org/hierarchyJSON?'.$str);
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 (!$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 (!$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 (!$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 }