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