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