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