Merge remote branch 'origin/platal-0.10.2'
[platal.git] / include / geoloc.inc.php
index bb341fd..3e7f40d 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2007 Polytechnique.org                              *
+ *  Copyright (C) 2003-2010 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -42,17 +42,6 @@ function geoloc_country($current, $avail_only = false)
     return $html;
 }
 
-function _geoloc_country_smarty($params)
-{
-    echo "miqjfmeij";
-    if(!isset($params['country'])) {
-        return;
-    }
-    return geoloc_country($params['country'], @$params['available']);
-}
-
-$GLOBALS['page']->register_function('geoloc_country', '_geoloc_country_smarty');
-
 /** donne la liste deroulante des regions pour un pays
  * @param $pays le pays dont on veut afficher les regions
  * @param $current la region actuellement selectionnee
@@ -79,15 +68,6 @@ function geoloc_region($country, $current, $avail_only = false)
     }
     return $html;
 }
-
-function _geoloc_region_smarty($params, &$smarty)
-{
-    if(!isset($params['country']) || !isset($params['region'])) {
-        return;
-    }
-    return geoloc_region($params['country'], $params['region'], @$params['available']);
-}
-$GLOBALS['page']->register_function('geoloc_region', '_geoloc_region_smarty');
 // }}}
 
 // {{{ get_address_infos($txt)
@@ -95,14 +75,34 @@ $GLOBALS['page']->register_function('geoloc_region', '_geoloc_region_smarty');
  * store on the fly the info of the city concerned
  * @param $txt the raw text of an address
  */
-function get_address_infos($txt) 
+function get_address_infos($txt)
 {
     global $globals;
+
     $url = $globals->geoloc->webservice_url."address.php?precise=1&txt=" . urlencode($txt);
-    if (!($f = @fopen($url, 'r'))) return false;
+    if ($globals->debug & DEBUG_BT) {
+        if (!isset(PlBacktrace::$bt['Geoloc'])) {
+            new PlBacktrace('Geoloc');
+        }
+        PlBacktrace::$bt['Geoloc']->start($url);
+    }
+    $f = @fopen($url, 'r');
+    if ($f === false) {
+        if ($globals->debug & DEBUG_BT) {
+            PlBacktrace::$bt['Geoloc']->stop(0, 'Can\'t fetch result');
+        }
+        return false;
+    }
     $keys = explode('|',fgets($f));
     $vals = explode('|',fgets($f));
-    $infos = array();
+    if ($globals->debug & DEBUG_BT) {
+        $data = array();
+        for ($i = 0 ; $i < count($keys) ; ++$i) {
+            $data[] = array($keys[$i], $vals[$i]);
+        }
+        PlBacktrace::$bt['Geoloc']->stop(count($keys), null, $data);
+    }
+    $infos = empty_address();
     foreach ($keys as $i=>$key) {
         if($vals[$i]) {
             if ($key == 'sql') {
@@ -113,12 +113,41 @@ function get_address_infos($txt)
             }
         }
     }
-    if (isset($infos['sql']) && $infos['sql'])
-       XDB::execute("REPLACE INTO geoloc_city VALUES ".$infos['sql']);
+    if (empty($infos['country'])) {
+        $infos['country'] = '00';
+    }
+    if (isset($infos['sql']) && $infos['sql']) {
+        $sql = explode(', ', trim($infos['sql'], '()'));
+        if (count($sql) == 16) {
+            for ($i = 0 ; $i < 16 ; ++$i) {
+                $sql[$i] = stripslashes(trim($sql[$i], ' \''));
+            }
+            XDB::execute("REPLACE INTO  geoloc_city
+                                VALUES  ({?}, {?}, {?}, {?}, {?}, {?},
+                                         {?}, {?}, {?}, {?}, {?}, {?},
+                                         {?}, {?}, {?}, {?})",
+                         $sql[0], $sql[1], $sql[2], $sql[3], $sql[4], $sql[5],
+                         $sql[6], $sql[7], $sql[8], $sql[9], $sql[10], $sql[11],
+                         $sql[12], $sql[13], $sql[14], $sql[15]);
+        }
+    }
     if (isset($infos['display']) && $infos['display'])
-        XDB::execute("UPDATE geoloc_pays SET display = {?} WHERE a2 = {?}", $infos['display'], $infos['country']);
-    if (isset($infos['cityid']))
+        XDB::execute("UPDATE  geoloc_pays
+                         SET  display = {?}
+                       WHERE  a2 = {?}", $infos['display'], $infos['country']);
+    if (isset($infos['cityid'])) {
         fix_cities_not_on_map(1, $infos['cityid']);
+        if (floatval($infos['precise_lat']) && floatval($infos['precise_lon'])) {
+            $res = XDB::query("SELECT  c.lat / 100000, c.lon / 100000
+                                 FROM  geoloc_city AS c
+                                WHERE  c.id = {?}", $infos['cityid']);
+            if ($res->numRows()) {
+                list($glat, $glng) = $res->fetchOneRow();
+                $infos['precise_lat'] = $glat;
+                $infos['precise_lon'] = $glng;
+            }
+        }
+    }
     return $infos;
 }
 // }}}
@@ -171,7 +200,7 @@ function get_new_maps($url)
 /** make the text of an address that can be read by a mailman
  * @param $adr an array with all the usual fields
  */
-function get_address_text($adr) 
+function get_address_text($adr)
 {
     $t = "";
     if (isset($adr['adr1']) && $adr['adr1']) $t.= $adr['adr1'];
@@ -197,7 +226,7 @@ function get_address_text($adr)
         if (isset($adr['city']) && $adr['city']) $l .= $adr['city'];
     }
     if ($l) $t .= "\n".trim($l);
-    if ($adr['country'] != '00' && (!$adr['countrytxt'] || $adr['countrytxt'] == strtoupper($adr['countrytxt']))) {
+    if ($adr['country'] != '00' && (!$adr['countrytxt'] || $adr['countrytxt'] == mb_strtoupper($adr['countrytxt']))) {
         $res = XDB::query("SELECT pays FROM geoloc_pays WHERE a2 = {?}", $adr['country']);
         $adr['countrytxt'] = $res->fetchOneCell();
     }
@@ -215,9 +244,9 @@ function get_address_text($adr)
  */
 function compare_addresses_text($a, $b)
 {
-    $ta = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $a));
-    $tb = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $b));
-   
+    $ta = mb_strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $a));
+    $tb = mb_strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $b));
+
     $la = explode("\n", $ta);
     $lb = explode("\n", $tb);
 
@@ -225,7 +254,7 @@ function compare_addresses_text($a, $b)
         return false;
     }
     foreach ($la as $i=>$l) {
-        if (levenshtein($l, $lb[$i]) > 3) {
+        if (levenshtein(trim($l), trim($lb[$i])) > 3) {
             return false;
         }
     }
@@ -245,7 +274,9 @@ function empty_address() {
         "region" => "",
         "regiontxt" => "",
         "country" => "00",
-        "countrytxt" => "");
+        "countrytxt" => "",
+        "precise_lat" => "",
+        "precise_lon" => "");
 }
 
 // create a simple address from a text without geoloc
@@ -299,7 +330,7 @@ function localize_addresses($uid)
 /** synchronise the local geoloc_city base to geoloc.org
  * @param $id the id of the city to synchronize
  */
-function synchro_city($id) 
+function synchro_city($id)
 {
     global $globals;
     $url = $globals->geoloc->webservice_url."cityFinder.php?method=id&id=".$id."&out=sql";
@@ -318,7 +349,7 @@ function fix_cities_not_on_map($limit=false, $cityid=false)
 {
     $missing = XDB::query("SELECT  c.id
                              FROM  geoloc_city AS c
-                        LEFT JOIN  geoloc_city_in_maps AS m ON(c.id = m.city_id) 
+                        LEFT JOIN  geoloc_city_in_maps AS m ON(c.id = m.city_id)
                             WHERE  m.city_id IS NULL"
                             . ($cityid ? " AND c.id = '" . $cityid . "'" : "" )
                             . ($limit ?  " LIMIT $limit" : "" ));
@@ -330,8 +361,10 @@ function fix_cities_not_on_map($limit=false, $cityid=false)
                 $values .= ",($cityid, $map_id, '')";
             }
         }
-        XDB::execute("REPLACE INTO  geoloc_city_in_maps
-                            VALUES  ".substr($values, 1));
+        if (strlen($values) > 1) {
+            XDB::execute("REPLACE INTO  geoloc_city_in_maps
+                                VALUES  ".substr($values, 1));
+        }
     } else {
         return false;
     }
@@ -368,7 +401,7 @@ function geoloc_to_y($lon, $lat)
     if ($lat > 75) {
         return latToY(75);
     }
-    return -100 * log(tan(pi()/4 + deg2rad(1)/2*$lat));   
+    return -100 * log(tan(pi()/4 + deg2rad(1)/2*$lat));
 }
 
 function size_of_city($nb)
@@ -420,7 +453,7 @@ function geoloc_getData_subcities($mapid, $SFields, &$cities, $direct=true)
                           $where . ($direct ? "gcim.infos = 'smallest'" : '1'),
                           'gc.id, gc.alias',
                           'pop DESC');
-    while ($c = $cityres->next()) {
+    foreach($cityres as $c) {
         if ($c['pop'] > 0) {
             $city = $c;
             $city['x'] = geoloc_to_x($c['x'], $c['y']);
@@ -431,18 +464,18 @@ function geoloc_getData_subcities($mapid, $SFields, &$cities, $direct=true)
     }
 }
 
-function geoloc_getData_subcountries($mapid, $sin, $minentities) 
+function geoloc_getData_subcountries($mapid, $sin, $minentities)
 {
     $countries = array();
     $cities = array();
-    
+
     if ($mapid === false) {
         $wheremapid = "WHERE gm.parent IS NULL";
     } else {
         $wheremapid = "WHERE   gm.parent = {?}";
     }
     $submapres = XDB::iterator(
-        "SELECT  gm.map_id AS id, gm.name, gm.x, gm.y, gm.xclip, gm.yclip, 
+        "SELECT  gm.map_id AS id, gm.name, gm.x, gm.y, gm.xclip, gm.yclip,
                  gm.width, gm.height, gm.scale, 1 AS rat
            FROM  geoloc_maps AS gm
         ". $wheremapid, Env::v('mapid',''));
@@ -455,7 +488,7 @@ function geoloc_getData_subcountries($mapid, $sin, $minentities)
         $country['swf'] = $globals->geoloc->webservice_url."maps/mercator/map_".$c['id'].".swf";
         $countries[$c['id']] = $country;
     }
-    
+
     if ($mapid === false) {
         return array($countries, $cities);
     }
@@ -480,8 +513,8 @@ function geoloc_getData_subcountries($mapid, $sin, $minentities)
                                           array('map.parent'),
                                           array('adresses','geoloc_city_in_maps','geoloc_maps'),
                                           array('am','gcim','map'),
-                                          array(getadr_join('am'), 
-                                          'am.cityid = gcim.city_id', 
+                                          array(getadr_join('am'),
+                                          'am.cityid = gcim.city_id',
                                           'map.map_id = gcim.map_id'));
     $fields = new SFieldGroup(true, $SFields);
     $where  = $fields->get_where_statement();
@@ -496,10 +529,10 @@ function geoloc_getData_subcountries($mapid, $sin, $minentities)
                             $where,
                             'map.map_id',
                             'NULL');
-    
+
     $maxpop = 0;
-    $nbentities = $nbcities + $countryres->total();
-    while ($c = $countryres->next()) {
+    $nbentities = $nbcities + count($countryres);
+    foreach ($countryres as $c) {
         $c['latPop'] /= $c['nbPop'];
         $c['lonPop'] /= $c['nbPop'];
         $c['rad'] = size_of_territory($c['nbPop']);
@@ -507,28 +540,28 @@ function geoloc_getData_subcountries($mapid, $sin, $minentities)
         $c['xPop'] = geoloc_to_x($c['lonPop'], $c['latPop']);
         $c['yPop'] = geoloc_to_y($c['lonPop'], $c['latPop']);
         @$countries[$c['id']] = array_merge($countries[$c['id']], $c);
-    
+
         $nbcities += $c['nbCities'];
-    } 
-    
+    }
+
     if ($nocity && $nbcities < $minentities){
         foreach($countries as $i => $c) {
             $countries[$i]['nbPop'] = 0;
             if (@$c['nbCities'] > 0) {
                 geoloc_getData_subcities($c['id'], $sin, $cities, false);
-            }   
+            }
         }
     }
-    
+
     foreach ($countries as $i => $c) {
-        if ($c['nbPop'] > 0) {
+        if (@$c['nbPop'] > 0) {
             $lambda = pow($c['nbPop'] / $maxpop,0.3);
             $countries[$i]['color'] = 0x0000FF + round((1-$lambda) * 0xFF)*0x010100;
         }
     }
-    
-    return array($countries, $cities);   
-} 
+
+    return array($countries, $cities);
+}
 // }}}
 
 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: