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