Avoid null gids.
[platal.git] / include / geoloc.inc.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 Polytechnique.org *
0337d704 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
a7de4ef7 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é
0337d704 25 */
b536b5ae 26function geoloc_country($current, $avail_only = false)
27{
28 if ($avail_only) {
29 $res = XDB::iterRow('SELECT g.a2, g.pays
30 FROM geoloc_pays AS g
31 INNER JOIN adresses AS a ON(a.country = g.a2)
32 GROUP BY g.a2
33 ORDER BY g.pays');
34 } else {
35 $res = XDB::iterRow('SELECT a2,pays FROM geoloc_pays ORDER BY pays');
36 }
0337d704 37 $html = "";
38 while (list($my_id, $my_pays) = $res->next()) {
b536b5ae 39 $html .= sprintf("<option value=\"%s\" %s>%s</option>\n",
40 $my_id, ($current==$my_id?"selected='selected'":""), $my_pays);
0337d704 41 }
42 return $html;
43}
44
0337d704 45/** donne la liste deroulante des regions pour un pays
46 * @param $pays le pays dont on veut afficher les regions
47 * @param $current la region actuellement selectionnee
48 */
b536b5ae 49function geoloc_region($country, $current, $avail_only = false)
50{
51 if ($avail_only) {
52 $res = XDB::iterRow('SELECT r.region, r.name
53 FROM geoloc_region AS r
54 INNER JOIN adresses AS a ON (a.country = r.a2 AND a.region = r.region)
55 WHERE r.a2 = {?}
56 GROUP BY r.region
57 ORDER BY r.name', $country);
58 } else {
59 $res = XDB::iterRow('SELECT region,name
60 FROM geoloc_region
61 WHERE a2 = {?}
62 ORDER BY name', $country);
63 }
0337d704 64 $html = "<option value=\"\"></option>";
65 while (list($regid, $regname) = $res->next()) {
b536b5ae 66 $html .= sprintf("<option value=\"%s\" %s>%s</option>\n",
67 $regid, ($current==$regid?"selected='selected'":""), $regname);
0337d704 68 }
69 return $html;
0337d704 70}
0337d704 71// }}}
72
73// {{{ get_address_infos($txt)
74/** retrieve the infos on a text address
75 * store on the fly the info of the city concerned
76 * @param $txt the raw text of an address
77 */
787bb3d7 78function get_address_infos($txt)
8c4a0c30 79{
56670b6a 80 global $globals;
8c4a0c30 81 $url = $globals->geoloc->webservice_url."address.php?precise=1&txt=" . urlencode($txt);
0337d704 82 if (!($f = @fopen($url, 'r'))) return false;
83 $keys = explode('|',fgets($f));
84 $vals = explode('|',fgets($f));
8eab04f4 85 $infos = empty_address();
2b98ac11 86 foreach ($keys as $i=>$key) {
87 if($vals[$i]) {
88 if ($key == 'sql') {
89 $infos[$key] = $vals[$i];
90 } else {
91 $val = strtr($vals[$i], array(chr(197).chr(147) => "&oelig;"));
8c4a0c30 92 $infos[$key] = $val;
2b98ac11 93 }
94 }
95 }
8eab04f4
FB
96 if (empty($infos['country'])) {
97 $infos['country'] = '00';
98 }
a25cdc91
FB
99 if (isset($infos['sql']) && $infos['sql']) {
100 $sql = explode(', ', trim($infos['sql'], '()'));
101 if (count($sql) == 16) {
102 for ($i = 0 ; $i < 16 ; ++$i) {
103 $sql[$i] = stripslashes(trim($sql[$i], ' \''));
104 }
105 XDB::execute("REPLACE INTO geoloc_city
106 VALUES ({?}, {?}, {?}, {?}, {?}, {?},
107 {?}, {?}, {?}, {?}, {?}, {?},
108 {?}, {?}, {?}, {?})",
109 $sql[0], $sql[1], $sql[2], $sql[3], $sql[4], $sql[5],
110 $sql[6], $sql[7], $sql[8], $sql[9], $sql[10], $sql[11],
111 $sql[12], $sql[13], $sql[14], $sql[15]);
112 }
113 }
5ee95138 114 if (isset($infos['display']) && $infos['display'])
de0485fd
FB
115 XDB::execute("UPDATE geoloc_pays
116 SET display = {?}
117 WHERE a2 = {?}", $infos['display'], $infos['country']);
118 if (isset($infos['cityid'])) {
b536b5ae 119 fix_cities_not_on_map(1, $infos['cityid']);
de0485fd
FB
120 if (floatval($infos['precise_lat']) && floatval($infos['precise_lon'])) {
121 $res = XDB::query("SELECT c.lat / 100000, c.lon / 100000
122 FROM geoloc_city AS c
123 WHERE c.id = {?}", $infos['cityid']);
124 if ($res->numRows()) {
125 list($glat, $glng) = $res->fetchOneRow();
126 $infos['precise_lat'] = $glat;
127 $infos['precise_lon'] = $glng;
128 }
129 }
130 }
0337d704 131 return $infos;
132}
133// }}}
134
56670b6a 135// {{{ get_cities_maps($array)
136/* get all the maps id of the cities contained in an array */
137function get_cities_maps($array)
138{
139 global $globals;
140 implode("\n",$array);
8c4a0c30 141 $url = $globals->geoloc->webservice_url."findMaps.php?datatext=".urlencode(implode("\n", $array));
56670b6a 142 if (!($f = @fopen($url, 'r'))) return false;
143 $maps = array();
144 while (!feof($f))
145 {
146 $l = trim(fgets($f));
147 $tab = explode(';', $l);
148 $i = $tab[0];
149 unset($tab[0]);
150 $maps[$i] = $tab;
151 }
152 return $maps;
153}
154// }}}
155
156// {{{ get_new_maps($url)
157/** set new maps from url **/
158function get_new_maps($url)
159{
a3a049fc 160 if (!($f = @fopen($url, 'r'))) {
161 return false;
162 }
163 XDB::query('TRUNCATE TABLE geoloc_maps');
164 $s = '';
165 while (!feof($f)) {
166 $l = fgetcsv($f, 1024, ';', '"');
167 foreach ($l as $i => $val) {
168 if ($val != 'NULL') {
169 $l[$i] = '\''.addslashes($val).'\'';
170 }
171 }
172 $s .= ',('.implode(',',$l).')';
173 }
174 XDB::execute('INSERT INTO geoloc_maps VALUES '.substr($s, 1));
175 return true;
56670b6a 176}
80244bbe 177// }}}
56670b6a 178
0337d704 179// {{{ get_address_text($adr)
180/** make the text of an address that can be read by a mailman
181 * @param $adr an array with all the usual fields
182 */
787bb3d7 183function get_address_text($adr)
8c4a0c30 184{
0337d704 185 $t = "";
5ee95138 186 if (isset($adr['adr1']) && $adr['adr1']) $t.= $adr['adr1'];
187 if (isset($adr['adr2']) && $adr['adr2']) $t.= "\n".$adr['adr2'];
188 if (isset($adr['adr3']) && $adr['adr3']) $t.= "\n".$adr['adr3'];
0337d704 189 $l = "";
5ee95138 190 if (isset($adr['display']) && $adr['display']) {
80ca1b4e 191 $keys = explode(' ', $adr['display']);
192 foreach ($keys as $key) {
8c4a0c30 193 if (isset($adr[$key])) {
80ca1b4e 194 $l .= " ".$adr[$key];
8c4a0c30 195 } else {
80ca1b4e 196 $l .= " ".$key;
8c4a0c30 197 }
80ca1b4e 198 }
8c4a0c30 199 if ($l) substr($l, 1);
200 } elseif ($adr['country'] == 'US' || $adr['country'] == 'CA' || $adr['country'] == 'GB') {
201 if ($adr['city']) $l .= $adr['city'].",\n";
202 if ($adr['region']) $l .= $adr['region']." ";
203 if ($adr['postcode']) $l .= $adr['postcode'];
204 } else {
205 if (isset($adr['postcode']) && $adr['postcode']) $l .= $adr['postcode']." ";
206 if (isset($adr['city']) && $adr['city']) $l .= $adr['city'];
0337d704 207 }
208 if ($l) $t .= "\n".trim($l);
209 if ($adr['country'] != '00' && (!$adr['countrytxt'] || $adr['countrytxt'] == strtoupper($adr['countrytxt']))) {
08cce2ff 210 $res = XDB::query("SELECT pays FROM geoloc_pays WHERE a2 = {?}", $adr['country']);
0337d704 211 $adr['countrytxt'] = $res->fetchOneCell();
212 }
8c4a0c30 213 if (isset($adr['countrytxt']) && $adr['countrytxt']) {
214 $t .= "\n".$adr['countrytxt'];
215 }
0337d704 216 return trim($t);
217}
218// }}}
219
220// {{{ compare_addresses_text($a, $b)
221/** compares if two address matches
222 * @param $a the raw text of an address
223 * @param $b the raw text of a complete valid address
224 */
8c4a0c30 225function compare_addresses_text($a, $b)
226{
0337d704 227 $ta = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $a));
228 $tb = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $b));
787bb3d7 229
0337d704 230 $la = explode("\n", $ta);
231 $lb = explode("\n", $tb);
232
8c4a0c30 233 if (count($lb) > count($la) + 1) {
234 return false;
235 }
236 foreach ($la as $i=>$l) {
37d44b3b 237 if (levenshtein(trim($l), trim($lb[$i])) > 3) {
8c4a0c30 238 return false;
239 }
240 }
0337d704 241 return true;
242}
243
244// }}}
245
246function empty_address() {
247 return Array(
248 "adr1" => "",
249 "adr2" => "",
250 "adr3" => "",
251 "cityid" => NULL,
252 "city" => "",
253 "postcode" => "",
254 "region" => "",
80ca1b4e 255 "regiontxt" => "",
0337d704 256 "country" => "00",
de0485fd
FB
257 "countrytxt" => "",
258 "precise_lat" => "",
259 "precise_lon" => "");
0337d704 260}
261
262// create a simple address from a text without geoloc
8c4a0c30 263function cut_address($txt)
264{
0337d704 265 $txt = str_replace("\r\n", "\n", $txt);
266 ereg("^([^\n]*)(\n([^\n]*)(\n(.*))?)?$", trim($txt), $a);
267 return array("adr1" => trim($a[1]), "adr2" => trim($a[3]), "adr3" => trim(str_replace("\n", " ", $a[5])));
268}
269
270// {{{ localize_addresses($uid)
271/* localize all the address of a user and modify the database
272 * if the new address match with the old one
273 * @param $uid the id of the user
274 */
8c4a0c30 275function localize_addresses($uid)
276{
277 $res = XDB::iterator("SELECT *
278 FROM adresses
279 WHERE uid = {?} and (cityid IS NULL OR cityid = 0)", $uid);
0337d704 280 $erreur = Array();
281
282 while ($a = $res->next()) {
283 $new = get_address_infos($ta = get_address_text($a));
284 if (compare_addresses_text($ta, get_address_text($new))) {
8c4a0c30 285 XDB::execute("UPDATE adresses
286 SET adr1 = {?}, adr2 = {?}, adr3 = {?},
287 cityid = {?}, city = {?}, postcode = {?},
288 region = {?}, regiontxt = {?}, country = {?},
289 glat = {?}, glng = {?}
290 WHERE uid = {?} AND adrid = {?}",
291 $new['adr1'], $new['adr2'], $new['adr3'],
292 $new['cityid'], $new['city'], $new['postcode'],
293 $new['region'], $new['regiontxt'], $new['country'],
294 $new['precise_lat'], $new['precise_lon'],
295 $uid, $a['adrid']);
296 $new['store'] = true;
297 if (!$new['cityid']) {
298 $erreur[$a['adrid']] = $new;
299 }
0337d704 300 } else {
301 $new['store'] = false;
302 $erreur[$a['adrid']] = $new;
303 }
304 }
305 return $erreur;
306}
307// }}}
308
309// {{{ synchro_city($id)
310/** synchronise the local geoloc_city base to geoloc.org
311 * @param $id the id of the city to synchronize
312 */
787bb3d7 313function synchro_city($id)
8c4a0c30 314{
56670b6a 315 global $globals;
316 $url = $globals->geoloc->webservice_url."cityFinder.php?method=id&id=".$id."&out=sql";
8c4a0c30 317 if (!($f = @fopen($url, 'r'))) {
318 return false;
319 }
0337d704 320 $s = fgets($f);
8c4a0c30 321 if ($s) {
08cce2ff 322 return XDB::execute("REPLACE INTO geoloc_city VALUES ".$s) > 0;
8c4a0c30 323 }
324}
0337d704 325 // }}}
326
56670b6a 327// {{{ function fix_cities_not_on_map($limit)
7f3ac007 328function fix_cities_not_on_map($limit=false, $cityid=false)
56670b6a 329{
8c4a0c30 330 $missing = XDB::query("SELECT c.id
331 FROM geoloc_city AS c
787bb3d7 332 LEFT JOIN geoloc_city_in_maps AS m ON(c.id = m.city_id)
8c4a0c30 333 WHERE m.city_id IS NULL"
334 . ($cityid ? " AND c.id = '" . $cityid . "'" : "" )
335 . ($limit ? " LIMIT $limit" : "" ));
56670b6a 336 $maps = get_cities_maps($missing->fetchColumn());
8c4a0c30 337 if ($maps) {
56670b6a 338 $values = "";
8c4a0c30 339 foreach ($maps as $cityid => $maps_c) {
340 foreach ($maps_c as $map_id) {
56670b6a 341 $values .= ",($cityid, $map_id, '')";
8c4a0c30 342 }
343 }
22cc3370
FB
344 if (strlen($values) > 1) {
345 XDB::execute("REPLACE INTO geoloc_city_in_maps
346 VALUES ".substr($values, 1));
347 }
8c4a0c30 348 } else {
56670b6a 349 return false;
8c4a0c30 350 }
014c8464 351 return true;
352}
56670b6a 353
8c4a0c30 354function set_smallest_levels()
355{
356 $maxlengths = XDB::iterRow("SELECT MAX(LENGTH(gm.path)), gcim.city_id
357 FROM geoloc_city_in_maps AS gcim
358 INNER JOIN geoloc_maps AS gm USING ( map_id )
359 GROUP BY gcim.city_id");
014c8464 360 while (list($length, $id) = $maxlengths->next()) {
8c4a0c30 361 XDB::execute("UPDATE geoloc_city_in_maps AS gcim
362 INNER JOIN geoloc_maps AS gm USING(map_id)
363 SET gcim.infos = IF(LENGTH(gm.path) = {?}, 'smallest', '')
364 WHERE gcim.city_id = {?}", $length, $id);
014c8464 365 }
56670b6a 366 return true;
367}
368// }}}
369
370
8c4a0c30 371function geoloc_to_x($lon, $lat)
372{
373 return deg2rad(1) * $lon *100;
374}
375
376function geoloc_to_y($lon, $lat)
377{
378 if ($lat < -75) {
379 return latToY(-75);
380 }
381 if ($lat > 75) {
382 return latToY(75);
383 }
787bb3d7 384 return -100 * log(tan(pi()/4 + deg2rad(1)/2*$lat));
8c4a0c30 385}
56670b6a 386
8c4a0c30 387function size_of_city($nb)
388{
389 $s = round(log($nb + 1)*2,2);
390 if ($s < 1) {
391 return 1;
392 }
393 return $s;
56670b6a 394}
395
8c4a0c30 396function size_of_territory($nb)
397{
398 return size_of_city($nb);
399}
56670b6a 400
8c4a0c30 401function geoloc_getData_subcities($mapid, $SFields, &$cities, $direct=true)
402{
403 if ($SFields instanceof UserSet) {
404 $set = $SFields;
405 $SFields = array();
406 } else {
407 $set = new UserSet();
408 }
409 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++) {
410 if ($SFields[$i_mapfield]->fieldFormName == 'mapid') {
411 break;
412 }
413 }
414 $SFields[$i_mapfield] = new MapSField('mapid',
415 array('gcim.map_id'),
416 array('adresses','geoloc_city_in_maps'),
417 array('am','gcim'),
418 array(getadr_join('am'), 'am.cityid = gcim.city_id'),
419 $mapid);
2b105fb6 420 $fields = new SFieldGroup(true, $SFields);
421 $where = $fields->get_where_statement();
86b5c8f0 422 $joins = $fields->get_select_statement();
8c4a0c30 423 if ($where) {
424 $where .= ' AND ';
425 }
426 $cityres = $set->get('gc.id,
427 gc.lon / 100000 AS x, gc.lat/100000 AS y,
428 gc.name,
429 COUNT(u.user_id) AS pop,
430 SUM(u.promo % 2) AS yellow',
86b5c8f0 431 "$joins
8c4a0c30 432 LEFT JOIN geoloc_city AS gc ON(gcim.city_id = gc.id)",
433 $where . ($direct ? "gcim.infos = 'smallest'" : '1'),
434 'gc.id, gc.alias',
435 'pop DESC');
06df222b 436 foreach($cityres as $c) {
8c4a0c30 437 if ($c['pop'] > 0) {
2b105fb6 438 $city = $c;
439 $city['x'] = geoloc_to_x($c['x'], $c['y']);
440 $city['y'] = geoloc_to_y($c['x'], $c['y']);
441 $city['size'] = size_of_city($c['pop']);
442 $cities[$c['id']] = $city;
443 }
8c4a0c30 444 }
2b105fb6 445}
446
787bb3d7 447function geoloc_getData_subcountries($mapid, $sin, $minentities)
8c4a0c30 448{
2b105fb6 449 $countries = array();
450 $cities = array();
787bb3d7 451
8c4a0c30 452 if ($mapid === false) {
b536b5ae 453 $wheremapid = "WHERE gm.parent IS NULL";
8c4a0c30 454 } else {
b536b5ae 455 $wheremapid = "WHERE gm.parent = {?}";
8c4a0c30 456 }
08cce2ff 457 $submapres = XDB::iterator(
787bb3d7 458 "SELECT gm.map_id AS id, gm.name, gm.x, gm.y, gm.xclip, gm.yclip,
8c4a0c30 459 gm.width, gm.height, gm.scale, 1 AS rat
460 FROM geoloc_maps AS gm
461 ". $wheremapid, Env::v('mapid',''));
2b105fb6 462
edfc872d 463 global $globals;
464
8c4a0c30 465 while ($c = $submapres->next()) {
2b105fb6 466 $country = $c;
2b105fb6 467 $country['color'] = 0xFFFFFF;
468 $country['swf'] = $globals->geoloc->webservice_url."maps/mercator/map_".$c['id'].".swf";
469 $countries[$c['id']] = $country;
470 }
787bb3d7 471
8c4a0c30 472 if ($mapid === false) {
473 return array($countries, $cities);
474 }
2b105fb6 475
8c4a0c30 476 geoloc_getData_subcities(Env::i('mapid'), $sin, $cities);
b536b5ae 477 $nbcities = count($cities);
478 $nocity = $nbcities == 0;
8c4a0c30 479 if ($sin instanceof UserSet) {
480 $set = $sin;
481 $SFields = array();
482 } else {
483 $set = new UserSet();
484 $SFields = $sin;
485 }
2b105fb6 486
8c4a0c30 487 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++) {
488 if ($SFields[$i_mapfield]->fieldFormName == 'mapid') {
489 break;
490 }
491 }
492 $SFields[$i_mapfield] = new MapSField('mapid',
493 array('map.parent'),
494 array('adresses','geoloc_city_in_maps','geoloc_maps'),
495 array('am','gcim','map'),
787bb3d7
FB
496 array(getadr_join('am'),
497 'am.cityid = gcim.city_id',
8c4a0c30 498 'map.map_id = gcim.map_id'));
b536b5ae 499 $fields = new SFieldGroup(true, $SFields);
86b5c8f0 500 $where = $fields->get_where_statement();
501 $joins = $fields->get_select_statement();
8c4a0c30 502 $countryres = $set->get('map.map_id AS id,
503 COUNT(u.user_id) AS nbPop,
504 SUM(u.promo % 2) AS yellow,
505 COUNT(DISTINCT gcim.city_id) AS nbCities,
506 SUM(IF(u.user_id IS NULL,0,am.glng)) AS lonPop,
507 SUM(IF(u.user_id IS NULL, 0,am.glat)) AS latPop',
86b5c8f0 508 $joins,
509 $where,
8c4a0c30 510 'map.map_id',
511 'NULL');
787bb3d7 512
b536b5ae 513 $maxpop = 0;
06df222b
FB
514 $nbentities = $nbcities + count($countryres);
515 foreach ($countryres as $c) {
b536b5ae 516 $c['latPop'] /= $c['nbPop'];
517 $c['lonPop'] /= $c['nbPop'];
518 $c['rad'] = size_of_territory($c['nbPop']);
519 if ($maxpop < $c['nbPop']) $maxpop = $c['nbPop'];
520 $c['xPop'] = geoloc_to_x($c['lonPop'], $c['latPop']);
521 $c['yPop'] = geoloc_to_y($c['lonPop'], $c['latPop']);
86b5c8f0 522 @$countries[$c['id']] = array_merge($countries[$c['id']], $c);
787bb3d7 523
b536b5ae 524 $nbcities += $c['nbCities'];
787bb3d7
FB
525 }
526
8c4a0c30 527 if ($nocity && $nbcities < $minentities){
528 foreach($countries as $i => $c) {
b536b5ae 529 $countries[$i]['nbPop'] = 0;
86b5c8f0 530 if (@$c['nbCities'] > 0) {
8c4a0c30 531 geoloc_getData_subcities($c['id'], $sin, $cities, false);
787bb3d7 532 }
8c4a0c30 533 }
b536b5ae 534 }
787bb3d7 535
8c4a0c30 536 foreach ($countries as $i => $c) {
c1895524 537 if (@$c['nbPop'] > 0) {
8c4a0c30 538 $lambda = pow($c['nbPop'] / $maxpop,0.3);
539 $countries[$i]['color'] = 0x0000FF + round((1-$lambda) * 0xFF)*0x010100;
540 }
b536b5ae 541 }
787bb3d7
FB
542
543 return array($countries, $cities);
544}
138b3c8e 545// }}}
546
a7de4ef7 547// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 548?>