]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - plugins/GeonamesPlugin.php
Merge branch 'master' into testing
[quix0rs-gnu-social.git] / plugins / GeonamesPlugin.php
index 805166eaae0660c3c864eeea27026a6fe842feda..3815a31fa681d90ed8b1fb8782f4791918bd18f4 100644 (file)
@@ -55,6 +55,12 @@ class GeonamesPlugin extends Plugin
     public $username = null;
     public $token    = null;
     public $expiry   = 7776000; // 90-day expiry
+    public $timeout  = 2;       // Web service timeout in seconds.
+    public $timeoutWindow = 60; // Further lookups in this process will be disabled for N seconds after a timeout.
+    public $cachePrefix = null; // Optional shared memcache prefix override
+                                // to share lookups between local instances.
+
+    protected $lastTimeout = null; // timestamp of last web service timeout
 
     /**
      * convert a name into a Location object
@@ -71,7 +77,7 @@ class GeonamesPlugin extends Plugin
         $loc = $this->getCache(array('name' => $name,
                                      'language' => $language));
 
-        if (!empty($loc)) {
+        if ($loc !== false) {
             $location = $loc;
             return false;
         }
@@ -87,12 +93,20 @@ class GeonamesPlugin extends Plugin
             return true;
         }
 
+        if (count($geonames) == 0) {
+            // no results
+            $this->setCache(array('name' => $name,
+                                  'language' => $language),
+                            null);
+            return true;
+        }
+
         $n = $geonames[0];
 
         $location = new Location();
 
-        $location->lat              = (string)$n->lat;
-        $location->lon              = (string)$n->lng;
+        $location->lat              = $this->canonical($n->lat);
+        $location->lon              = $this->canonical($n->lng);
         $location->names[$language] = (string)$n->name;
         $location->location_id      = (string)$n->geonameId;
         $location->location_ns      = self::LOCATION_NS;
@@ -125,7 +139,7 @@ class GeonamesPlugin extends Plugin
 
         $loc = $this->getCache(array('id' => $id));
 
-        if (!empty($loc)) {
+        if ($loc !== false) {
             $location = $loc;
             return false;
         }
@@ -157,8 +171,9 @@ class GeonamesPlugin extends Plugin
 
         $location->location_id      = (string)$last->geonameId;
         $location->location_ns      = self::LOCATION_NS;
-        $location->lat              = (string)$last->lat;
-        $location->lon              = (string)$last->lng;
+        $location->lat              = $this->canonical($last->lat);
+        $location->lon              = $this->canonical($last->lng);
+
         $location->names[$language] = implode(', ', array_reverse($parts));
 
         $this->setCache(array('id' => (string)$last->geonameId),
@@ -186,13 +201,15 @@ class GeonamesPlugin extends Plugin
 
     function onLocationFromLatLon($lat, $lon, $language, &$location)
     {
-        $lat = rtrim($lat, "0");
-        $lon = rtrim($lon, "0");
+        // Make sure they're canonical
+
+        $lat = $this->canonical($lat);
+        $lon = $this->canonical($lon);
 
         $loc = $this->getCache(array('lat' => $lat,
                                      'lon' => $lon));
 
-        if (!empty($loc)) {
+        if ($loc !== false) {
             $location = $loc;
             return false;
         }
@@ -207,6 +224,14 @@ class GeonamesPlugin extends Plugin
             return true;
         }
 
+        if (count($geonames) == 0) {
+            // no results
+            $this->setCache(array('lat' => $lat,
+                                  'lon' => $lon),
+                            null);
+            return true;
+        }
+
         $n = $geonames[0];
 
         $parts = array();
@@ -225,8 +250,8 @@ class GeonamesPlugin extends Plugin
 
         $location->location_id = (string)$n->geonameId;
         $location->location_ns = self::LOCATION_NS;
-        $location->lat         = (string)$lat;
-        $location->lon         = (string)$lon;
+        $location->lat         = $this->canonical($n->lat);
+        $location->lon         = $this->canonical($n->lng);
 
         $location->names[$language] = implode(', ', $parts);
 
@@ -264,7 +289,7 @@ class GeonamesPlugin extends Plugin
         $n = $this->getCache(array('id' => $id,
                                    'language' => $language));
 
-        if (!empty($n)) {
+        if ($n !== false) {
             $name = $n;
             return false;
         }
@@ -278,6 +303,13 @@ class GeonamesPlugin extends Plugin
             return false;
         }
 
+        if (count($geonames) == 0) {
+            $this->setCache(array('id' => $id,
+                                  'language' => $language),
+                            null);
+            return false;
+        }
+
         $parts = array();
 
         foreach ($geonames as $level) {
@@ -344,7 +376,7 @@ class GeonamesPlugin extends Plugin
             return true;
         }
 
-        $url = 'http://sw.geonames.org/' . $location->location_id . '/';
+        $url = 'http://sws.geonames.org/' . $location->location_id . '/';
 
         // it's been filled, so don't process further.
         return false;
@@ -382,9 +414,14 @@ class GeonamesPlugin extends Plugin
 
     function cacheKey($attrs)
     {
-        return common_cache_key('geonames:'.
-                                implode(',', array_keys($attrs)) . ':'.
-                                common_keyize(implode(',', array_values($attrs))));
+        $key = 'geonames:' .
+               implode(',', array_keys($attrs)) . ':'.
+               common_keyize(implode(',', array_values($attrs)));
+        if ($this->cachePrefix) {
+            return $this->cachePrefix . ':' . $key;
+        } else {
+            return common_cache_key($key);
+        }
     }
 
     function wsUrl($method, $params)
@@ -404,26 +441,70 @@ class GeonamesPlugin extends Plugin
 
     function getGeonames($method, $params)
     {
+        if ($this->lastTimeout && (time() - $this->lastTimeout < $this->timeoutWindow)) {
+            throw new Exception("skipping due to recent web service timeout");
+        }
+
         $client = HTTPClient::start();
+        $client->setConfig('connect_timeout', $this->timeout);
+        $client->setConfig('timeout', $this->timeout);
 
-        $result = $client->get($this->wsUrl($method, $params));
+        try {
+            $result = $client->get($this->wsUrl($method, $params));
+        } catch (Exception $e) {
+            common_log(LOG_ERR, __METHOD__ . ": " . $e->getMessage());
+            $this->lastTimeout = time();
+            throw $e;
+        }
 
         if (!$result->isOk()) {
-            throw new Exception("HTTP error code " . $result->code);
+            throw new Exception("HTTP error code " . $result->getStatus());
         }
 
-        $document = new SimpleXMLElement($result->getBody());
+        $body = $result->getBody();
 
-        if (empty($document)) {
-            throw new Exception("No results in response");
+        if (empty($body)) {
+            throw new Exception("Empty HTTP body in response");
+        }
+
+        // This will throw an exception if the XML is mal-formed
+
+        $document = new SimpleXMLElement($body);
+
+        // No children, usually no results
+
+        $children = $document->children();
+
+        if (count($children) == 0) {
+            return array();
         }
 
         if (isset($document->status)) {
             throw new Exception("Error #".$document->status['value']." ('".$document->status['message']."')");
         }
 
-        // Array of elements
+        // Array of elements, >0 elements
 
         return $document->geoname;
     }
+
+    function onPluginVersion(&$versions)
+    {
+        $versions[] = array('name' => 'Geonames',
+                            'version' => STATUSNET_VERSION,
+                            'author' => 'Evan Prodromou',
+                            'homepage' => 'http://status.net/wiki/Plugin:Geonames',
+                            'rawdescription' =>
+                            _m('Uses <a href="http://geonames.org/">Geonames</a> service to get human-readable '.
+                               'names for locations based on user-provided lat/long pairs.'));
+        return true;
+    }
+
+    function canonical($coord)
+    {
+        $coord = rtrim($coord, "0");
+        $coord = rtrim($coord, ".");
+
+        return $coord;
+    }
 }