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