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