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