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