| 1 | <?php |
| 2 | /*************************************************************************** |
| 3 | * Copyright (C) 2003-2006 Polytechnique.org * |
| 4 | * http://opensource.polytechnique.org/ * |
| 5 | * * |
| 6 | * This program is free software; you can redistribute it and/or modify * |
| 7 | * it under the terms of the GNU General Public License as published by * |
| 8 | * the Free Software Foundation; either version 2 of the License, or * |
| 9 | * (at your option) any later version. * |
| 10 | * * |
| 11 | * This program is distributed in the hope that it will be useful, * |
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 14 | * GNU General Public License for more details. * |
| 15 | * * |
| 16 | * You should have received a copy of the GNU General Public License * |
| 17 | * along with this program; if not, write to the Free Software * |
| 18 | * Foundation, Inc., * |
| 19 | * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * |
| 20 | ***************************************************************************/ |
| 21 | |
| 22 | // {{{ liste les pays ou les régions d'un pays |
| 23 | /** donne la liste déroulante des pays |
| 24 | * @param $current pays actuellement selectionné |
| 25 | */ |
| 26 | function geoloc_country($current) { |
| 27 | $res = XDB::iterRow('SELECT a2,pays FROM geoloc_pays ORDER BY pays'); |
| 28 | $html = ""; |
| 29 | while (list($my_id, $my_pays) = $res->next()) { |
| 30 | $html .= sprintf("<option value=\"%s\" %s>%s</option>\n", |
| 31 | $my_id, ($current==$my_id?"selected='selected'":""), $my_pays); |
| 32 | } |
| 33 | return $html; |
| 34 | } |
| 35 | |
| 36 | function _geoloc_country_smarty($params){ |
| 37 | if(!isset($params['country'])) |
| 38 | return; |
| 39 | return geoloc_country($params['country']); |
| 40 | } |
| 41 | $GLOBALS['page']->register_function('geoloc_country', '_geoloc_country_smarty'); |
| 42 | |
| 43 | /** donne la liste deroulante des regions pour un pays |
| 44 | * @param $pays le pays dont on veut afficher les regions |
| 45 | * @param $current la region actuellement selectionnee |
| 46 | */ |
| 47 | function geoloc_region($country,$current) { |
| 48 | $res = XDB::iterRow('SELECT region,name FROM geoloc_region where a2={?} ORDER BY name', $country); |
| 49 | $html = "<option value=\"\"></option>"; |
| 50 | while (list($regid, $regname) = $res->next()) { |
| 51 | $html .= sprintf("<option value=\"%s\" %s>%s</option>\n", |
| 52 | $regid, ($current==$regid?"selected='selected'":""), $regname); |
| 53 | } |
| 54 | return $html; |
| 55 | |
| 56 | } |
| 57 | function _geoloc_region_smarty($params){ |
| 58 | if(!isset($params['country'])) |
| 59 | return; |
| 60 | if(!isset($params['region'])) |
| 61 | return; |
| 62 | return geoloc_region($params['country'], $params['region']); |
| 63 | } |
| 64 | $GLOBALS['page']->register_function('geoloc_region', '_geoloc_region_smarty'); |
| 65 | // }}} |
| 66 | |
| 67 | // {{{ get_address_infos($txt) |
| 68 | /** retrieve the infos on a text address |
| 69 | * store on the fly the info of the city concerned |
| 70 | * @param $txt the raw text of an address |
| 71 | */ |
| 72 | function get_address_infos($txt) { |
| 73 | global $globals; |
| 74 | $url = $globals->geoloc->webservice_url."address.php?precise=1&txt=".urlencode(utf8_encode($txt)); |
| 75 | if (!($f = @fopen($url, 'r'))) return false; |
| 76 | $keys = explode('|',fgets($f)); |
| 77 | $vals = explode('|',fgets($f)); |
| 78 | $infos = array(); |
| 79 | foreach ($keys as $i=>$key) if($vals[$i]) $infos[$key] = ($key == 'sql')?$vals[$i]:utf8_decode(strtr($vals[$i], array(chr(197).chr(147) => "œ"))); |
| 80 | if ($infos['sql']) |
| 81 | XDB::execute("REPLACE INTO geoloc_city VALUES ".$infos['sql']); |
| 82 | if ($infos['display']) |
| 83 | XDB::execute("UPDATE geoloc_pays SET display = {?} WHERE a2 = {?}", $infos['display'], $infos['country']); |
| 84 | return $infos; |
| 85 | } |
| 86 | // }}} |
| 87 | |
| 88 | // {{{ get_cities_maps($array) |
| 89 | /* get all the maps id of the cities contained in an array */ |
| 90 | function get_cities_maps($array) |
| 91 | { |
| 92 | global $globals; |
| 93 | implode("\n",$array); |
| 94 | $url = $globals->geoloc->webservice_url."findMaps.php?datatext=".urlencode(utf8_encode(implode("\n", $array))); |
| 95 | if (!($f = @fopen($url, 'r'))) return false; |
| 96 | $maps = array(); |
| 97 | while (!feof($f)) |
| 98 | { |
| 99 | $l = trim(fgets($f)); |
| 100 | $tab = explode(';', $l); |
| 101 | $i = $tab[0]; |
| 102 | unset($tab[0]); |
| 103 | $maps[$i] = $tab; |
| 104 | } |
| 105 | return $maps; |
| 106 | } |
| 107 | // }}} |
| 108 | |
| 109 | // {{{ get_new_maps($url) |
| 110 | /** set new maps from url **/ |
| 111 | function get_new_maps($url) |
| 112 | { |
| 113 | if (!($f = @fopen($url, 'r'))) { |
| 114 | return false; |
| 115 | } |
| 116 | XDB::query('TRUNCATE TABLE geoloc_maps'); |
| 117 | $s = ''; |
| 118 | while (!feof($f)) { |
| 119 | $l = fgetcsv($f, 1024, ';', '"'); |
| 120 | foreach ($l as $i => $val) { |
| 121 | if ($val != 'NULL') { |
| 122 | $l[$i] = '\''.addslashes($val).'\''; |
| 123 | } |
| 124 | } |
| 125 | $s .= ',('.implode(',',$l).')'; |
| 126 | } |
| 127 | XDB::execute('INSERT INTO geoloc_maps VALUES '.substr($s, 1)); |
| 128 | return true; |
| 129 | } |
| 130 | // }}} |
| 131 | |
| 132 | // {{{ get_address_text($adr) |
| 133 | /** make the text of an address that can be read by a mailman |
| 134 | * @param $adr an array with all the usual fields |
| 135 | */ |
| 136 | function get_address_text($adr) { |
| 137 | $t = ""; |
| 138 | if ($adr['adr1']) $t.= $adr['adr1']; |
| 139 | if ($adr['adr2']) $t.= "\n".$adr['adr2']; |
| 140 | if ($adr['adr3']) $t.= "\n".$adr['adr3']; |
| 141 | $l = ""; |
| 142 | if ($adr['display']) { |
| 143 | $keys = explode(' ', $adr['display']); |
| 144 | foreach ($keys as $key) { |
| 145 | if (isset($adr[$key])) |
| 146 | $l .= " ".$adr[$key]; |
| 147 | else |
| 148 | $l .= " ".$key; |
| 149 | } |
| 150 | if ($l) $l = substr($l, 1); |
| 151 | } |
| 152 | else |
| 153 | { |
| 154 | if ($adr['country'] == 'US' || $adr['country'] == 'CA' || $adr['country'] == 'GB') { |
| 155 | if ($adr['city']) $l .= $adr['city'].",\n"; |
| 156 | if ($adr['region']) $l .= $adr['region']." "; |
| 157 | if ($adr['postcode']) $l .= $adr['postcode']; |
| 158 | } else { |
| 159 | if ($adr['postcode']) $l .= $adr['postcode']." "; |
| 160 | if ($adr['city']) $l .= $adr['city']; |
| 161 | } |
| 162 | } |
| 163 | if ($l) $t .= "\n".trim($l); |
| 164 | if ($adr['country'] != '00' && (!$adr['countrytxt'] || $adr['countrytxt'] == strtoupper($adr['countrytxt']))) { |
| 165 | $res = XDB::query("SELECT pays FROM geoloc_pays WHERE a2 = {?}", $adr['country']); |
| 166 | $adr['countrytxt'] = $res->fetchOneCell(); |
| 167 | } |
| 168 | if ($adr['countrytxt']) $t .= "\n".$adr['countrytxt']; |
| 169 | return trim($t); |
| 170 | } |
| 171 | // }}} |
| 172 | |
| 173 | // {{{ compare_addresses_text($a, $b) |
| 174 | /** compares if two address matches |
| 175 | * @param $a the raw text of an address |
| 176 | * @param $b the raw text of a complete valid address |
| 177 | */ |
| 178 | function compare_addresses_text($a, $b) { |
| 179 | $ta = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $a)); |
| 180 | $tb = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $b)); |
| 181 | |
| 182 | $la = explode("\n", $ta); |
| 183 | $lb = explode("\n", $tb); |
| 184 | |
| 185 | if (count($lb) > count($la) + 1) return false; |
| 186 | foreach ($la as $i=>$l) if (levenshtein($l, $lb[$i]) > 3) return false; |
| 187 | return true; |
| 188 | } |
| 189 | |
| 190 | // }}} |
| 191 | |
| 192 | function empty_address() { |
| 193 | return Array( |
| 194 | "adr1" => "", |
| 195 | "adr2" => "", |
| 196 | "adr3" => "", |
| 197 | "cityid" => NULL, |
| 198 | "city" => "", |
| 199 | "postcode" => "", |
| 200 | "region" => "", |
| 201 | "regiontxt" => "", |
| 202 | "country" => "00", |
| 203 | "countrytxt" => ""); |
| 204 | } |
| 205 | |
| 206 | // create a simple address from a text without geoloc |
| 207 | function cut_address($txt) { |
| 208 | $txt = str_replace("\r\n", "\n", $txt); |
| 209 | ereg("^([^\n]*)(\n([^\n]*)(\n(.*))?)?$", trim($txt), $a); |
| 210 | return array("adr1" => trim($a[1]), "adr2" => trim($a[3]), "adr3" => trim(str_replace("\n", " ", $a[5]))); |
| 211 | } |
| 212 | |
| 213 | // {{{ localize_addresses($uid) |
| 214 | /* localize all the address of a user and modify the database |
| 215 | * if the new address match with the old one |
| 216 | * @param $uid the id of the user |
| 217 | */ |
| 218 | function localize_addresses($uid) { |
| 219 | $res = XDB::iterator("SELECT * FROM adresses WHERE uid = {?} and (cityid IS NULL OR cityid = 0)", $uid); |
| 220 | $erreur = Array(); |
| 221 | |
| 222 | while ($a = $res->next()) { |
| 223 | $new = get_address_infos($ta = get_address_text($a)); |
| 224 | if (compare_addresses_text($ta, get_address_text($new))) { |
| 225 | XDB::execute("UPDATE adresses SET |
| 226 | adr1 = {?}, adr2 = {?}, adr3 = {?}, |
| 227 | cityid = {?}, city = {?}, postcode = {?}, |
| 228 | region = {?}, regiontxt = {?}, country = {?}, |
| 229 | glat = {?}, glng = {?} |
| 230 | WHERE uid = {?} AND adrid = {?}", |
| 231 | $new['adr1'], $new['adr2'], $new['adr3'], |
| 232 | $new['cityid'], $new['city'], $new['postcode'], |
| 233 | $new['region'], $new['regiontxt'], $new['country'], |
| 234 | $new['precise_lat'], $new['precise_lon'], |
| 235 | $uid, $a['adrid']); |
| 236 | $new['store'] = true; |
| 237 | if (!$new['cityid']) $erreur[$a['adrid']] = $new; |
| 238 | } else { |
| 239 | $new['store'] = false; |
| 240 | $erreur[$a['adrid']] = $new; |
| 241 | } |
| 242 | } |
| 243 | return $erreur; |
| 244 | } |
| 245 | // }}} |
| 246 | |
| 247 | // {{{ synchro_city($id) |
| 248 | /** synchronise the local geoloc_city base to geoloc.org |
| 249 | * @param $id the id of the city to synchronize |
| 250 | */ |
| 251 | function synchro_city($id) { |
| 252 | global $globals; |
| 253 | $url = $globals->geoloc->webservice_url."cityFinder.php?method=id&id=".$id."&out=sql"; |
| 254 | if (!($f = @fopen($url, 'r'))) return false; |
| 255 | $s = fgets($f); |
| 256 | if ($s) |
| 257 | return XDB::execute("REPLACE INTO geoloc_city VALUES ".$s) > 0; |
| 258 | } |
| 259 | // }}} |
| 260 | |
| 261 | // {{{ function fix_cities_not_on_map($limit) |
| 262 | function fix_cities_not_on_map($limit=false) |
| 263 | { |
| 264 | $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) WHERE m.city_id IS NULL".($limit?" LIMIT $limit":"")); |
| 265 | $maps = get_cities_maps($missing->fetchColumn()); |
| 266 | if ($maps) |
| 267 | { |
| 268 | $values = ""; |
| 269 | foreach ($maps as $cityid => $maps_c) |
| 270 | foreach ($maps_c as $map_id) |
| 271 | $values .= ",($cityid, $map_id, '')"; |
| 272 | XDB::execute("REPLACE INTO geoloc_city_in_maps VALUES ".substr($values, 1)); |
| 273 | } |
| 274 | else |
| 275 | return false; |
| 276 | return true; |
| 277 | } |
| 278 | |
| 279 | function set_smallest_levels() { |
| 280 | $maxlengths = XDB::iterRow("SELECT MAX(LENGTH(gm.path)), gcim.city_id |
| 281 | FROM geoloc_city_in_maps AS gcim |
| 282 | INNER JOIN geoloc_maps AS gm |
| 283 | USING ( map_id ) |
| 284 | GROUP BY gcim.city_id |
| 285 | "); |
| 286 | while (list($length, $id) = $maxlengths->next()) { |
| 287 | XDB::execute("UPDATE geoloc_city_in_maps AS gcim |
| 288 | INNER JOIN geoloc_maps AS gm USING(map_id) |
| 289 | SET gcim.infos = IF(LENGTH(gm.path) = {?}, 'smallest', '') |
| 290 | WHERE gcim.city_id = {?}", $length, $id); |
| 291 | } |
| 292 | return true; |
| 293 | } |
| 294 | // }}} |
| 295 | |
| 296 | |
| 297 | function geoloc_to_x($lon, $lat) { return deg2rad(1) * $lon *100; } |
| 298 | |
| 299 | function geoloc_to_y($lon, $lat) { |
| 300 | if ($lat < -75) return latToY(-75); |
| 301 | if ($lat > 75) return latToY(75); |
| 302 | return -100 * log(tan(pi()/4 + deg2rad(1)/2*$lat)); |
| 303 | } |
| 304 | |
| 305 | function size_of_city($nb) { $s = round(log($nb + 1)*2,2); if ($s < 1) return 1; return $s; } |
| 306 | function size_of_territory($nb) { return size_of_city($nb); } |
| 307 | |
| 308 | function geoloc_getData_subcities($mapid, $SFields, &$cities, $direct=true) { |
| 309 | for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++) if ($SFields[$i_mapfield]->fieldFormName == 'mapid') break; |
| 310 | $SFields[$i_mapfield] = new MapSField('mapid', array('gcim.map_id'), array('adresses','geoloc_city_in_maps'), array('am','gcim'), array(getadr_join('am'), 'am.cityid = gcim.city_id'), $mapid); |
| 311 | |
| 312 | $fields = new SFieldGroup(true, $SFields); |
| 313 | $where = $fields->get_where_statement(); |
| 314 | if ($where) $where = " AND ".$where; |
| 315 | |
| 316 | $cityres = XDB::iterator(" |
| 317 | SELECT gc.id, |
| 318 | gc.lon / 100000 AS x, gc.lat/100000 AS y, |
| 319 | gc.name, |
| 320 | COUNT(u.user_id) AS pop, |
| 321 | SUM(u.promo % 2) AS yellow |
| 322 | FROM auth_user_md5 AS u |
| 323 | INNER JOIN auth_user_quick AS q ON(u.user_id = q.user_id) |
| 324 | ".$fields->get_select_statement()." |
| 325 | LEFT JOIN geoloc_city AS gc ON(gcim.city_id = gc.id) |
| 326 | WHERE ".($direct?"gcim.infos = 'smallest'":"1")." |
| 327 | $where |
| 328 | GROUP BY gc.id,gc.alias ORDER BY pop DESC"); |
| 329 | while ($c = $cityres->next()) |
| 330 | if ($c['pop'] > 0) |
| 331 | { |
| 332 | $city = $c; |
| 333 | $city['x'] = geoloc_to_x($c['x'], $c['y']); |
| 334 | $city['y'] = geoloc_to_y($c['x'], $c['y']); |
| 335 | $city['size'] = size_of_city($c['pop']); |
| 336 | $cities[$c['id']] = $city; |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | function geoloc_getData_subcountries($mapid, $SFields, $minentities) { |
| 341 | $countries = array(); |
| 342 | $cities = array(); |
| 343 | |
| 344 | if ($mapid === false) |
| 345 | $wheremapid = "WHERE gm.parent IS NULL"; |
| 346 | else |
| 347 | $wheremapid = "WHERE gm.parent = {?}"; |
| 348 | $submapres = XDB::iterator( |
| 349 | "SELECT gm.map_id AS id, gm.name, gm.x, gm.y, gm.xclip, gm.yclip, |
| 350 | gm.width, gm.height, gm.scale, 1 AS rat |
| 351 | FROM geoloc_maps AS gm |
| 352 | ".$wheremapid, Env::v('mapid','')); |
| 353 | |
| 354 | global $globals; |
| 355 | |
| 356 | while ($c = $submapres->next()) |
| 357 | { |
| 358 | $country = $c; |
| 359 | $country['name'] = utf8_decode($country['name']); |
| 360 | $country['color'] = 0xFFFFFF; |
| 361 | $country['swf'] = $globals->geoloc->webservice_url."maps/mercator/map_".$c['id'].".swf"; |
| 362 | $countries[$c['id']] = $country; |
| 363 | } |
| 364 | |
| 365 | if ($mapid === false) return array($countries, $cities); |
| 366 | |
| 367 | geoloc_getData_subcities(Env::i('mapid'), $SFields, $cities); |
| 368 | $nbcities = count($cities); |
| 369 | $nocity = $nbcities == 0; |
| 370 | |
| 371 | for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++) if ($SFields[$i_mapfield]->fieldFormName == 'mapid') break; |
| 372 | $SFields[$i_mapfield] = new MapSField('mapid', array('map.parent'), array('adresses','geoloc_city_in_maps','geoloc_maps'), array('am','gcim','map'), array(getadr_join('am'), 'am.cityid = gcim.city_id', 'map.map_id = gcim.map_id')); |
| 373 | |
| 374 | $fields = new SFieldGroup(true, $SFields); |
| 375 | $where = $fields->get_where_statement(); |
| 376 | if ($where) $where = " WHERE ".$where; |
| 377 | |
| 378 | $countryres = XDB::iterator(" |
| 379 | SELECT map.map_id AS id, |
| 380 | COUNT(u.user_id) AS nbPop, |
| 381 | SUM(u.promo % 2) AS yellow, |
| 382 | COUNT(DISTINCT gcim.city_id) AS nbCities, |
| 383 | SUM(IF(u.user_id IS NULL,0,am.glng)) AS lonPop, |
| 384 | SUM(IF(u.user_id IS NULL, 0,am.glat)) AS latPop |
| 385 | FROM auth_user_md5 AS u |
| 386 | INNER JOIN auth_user_quick AS q ON(u.user_id = q.user_id) |
| 387 | ".$fields->get_select_statement()." |
| 388 | $where |
| 389 | GROUP BY map.map_id ORDER BY NULL", $hierarchy); |
| 390 | |
| 391 | $maxpop = 0; |
| 392 | $nbentities = $nbcities + $countryres->total(); |
| 393 | while ($c = $countryres->next()) |
| 394 | { |
| 395 | $c['latPop'] /= $c['nbPop']; |
| 396 | $c['lonPop'] /= $c['nbPop']; |
| 397 | $c['rad'] = size_of_territory($c['nbPop']); |
| 398 | if ($maxpop < $c['nbPop']) $maxpop = $c['nbPop']; |
| 399 | $c['xPop'] = geoloc_to_x($c['lonPop'], $c['latPop']); |
| 400 | $c['yPop'] = geoloc_to_y($c['lonPop'], $c['latPop']); |
| 401 | $countries[$c['id']] = array_merge($countries[$c['id']], $c); |
| 402 | |
| 403 | $nbcities += $c['nbCities']; |
| 404 | } |
| 405 | |
| 406 | if ($nocity && $nbcities < $minentities) |
| 407 | { |
| 408 | foreach($countries as $i => $c) |
| 409 | { |
| 410 | $countries[$i]['nbPop'] = 0; |
| 411 | if ($c['nbCities'] > 0) |
| 412 | geoloc_getData_subcities($c['id'], $SFields, $cities, false); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | foreach ($countries as $i => $c) if ($c['nbPop'] > 0) |
| 417 | { |
| 418 | $lambda = pow($c['nbPop'] / $maxpop,0.3); |
| 419 | $countries[$i]['color'] = 0x0000FF + round((1-$lambda) * 0xFF)*0x010100; |
| 420 | } |
| 421 | |
| 422 | return array($countries, $cities); |
| 423 | } |
| 424 | // }}} |
| 425 | |
| 426 | // vim:set et sw=4 sts=4 sws=4 foldmethod=marker: |
| 427 | ?> |