2 /***************************************************************************
3 * Copyright (C) 2003-2006 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
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é
26 function geoloc_country($current) {
27 $res = XDB
::iterRow('SELECT a2,pays FROM geoloc_pays ORDER BY pays');
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);
36 function _geoloc_country_smarty($params){
37 if(!isset($params['country']))
39 return geoloc_country($params['country']);
41 $GLOBALS['page']->register_function('geoloc_country', '_geoloc_country_smarty');
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
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);
57 function _geoloc_region_smarty($params){
58 if(!isset($params['country']))
60 if(!isset($params['region']))
62 return geoloc_region($params['country'], $params['region']);
64 $GLOBALS['page']->register_function('geoloc_region', '_geoloc_region_smarty');
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
72 function get_address_infos($txt) {
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));
79 foreach ($keys as $i=>$key) {
82 $infos[$key] = $vals[$i];
84 $val = strtr($vals[$i], array(chr(197).chr(147) => "œ"));
85 $infos[$key] = (iconv('utf-8', 'utf-8', $val) == $val) ?
utf8_decode($val) : $val;
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']);
97 // {{{ get_cities_maps($array)
98 /* get all the maps id of the cities contained in an array */
99 function get_cities_maps($array)
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
;
108 $l = trim(fgets($f));
109 $tab = explode(';', $l);
118 // {{{ get_new_maps($url)
119 /** set new maps from url **/
120 function get_new_maps($url)
122 if (!($f = @fopen
($url, 'r'))) {
125 XDB
::query('TRUNCATE TABLE geoloc_maps');
128 $l = fgetcsv($f, 1024, ';', '"');
129 foreach ($l as $i => $val) {
130 if ($val != 'NULL') {
131 $l[$i] = '\''.addslashes($val).'\'';
134 $s .= ',('.implode(',',$l).')';
136 XDB
::execute('INSERT INTO geoloc_maps VALUES '.substr($s, 1));
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
145 function get_address_text($adr) {
147 if ($adr['adr1']) $t.= $adr['adr1'];
148 if ($adr['adr2']) $t.= "\n".$adr['adr2'];
149 if ($adr['adr3']) $t.= "\n".$adr['adr3'];
151 if ($adr['display']) {
152 $keys = explode(' ', $adr['display']);
153 foreach ($keys as $key) {
154 if (isset($adr[$key]))
155 $l .= " ".$adr[$key];
159 if ($l) $l = substr($l, 1);
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'];
168 if ($adr['postcode']) $l .= $adr['postcode']." ";
169 if ($adr['city']) $l .= $adr['city'];
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();
177 if ($adr['countrytxt']) $t .= "\n".$adr['countrytxt'];
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
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));
191 $la = explode("\n", $ta);
192 $lb = explode("\n", $tb);
194 if (count($lb) > count($la) +
1) return false
;
195 foreach ($la as $i=>$l) if (levenshtein($l, $lb[$i]) > 3) return false
;
201 function empty_address() {
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])));
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
227 function localize_addresses($uid) {
228 $res = XDB
::iterator("SELECT * FROM adresses WHERE uid = {?} and (cityid IS NULL OR cityid = 0)", $uid);
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'],
245 $new['store'] = true
;
246 if (!$new['cityid']) $erreur[$a['adrid']] = $new;
248 $new['store'] = false
;
249 $erreur[$a['adrid']] = $new;
256 // {{{ synchro_city($id)
257 /** synchronise the local geoloc_city base to geoloc.org
258 * @param $id the id of the city to synchronize
260 function synchro_city($id) {
262 $url = $globals->geoloc
->webservice_url
."cityFinder.php?method=id&id=".$id."&out=sql";
263 if (!($f = @fopen
($url, 'r'))) return false
;
266 return XDB
::execute("REPLACE INTO geoloc_city VALUES ".$s) > 0;
270 // {{{ function fix_cities_not_on_map($limit)
271 function fix_cities_not_on_map($limit=false
)
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());
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));
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
293 GROUP BY gcim.city_id
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);
306 function geoloc_to_x($lon, $lat) { return deg2rad(1) * $lon *100; }
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));
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); }
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);
321 $fields = new SFieldGroup(true
, $SFields);
322 $where = $fields->get_where_statement();
323 if ($where) $where = " AND ".$where;
325 $cityres = XDB
::iterator("
327 gc.lon / 100000 AS x, gc.lat/100000 AS y,
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")."
337 GROUP BY gc.id,gc.alias ORDER BY pop DESC");
338 while ($c = $cityres->next())
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;
349 function geoloc_getData_subcountries($mapid, $SFields, $minentities) {
350 $countries = array();
353 if ($mapid === false
)
354 $wheremapid = "WHERE gm.parent IS NULL";
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',''));
365 while ($c = $submapres->next())
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;
374 if ($mapid === false
) return array($countries, $cities);
376 geoloc_getData_subcities(Env
::i('mapid'), $SFields, $cities);
377 $nbcities = count($cities);
378 $nocity = $nbcities == 0;
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'));
383 $fields = new SFieldGroup(true
, $SFields);
384 $where = $fields->get_where_statement();
385 if ($where) $where = " WHERE ".$where;
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()."
398 GROUP BY map.map_id ORDER BY NULL", $hierarchy);
401 $nbentities = $nbcities +
$countryres->total();
402 while ($c = $countryres->next())
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);
412 $nbcities +
= $c['nbCities'];
415 if ($nocity && $nbcities < $minentities)
417 foreach($countries as $i => $c)
419 $countries[$i]['nbPop'] = 0;
420 if ($c['nbCities'] > 0)
421 geoloc_getData_subcities($c['id'], $SFields, $cities, false
);
425 foreach ($countries as $i => $c) if ($c['nbPop'] > 0)
427 $lambda = pow($c['nbPop'] / $maxpop,0.3);
428 $countries[$i]['color'] = 0x0000FF +
round((1-$lambda) * 0xFF)*0x010100;
431 return array($countries, $cities);
435 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker: