0a6bfac359a68b94829c2e7aa7aafb4292e342d1
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 // {{{ get_address_text($adr)
23 /** make the text of an address that can be read by a mailman
24 * @param $adr an array with all the usual fields
26 function get_address_text($adr)
29 if (isset($adr['adr1']) && $adr['adr1']) $t.= $adr['adr1'];
30 if (isset($adr['adr2']) && $adr['adr2']) $t.= "\n".$adr['adr2'];
31 if (isset($adr['adr3']) && $adr['adr3']) $t.= "\n".$adr['adr3'];
33 if (isset($adr['display']) && $adr['display']) {
34 $keys = explode(' ', $adr['display']);
35 foreach ($keys as $key) {
36 if (isset($adr[$key])) {
42 if ($l) substr($l, 1);
43 } elseif ($adr['country'] == 'US' ||
$adr['country'] == 'CA' ||
$adr['country'] == 'GB') {
44 if ($adr['city']) $l .= $adr['city'].",\n";
45 if ($adr['region']) $l .= $adr['region']." ";
46 if ($adr['postcode']) $l .= $adr['postcode'];
48 if (isset($adr['postcode']) && $adr['postcode']) $l .= $adr['postcode']." ";
49 if (isset($adr['city']) && $adr['city']) $l .= $adr['city'];
51 if ($l) $t .= "\n".trim($l);
52 if ($adr['country'] != '00' && (!$adr['countrytxt'] ||
$adr['countrytxt'] == strtoupper($adr['countrytxt']))) {
53 $res = XDB
::query("SELECT pays FROM geoloc_pays WHERE a2 = {?}", $adr['country']);
54 $adr['countrytxt'] = $res->fetchOneCell();
56 if (isset($adr['countrytxt']) && $adr['countrytxt']) {
57 $t .= "\n".$adr['countrytxt'];
62 // {{{ compare_addresses_text($a, $b)
63 /** compares if two address matches
64 * @param $a the raw text of an address
65 * @param $b the raw text of a complete valid address
67 function compare_addresses_text($a, $b)
69 $ta = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $a));
70 $tb = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $b));
72 $la = explode("\n", $ta);
73 $lb = explode("\n", $tb);
75 if (count($lb) > count($la) +
1) {
78 foreach ($la as $i => $l) {
79 if (levenshtein(trim($l), trim($lb[$i])) > 3) {
87 // {{{ localize_addresses($uid)
88 /* localize all the address of a user and modify the database
89 * if the new address match with the old one
90 * @param $uid the id of the user
92 function localize_addresses($uid)
94 $res = XDB
::iterator("SELECT *
96 WHERE uid = {?} and (cityid IS NULL OR cityid = 0)", $uid);
99 while ($a = $res->next()) {
100 $new = get_address_infos($ta = get_address_text($a));
101 if (compare_addresses_text($ta, get_address_text($new))) {
102 XDB
::execute("UPDATE adresses
103 SET adr1 = {?}, adr2 = {?}, adr3 = {?},
104 cityid = {?}, city = {?}, postcode = {?},
105 region = {?}, regiontxt = {?}, country = {?},
106 glat = {?}, glng = {?}
107 WHERE uid = {?} AND adrid = {?}",
108 $new['adr1'], $new['adr2'], $new['adr3'],
109 $new['cityid'], $new['city'], $new['postcode'],
110 $new['region'], $new['regiontxt'], $new['country'],
111 $new['precise_lat'], $new['precise_lon'],
113 $new['store'] = true
;
114 if (!$new['cityid']) {
115 $erreur[$a['adrid']] = $new;
118 $new['store'] = false
;
119 $erreur[$a['adrid']] = $new;
125 // {{{ get_address_infos($txt)
126 /** retrieve the infos on a text address
127 * store on the fly the info of the city concerned
128 * @param $txt the raw text of an address
131 function get_address_infos($txt)
135 $url = $globals->geoloc
->webservice_url
."address.php?precise=1&txt=" . urlencode($txt);
136 if ($globals->debug
& DEBUG_BT
) {
137 if (!isset(PlBacktrace
::$bt['Geoloc'])) {
138 new PlBacktrace('Geoloc');
140 PlBacktrace
::$bt['Geoloc']->start($url);
142 $f = @fopen
($url, 'r');
144 if ($globals->debug
& DEBUG_BT
) {
145 PlBacktrace
::$bt['Geoloc']->stop(0, 'Can\'t fetch result');
149 $keys = explode('|',fgets($f));
150 $vals = explode('|',fgets($f));
151 if ($globals->debug
& DEBUG_BT
) {
153 for ($i = 0 ; $i < count($keys) ; ++
$i) {
154 $data[] = array($keys[$i], $vals[$i]);
156 PlBacktrace
::$bt['Geoloc']->stop(count($keys), null
, $data);
158 $infos = empty_address();
159 foreach ($keys as $i=>$key) {
162 $infos[$key] = $vals[$i];
164 $val = strtr($vals[$i], array(chr(197).chr(147) => "œ"));
169 if (empty($infos['country'])) {
170 $infos['country'] = '00';
172 if (isset($infos['sql']) && $infos['sql']) {
173 $sql = explode(', ', trim($infos['sql'], '()'));
174 if (count($sql) == 16) {
175 for ($i = 0 ; $i < 16 ; ++
$i) {
176 $sql[$i] = stripslashes(trim($sql[$i], ' \''));
178 XDB
::execute("REPLACE INTO geoloc_city
179 VALUES ({?}, {?}, {?}, {?}, {?}, {?},
180 {?}, {?}, {?}, {?}, {?}, {?},
181 {?}, {?}, {?}, {?})",
182 $sql[0], $sql[1], $sql[2], $sql[3], $sql[4], $sql[5],
183 $sql[6], $sql[7], $sql[8], $sql[9], $sql[10], $sql[11],
184 $sql[12], $sql[13], $sql[14], $sql[15]);
187 if (isset($infos['display']) && $infos['display'])
188 XDB
::execute("UPDATE geoloc_pays
190 WHERE a2 = {?}", $infos['display'], $infos['country']);
191 if (isset($infos['cityid'])) {
192 fix_cities_not_on_map(1, $infos['cityid']);
193 if (floatval($infos['precise_lat']) && floatval($infos['precise_lon'])) {
194 $res = XDB
::query("SELECT c.lat / 100000, c.lon / 100000
195 FROM geoloc_city AS c
196 WHERE c.id = {?}", $infos['cityid']);
197 if ($res->numRows()) {
198 list($glat, $glng) = $res->fetchOneRow();
199 $infos['precise_lat'] = $glat;
200 $infos['precise_lon'] = $glng;
208 // {{{ synchro_city($id)
209 /** synchronise the local geoloc_city base to geoloc.org
210 * @param $id the id of the city to synchronize
212 function synchro_city($id)
215 $url = $globals->geoloc
->webservice_url
."cityFinder.php?method=id&id=".$id."&out=sql";
216 if (!($f = @fopen
($url, 'r'))) {
221 return XDB
::execute("REPLACE INTO geoloc_city VALUES ".$s) > 0;
225 // {{{ function fix_cities_not_on_map($limit)
226 function fix_cities_not_on_map($limit=false
, $cityid=false
)
228 $missing = XDB
::query("SELECT c.id
229 FROM geoloc_city AS c
230 LEFT JOIN geoloc_city_in_maps AS m ON(c.id = m.city_id)
231 WHERE m.city_id IS NULL"
232 . ($cityid ?
" AND c.id = '" . $cityid . "'" : "" )
233 . ($limit ?
" LIMIT $limit" : "" ));
234 $maps = get_cities_maps($missing->fetchColumn());
237 foreach ($maps as $cityid => $maps_c) {
238 foreach ($maps_c as $map_id) {
239 $values .= ",($cityid, $map_id, '')";
242 if (strlen($values) > 1) {
243 XDB
::execute("REPLACE INTO geoloc_city_in_maps
244 VALUES ".substr($values, 1));
252 function set_smallest_levels()
254 $maxlengths = XDB
::iterRow("SELECT MAX(LENGTH(gm.path)), gcim.city_id
255 FROM geoloc_city_in_maps AS gcim
256 INNER JOIN geoloc_maps AS gm USING ( map_id )
257 GROUP BY gcim.city_id");
258 while (list($length, $id) = $maxlengths->next()) {
259 XDB
::execute("UPDATE geoloc_city_in_maps AS gcim
260 INNER JOIN geoloc_maps AS gm USING(map_id)
261 SET gcim.infos = IF(LENGTH(gm.path) = {?}, 'smallest', '')
262 WHERE gcim.city_id = {?}", $length, $id);
267 // {{{ geoloc_country($current, $avail_only = false)
268 /** donne la liste déroulante des pays
269 * @param $current pays actuellement selectionné
271 function geoloc_country($current, $avail_only = false
)
274 $res = XDB
::iterRow('SELECT g.a2, g.pays
275 FROM geoloc_pays AS g
276 INNER JOIN adresses AS a ON(a.country = g.a2)
280 $res = XDB
::iterRow('SELECT a2,pays FROM geoloc_pays ORDER BY pays');
283 while (list($my_id, $my_pays) = $res->next()) {
284 $html .= sprintf("<option value=\"%s\" %s>%s</option>\n",
285 $my_id, ($current==$my_id?
"selected='selected'":""), $my_pays);
291 // {{{ geoloc_region($country, $current, $avail_only = false)
292 /** donne la liste deroulante des regions pour un pays
293 * @param $pays le pays dont on veut afficher les regions
294 * @param $current la region actuellement selectionnee
296 function geoloc_region($country, $current, $avail_only = false
)
299 $res = XDB
::iterRow('SELECT r.region, r.name
300 FROM geoloc_region AS r
301 INNER JOIN adresses AS a ON (a.country = r.a2 AND a.region = r.region)
304 ORDER BY r.name', $country);
306 $res = XDB
::iterRow('SELECT region,name
309 ORDER BY name', $country);
311 $html = "<option value=\"\"></option>";
312 while (list($regid, $regname) = $res->next()) {
313 $html .= sprintf("<option value=\"%s\" %s>%s</option>\n",
314 $regid, ($current==$regid?
"selected='selected'":""), $regname);
319 // {{{ get_cities_maps($array)
320 /* get all the maps id of the cities contained in an array */
321 function get_cities_maps($array)
324 implode("\n",$array);
325 $url = $globals->geoloc
->webservice_url
."findMaps.php?datatext=".urlencode(implode("\n", $array));
326 if (!($f = @fopen
($url, 'r'))) return false
;
330 $l = trim(fgets($f));
331 $tab = explode(';', $l);
339 // {{{ get_new_maps($url)
340 /** set new maps from url **/
341 function get_new_maps($url)
343 if (!($f = @fopen
($url, 'r'))) {
346 XDB
::query('TRUNCATE TABLE geoloc_maps');
349 $l = fgetcsv($f, 1024, ';', '"');
350 foreach ($l as $i => $val) {
351 if ($val != 'NULL') {
352 $l[$i] = '\''.addslashes($val).'\'';
355 $s .= ',('.implode(',',$l).')';
357 XDB
::execute('INSERT INTO geoloc_maps VALUES '.substr($s, 1));
362 function geoloc_to_x($lon, $lat)
364 return deg2rad(1) * $lon *100;
367 function geoloc_to_y($lon, $lat)
375 return -100 * log(tan(pi()/4 +
deg2rad(1)/2*$lat));
378 function size_of_city($nb)
380 $s = round(log($nb +
1)*2,2);
387 function size_of_territory($nb)
389 return size_of_city($nb);
392 function geoloc_getData_subcities($mapid, $SFields, &$cities, $direct=true
)
394 if ($SFields instanceof UserSet
) {
398 $set = new UserSet();
400 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++
) {
401 if ($SFields[$i_mapfield]->fieldFormName
== 'mapid') {
405 $SFields[$i_mapfield] = new MapSField('mapid',
406 array('gcim.map_id'),
407 array('adresses','geoloc_city_in_maps'),
409 array(getadr_join('am'), 'am.cityid = gcim.city_id'),
411 $fields = new SFieldGroup(true
, $SFields);
412 $where = $fields->get_where_statement();
413 $joins = $fields->get_select_statement();
417 $cityres = $set->get('gc.id,
418 gc.lon / 100000 AS x, gc.lat/100000 AS y,
420 COUNT(u.user_id) AS pop,
421 SUM(u.promo % 2) AS yellow',
423 LEFT JOIN geoloc_city AS gc ON(gcim.city_id = gc.id)",
424 $where . ($direct ?
"gcim.infos = 'smallest'" : '1'),
427 foreach($cityres as $c) {
430 $city['x'] = geoloc_to_x($c['x'], $c['y']);
431 $city['y'] = geoloc_to_y($c['x'], $c['y']);
432 $city['size'] = size_of_city($c['pop']);
433 $cities[$c['id']] = $city;
438 function geoloc_getData_subcountries($mapid, $sin, $minentities)
440 $countries = array();
443 if ($mapid === false
) {
444 $wheremapid = "WHERE gm.parent IS NULL";
446 $wheremapid = "WHERE gm.parent = {?}";
448 $submapres = XDB
::iterator(
449 "SELECT gm.map_id AS id, gm.name, gm.x, gm.y, gm.xclip, gm.yclip,
450 gm.width, gm.height, gm.scale, 1 AS rat
451 FROM geoloc_maps AS gm
452 ". $wheremapid, Env
::v('mapid',''));
456 while ($c = $submapres->next()) {
458 $country['color'] = 0xFFFFFF;
459 $country['swf'] = $globals->geoloc
->webservice_url
."maps/mercator/map_".$c['id'].".swf";
460 $countries[$c['id']] = $country;
463 if ($mapid === false
) {
464 return array($countries, $cities);
467 geoloc_getData_subcities(Env
::i('mapid'), $sin, $cities);
468 $nbcities = count($cities);
469 $nocity = $nbcities == 0;
470 if ($sin instanceof UserSet
) {
474 $set = new UserSet();
478 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++
) {
479 if ($SFields[$i_mapfield]->fieldFormName
== 'mapid') {
483 $SFields[$i_mapfield] = new MapSField('mapid',
485 array('adresses','geoloc_city_in_maps','geoloc_maps'),
486 array('am','gcim','map'),
487 array(getadr_join('am'),
488 'am.cityid = gcim.city_id',
489 'map.map_id = gcim.map_id'));
490 $fields = new SFieldGroup(true
, $SFields);
491 $where = $fields->get_where_statement();
492 $joins = $fields->get_select_statement();
493 $countryres = $set->get('map.map_id AS id,
494 COUNT(u.user_id) AS nbPop,
495 SUM(u.promo % 2) AS yellow,
496 COUNT(DISTINCT gcim.city_id) AS nbCities,
497 SUM(IF(u.user_id IS NULL,0,am.glng)) AS lonPop,
498 SUM(IF(u.user_id IS NULL, 0,am.glat)) AS latPop',
505 $nbentities = $nbcities +
count($countryres);
506 foreach ($countryres as $c) {
507 $c['latPop'] /= $c['nbPop'];
508 $c['lonPop'] /= $c['nbPop'];
509 $c['rad'] = size_of_territory($c['nbPop']);
510 if ($maxpop < $c['nbPop']) $maxpop = $c['nbPop'];
511 $c['xPop'] = geoloc_to_x($c['lonPop'], $c['latPop']);
512 $c['yPop'] = geoloc_to_y($c['lonPop'], $c['latPop']);
513 @$countries[$c['id']] = array_merge($countries[$c['id']], $c);
515 $nbcities +
= $c['nbCities'];
518 if ($nocity && $nbcities < $minentities){
519 foreach($countries as $i => $c) {
520 $countries[$i]['nbPop'] = 0;
521 if (@$c['nbCities'] > 0) {
522 geoloc_getData_subcities($c['id'], $sin, $cities, false
);
527 foreach ($countries as $i => $c) {
528 if (@$c['nbPop'] > 0) {
529 $lambda = pow($c['nbPop'] / $maxpop,0.3);
530 $countries[$i]['color'] = 0x0000FF +
round((1-$lambda) * 0xFF)*0x010100;
534 return array($countries, $cities);
537 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: