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 // {{{ geoloc_country($current, $avail_only = false)
23 /** donne la liste déroulante des pays
24 * @param $current pays actuellement selectionné
26 function geoloc_country($current, $avail_only = false
)
29 $res = XDB
::iterRow('SELECT g.a2, g.pays
31 INNER JOIN adresses AS a ON(a.country = g.a2)
35 $res = XDB
::iterRow('SELECT a2,pays FROM geoloc_pays ORDER BY pays');
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);
46 // {{{ geoloc_region($country, $current, $avail_only = false)
47 /** donne la liste deroulante des regions pour un pays
48 * @param $pays le pays dont on veut afficher les regions
49 * @param $current la region actuellement selectionnee
51 function geoloc_region($country, $current, $avail_only = false
)
54 $res = XDB
::iterRow('SELECT r.region, r.name
55 FROM geoloc_region AS r
56 INNER JOIN adresses AS a ON (a.country = r.a2 AND a.region = r.region)
59 ORDER BY r.name', $country);
61 $res = XDB
::iterRow('SELECT region,name
64 ORDER BY name', $country);
66 $html = "<option value=\"\"></option>";
67 while (list($regid, $regname) = $res->next()) {
68 $html .= sprintf("<option value=\"%s\" %s>%s</option>\n",
69 $regid, ($current==$regid?
"selected='selected'":""), $regname);
74 // {{{ get_cities_maps($array)
75 /* get all the maps id of the cities contained in an array */
76 function get_cities_maps($array)
80 $url = $globals->geoloc
->webservice_url
."findMaps.php?datatext=".urlencode(implode("\n", $array));
81 if (!($f = @fopen
($url, 'r'))) return false
;
86 $tab = explode(';', $l);
94 // {{{ get_new_maps($url)
95 /** set new maps from url **/
96 function get_new_maps($url)
98 if (!($f = @fopen
($url, 'r'))) {
101 XDB
::query('TRUNCATE TABLE geoloc_maps');
104 $l = fgetcsv($f, 1024, ';', '"');
105 foreach ($l as $i => $val) {
106 if ($val != 'NULL') {
107 $l[$i] = '\''.addslashes($val).'\'';
110 $s .= ',('.implode(',',$l).')';
112 XDB
::execute('INSERT INTO geoloc_maps VALUES '.substr($s, 1));
116 // {{{ geolocGoogle (array $address)
117 // retrieve the infos on a text address
119 function geolocGoogle (array &$address)
122 * www.polytechnique.org:
123 * ABQIAAAAIlFNe1A494mwR9Zf4R3t0xRsw9kzQBeaENRP66lRw7Ru3uVJcRR73lY1tmAdYGqw-pyHTdynmicz0w
124 * www.polytechnique.net and dev.polytechnique.net:
125 * ABQIAAAAIlFNe1A494mwR9Zf4R3t0xT8SmDPc83znji5QwIVTgAvxgX5zRRMagHx_rmGeQF5SnCzmyqiSeSAxA
127 * ABQIAAAAIlFNe1A494mwR9Zf4R3t0xQ31muaRX97DHXrOFfMwMMCxEnhaxQIPDe9Ct3D6ZvWuGiWllkGAP3IqA
130 * http://code.google.com/intl/fr/apis/maps/documentation/geocoding/
131 * http://code.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy */
134 $key = 'ABQIAAAAIlFNe1A494mwR9Zf4R3t0xQ31muaRX97DHXrOFfMwMMCxEnhaxQIPDe9Ct3D6ZvWuGiWllkGAP3IqA';
135 $webservice = "http://maps.google.com/maps/geo?";
136 $baseurl = $webservice . "&key=$key" . "&sensor=false&output=json&oe=utf8&gl=fr&hl=fr&q=";
138 $url = $baseurl . urlencode($address['text']);
139 if (!geolocalizeAddress($url, $gAddress)) {
140 $addressLines = explode("\n", $address['text']);
141 $nbLines = count($addressLines);
142 $currentState = array();
144 for ($i = 1; !$success && ($i < $nbLines); $i++
) {
145 for ($j = 0; $j < $i; $j++
) {
146 $currentState[$j] = 0;
148 while($j < $nbLines) {
149 $currentState[$j] = 1;
153 $partialAddress = "";
154 for ($j = 0; $j < $nbLines; $j++
) {
155 if ($currentState[$j] == 1) {
156 $partialAddress .= $addressLines[$j] . " ";
159 $url = $baseurl . urlencode(trim($partialAddress));
160 $success = geolocalizeAddress($url, $gAddress);
161 } while (!$success && nextCurrentState($currentState, $nbLines));
165 for ($i = 0; $i < $nbLines; $i++
) {
166 if ($currentState[$i] == 0) {
167 $extras .= $addressLines[$i] . ", ";
171 $address['extras'] = $extras;
175 fillAddress($address, $gAddress);
176 formatAddress($address);
182 // {{{ nextCurrentState(&$currentState, $nbLines)
184 function nextCurrentState(&$currentState, $nbLines)
188 for ($i = 0; $i < $nbLines; $i++
) {
189 if ($currentState[$i] == 1) {
198 } elseif ($currentState[$lastOne - 1] == 0) {
199 $currentState[$lastOne - 1] = 1;
200 $currentState[$lastOne] = 0;
204 for ($j = 0; $j < $lastOne; $j++
) {
205 if ($currentState[$j] == 0) {
209 if ($lastZero == -1) {
212 $currentState[$lastZero] = 1;
213 for ($k = $lastZero +
1; $k < $lastZero +
$nbZeros; $k++
) {
214 $currentState[$k] = 0;
216 for ($k = $lastZero +
$nbZeros; $k < $nbLines; $k++
) {
217 $currentState[$k] = 1;
225 // {{{ geolocalizeAddress ($url, &$result)
227 function geolocalizeAddress ($url, &$result = array())
231 if ($globals->debug
& DEBUG_BT
) {
232 if (!isset(PlBacktrace
::$bt['Geoloc'])) {
233 new PlBacktrace('Geoloc');
235 PlBacktrace
::$bt['Geoloc']->start($url);
238 if ($f = file_get_contents($url, 'r')) {
239 $data = json_decode($f, true
);
240 if ($globals->debug
& DEBUG_BT
) {
241 PlBacktrace
::$bt['Geoloc']->stop(count($data), null
, $data);
243 if ($data['Status']['code'] != 200) {
246 $nbResults = count($data['Placemark']);
248 if ($nbResults > 1) {
249 $bestAccuracy = $data['Placemark'][0]['AddressDetails']['Accuracy'];
250 for ($i = 1; $i < $nbResults; $i++
) {
251 if ($data['Placemark'][$i]['AddressDetails']['Accuracy'] > $bestAccuracy) {
252 unset($data['Placemark'][$idAccuracy]);
253 $bestAccuracy = $data['Placemark'][$i]['AddressDetails']['Accuracy'];
256 unset($data['Placemark'][$i]);
260 $result = $data['Placemark'][$idAccuracy];
263 if ($globals->debug
& DEBUG_BT
) {
264 PlBacktrace
::$bt['Geoloc']->stop(0, "Can't fetch result.");
270 // {{{ fillAddress(array &$address, $gAddress)
272 function fillAddress(array &$address, array $gAddress)
274 // An address is Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
275 // with all the shortcuts possible
278 $address['geoloc'] = str_replace(", ", "\n", $gAddress['address']);
279 if (isset($gAddress['AddressDetails']['Accuracy'])) {
280 $address['accuracy'] = $gAddress['AddressDetails']['Accuracy'];
282 $currentPosition = $gAddress['AddressDetails'];
283 if (isset($currentPosition['Country'])) {
284 $currentPosition = $currentPosition['Country'];
285 $address['countryId'] = $currentPosition['CountryNameCode'];
286 $address['country'] = $currentPosition['CountryName'];
288 if (isset($currentPosition['AdministrativeArea'])) {
289 $currentPosition = $currentPosition['AdministrativeArea'];
290 $address['administrativeAreaName'] = $currentPosition['AdministrativeAreaName'];
292 if (isset($currentPosition['SubAdministrativeArea'])) {
293 $currentPosition = $currentPosition['SubAdministrativeArea'];
294 $address['subAdministrativeAreaName'] = $currentPosition['SubAdministrativeAreaName'];
296 if (isset($currentPosition['Locality'])) {
297 $currentPosition = $currentPosition['Locality'];
298 $address['localityName'] = $currentPosition['LocalityName'];
300 if (isset($currentPosition['Thoroughfare'])) {
301 $address['thoroughfareName'] = $currentPosition['Thoroughfare']['ThoroughfareName'];
303 if (isset($currentPosition['PostalCode'])) {
304 $address['postalCode'] = $currentPosition['PostalCode']['PostalCodeNumber'];
308 if (isset($gAddress['Point']['coordinates'][0])) {
309 $address['latitude'] = $gAddress['Point']['coordinates'][0];
311 if (isset($gAddress['Point']['coordinates'][1])) {
312 $address['longitude'] = $gAddress['Point']['coordinates'][1];
314 if (isset($gAddress['ExtendedData']['LatLonBox']['north'])) {
315 $address['north'] = $gAddress['ExtendedData']['LatLonBox']['north'];
317 if (isset($gAddress['ExtendedData']['LatLonBox']['south'])) {
318 $address['south'] = $gAddress['ExtendedData']['LatLonBox']['south'];
320 if (isset($gAddress['ExtendedData']['LatLonBox']['east'])) {
321 $address['east'] = $gAddress['ExtendedData']['LatLonBox']['east'];
323 if (isset($gAddress['ExtendedData']['LatLonBox']['west'])) {
324 $address['west'] = $gAddress['ExtendedData']['LatLonBox']['west'];
329 // {{{ formatAddress(array &$address)
331 function formatAddress(array &$address)
334 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
335 array("", "\n"), $address['text']));
336 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
337 array("", "\n"), $address['geoloc']));
338 if (isset($address['extras']) && $address['extras']) {
339 $address['geoloc'] = $address['extras'] . "\n" . $address['geoloc'];
340 $extras = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
341 array("", "\n"), $address['extras']));
342 $geoloc = $extras . $geoloc;
343 unset($address['extras']);
346 $arrayText = explode("\n", $text);
347 $arrayGeoloc = explode("\n", $geoloc);
348 $nbText = count($arrayText);
349 $nbGeoloc = count($arrayGeoloc);
351 if ((($nbText > $nbGeoloc) ||
($nbText < $nbGeoloc - 1))
352 ||
(($nbText == $nbGeoloc - 1) && ($arrayText[$nbText - 1] == strtoupper($address['country'])))) {
355 foreach ($arrayText as $i => $lignText) {
356 if (levenshtein($lignText, trim($arrayGeoloc[$i])) > 3) {
362 $address['text'] = $address['geoloc'];
363 unset($address['geoloc']);
368 // {{{ cleanText(&$text)
370 function cleanText(&$text)
372 $lines = explode("\n", $text);
375 for ($i = 0; $i < $n; $i++
) {
376 if (trim($lines[$i])) {
377 $text .= trim($lines[$i]) . "\n";
384 // {{{ getAreaId(array &$address, $area)
386 function getAreaId(array &$address, $area)
388 if (isset($address[$area . 'Name'])) {
389 $res = XDB
::query("SELECT id
390 FROM geoloc_" . $area . "
392 $address[$area . 'Name']);
393 if ($res->numRows() == 0) {
394 $address[$area . 'Id'] = XDB
::execute("INSERT INTO geoloc_" . $area . " (name, country)
396 $address[$area . 'Name'], $address['countryId']);
398 $address[$area . 'Id'] = $res->fetchOneCell();
404 // {{{ get_address_text($adr)
405 /** make the text of an address that can be read by a mailman
406 * @param $adr an array with all the usual fields
408 function get_address_text($adr)
411 if (isset($adr['adr1']) && $adr['adr1']) $t.= $adr['adr1'];
412 if (isset($adr['adr2']) && $adr['adr2']) $t.= "\n".$adr['adr2'];
413 if (isset($adr['adr3']) && $adr['adr3']) $t.= "\n".$adr['adr3'];
415 if (isset($adr['display']) && $adr['display']) {
416 $keys = explode(' ', $adr['display']);
417 foreach ($keys as $key) {
418 if (isset($adr[$key])) {
419 $l .= " ".$adr[$key];
424 if ($l) substr($l, 1);
425 } elseif ($adr['country'] == 'US' ||
$adr['country'] == 'CA' ||
$adr['country'] == 'GB') {
426 if ($adr['city']) $l .= $adr['city'].",\n";
427 if ($adr['region']) $l .= $adr['region']." ";
428 if ($adr['postcode']) $l .= $adr['postcode'];
430 if (isset($adr['postcode']) && $adr['postcode']) $l .= $adr['postcode']." ";
431 if (isset($adr['city']) && $adr['city']) $l .= $adr['city'];
433 if ($l) $t .= "\n".trim($l);
434 if ($adr['country'] != '00' && (!$adr['countrytxt'] ||
$adr['countrytxt'] == strtoupper($adr['countrytxt']))) {
435 $res = XDB
::query("SELECT pays FROM geoloc_pays WHERE a2 = {?}", $adr['country']);
436 $adr['countrytxt'] = $res->fetchOneCell();
438 if (isset($adr['countrytxt']) && $adr['countrytxt']) {
439 $t .= "\n".$adr['countrytxt'];
444 // {{{ compare_addresses_text($a, $b)
445 /** compares if two address matches
446 * @param $a the raw text of an address
447 * @param $b the raw text of a complete valid address
449 function compare_addresses_text($a, $b)
451 $ta = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $a));
452 $tb = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $b));
454 $la = explode("\n", $ta);
455 $lb = explode("\n", $tb);
457 if (count($lb) > count($la) +
1) {
460 foreach ($la as $i => $l) {
461 if (levenshtein(trim($l), trim($lb[$i])) > 3) {
469 // {{{ fixNumber($oldtext, &$new)
471 function fixNumber($oldtext, &$new)
473 $ThoroughfareName = $new['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['Thoroughfare']['ThoroughfareName'];
474 $ThoroughfareName = trim(strtoupper(preg_replace(array("/[,\"'#~:;_\-]/", "/\r\n/"),
475 array("", "\n"), $ThoroughfareName)));
476 $oldarray = explode("\n", trim(strtoupper(preg_replace(array("/[,\"'#~:;_\-]/", "/\r\n/"),
477 array("", "\n"), $oldtext))));
478 $mindist = strlen($ThoroughfareName);
480 foreach ($oldarray as $i => $oldline) {
481 if (($l = levenshtein(trim($oldline), $ThoroughfareName)) < $mindist) {
486 $nb = explode(" ", $oldarray[$minpos]);
487 $new['text'] = $nb[0] . " " . $new['text'];
491 // {{{ localize_addresses($uid)
492 /* localize all the address of a user and modify the database
493 * if the new address match with the old one
494 * @param $uid the id of the user
496 function localize_addresses($uid)
498 $res = XDB
::iterator("SELECT *
500 WHERE uid = {?} and (cityid IS NULL OR cityid = 0)", $uid);
503 while ($a = $res->next()) {
504 $new = get_address_infos($ta = get_address_text($a));
505 if (compare_addresses_text($ta, get_address_text($new))) {
506 XDB
::execute("UPDATE adresses
507 SET adr1 = {?}, adr2 = {?}, adr3 = {?},
508 cityid = {?}, city = {?}, postcode = {?},
509 region = {?}, regiontxt = {?}, country = {?},
510 glat = {?}, glng = {?}
511 WHERE uid = {?} AND adrid = {?}",
512 $new['adr1'], $new['adr2'], $new['adr3'],
513 $new['cityid'], $new['city'], $new['postcode'],
514 $new['region'], $new['regiontxt'], $new['country'],
515 $new['precise_lat'], $new['precise_lon'],
517 $new['store'] = true
;
518 if (!$new['cityid']) {
519 $erreur[$a['adrid']] = $new;
522 $new['store'] = false
;
523 $erreur[$a['adrid']] = $new;
529 // {{{ get_address_infos($txt)
530 /** retrieve the infos on a text address
531 * store on the fly the info of the city concerned
532 * @param $txt the raw text of an address
535 function get_address_infos($txt)
539 $url = $globals->geoloc
->webservice_url
."address.php?precise=1&txt=" . urlencode($txt);
540 if ($globals->debug
& DEBUG_BT
) {
541 if (!isset(PlBacktrace
::$bt['Geoloc'])) {
542 new PlBacktrace('Geoloc');
544 PlBacktrace
::$bt['Geoloc']->start($url);
546 $f = @fopen
($url, 'r');
548 if ($globals->debug
& DEBUG_BT
) {
549 PlBacktrace
::$bt['Geoloc']->stop(0, 'Can\'t fetch result');
553 $keys = explode('|',fgets($f));
554 $vals = explode('|',fgets($f));
555 if ($globals->debug
& DEBUG_BT
) {
557 for ($i = 0 ; $i < count($keys) ; ++
$i) {
558 $data[] = array($keys[$i], $vals[$i]);
560 PlBacktrace
::$bt['Geoloc']->stop(count($keys), null
, $data);
562 $infos = empty_address();
563 foreach ($keys as $i=>$key) {
566 $infos[$key] = $vals[$i];
568 $val = strtr($vals[$i], array(chr(197).chr(147) => "œ"));
573 if (empty($infos['country'])) {
574 $infos['country'] = '00';
576 if (isset($infos['sql']) && $infos['sql']) {
577 $sql = explode(', ', trim($infos['sql'], '()'));
578 if (count($sql) == 16) {
579 for ($i = 0 ; $i < 16 ; ++
$i) {
580 $sql[$i] = stripslashes(trim($sql[$i], ' \''));
582 XDB
::execute("REPLACE INTO geoloc_city
583 VALUES ({?}, {?}, {?}, {?}, {?}, {?},
584 {?}, {?}, {?}, {?}, {?}, {?},
585 {?}, {?}, {?}, {?})",
586 $sql[0], $sql[1], $sql[2], $sql[3], $sql[4], $sql[5],
587 $sql[6], $sql[7], $sql[8], $sql[9], $sql[10], $sql[11],
588 $sql[12], $sql[13], $sql[14], $sql[15]);
591 if (isset($infos['display']) && $infos['display'])
592 XDB
::execute("UPDATE geoloc_pays
594 WHERE a2 = {?}", $infos['display'], $infos['country']);
595 if (isset($infos['cityid'])) {
596 fix_cities_not_on_map(1, $infos['cityid']);
597 if (floatval($infos['precise_lat']) && floatval($infos['precise_lon'])) {
598 $res = XDB
::query("SELECT c.lat / 100000, c.lon / 100000
599 FROM geoloc_city AS c
600 WHERE c.id = {?}", $infos['cityid']);
601 if ($res->numRows()) {
602 list($glat, $glng) = $res->fetchOneRow();
603 $infos['precise_lat'] = $glat;
604 $infos['precise_lon'] = $glng;
612 // {{{ synchro_city($id)
613 /** synchronise the local geoloc_city base to geoloc.org
614 * @param $id the id of the city to synchronize
616 function synchro_city($id)
619 $url = $globals->geoloc
->webservice_url
."cityFinder.php?method=id&id=".$id."&out=sql";
620 if (!($f = @fopen
($url, 'r'))) {
625 return XDB
::execute("REPLACE INTO geoloc_city VALUES ".$s) > 0;
629 // {{{ function fix_cities_not_on_map($limit)
630 function fix_cities_not_on_map($limit=false
, $cityid=false
)
632 $missing = XDB
::query("SELECT c.id
633 FROM geoloc_city AS c
634 LEFT JOIN geoloc_city_in_maps AS m ON(c.id = m.city_id)
635 WHERE m.city_id IS NULL"
636 . ($cityid ?
" AND c.id = '" . $cityid . "'" : "" )
637 . ($limit ?
" LIMIT $limit" : "" ));
638 $maps = get_cities_maps($missing->fetchColumn());
641 foreach ($maps as $cityid => $maps_c) {
642 foreach ($maps_c as $map_id) {
643 $values .= ",($cityid, $map_id, '')";
646 if (strlen($values) > 1) {
647 XDB
::execute("REPLACE INTO geoloc_city_in_maps
648 VALUES ".substr($values, 1));
656 function set_smallest_levels()
658 $maxlengths = XDB
::iterRow("SELECT MAX(LENGTH(gm.path)), gcim.city_id
659 FROM geoloc_city_in_maps AS gcim
660 INNER JOIN geoloc_maps AS gm USING ( map_id )
661 GROUP BY gcim.city_id");
662 while (list($length, $id) = $maxlengths->next()) {
663 XDB
::execute("UPDATE geoloc_city_in_maps AS gcim
664 INNER JOIN geoloc_maps AS gm USING(map_id)
665 SET gcim.infos = IF(LENGTH(gm.path) = {?}, 'smallest', '')
666 WHERE gcim.city_id = {?}", $length, $id);
672 function geoloc_to_x($lon, $lat)
674 return deg2rad(1) * $lon *100;
677 function geoloc_to_y($lon, $lat)
685 return -100 * log(tan(pi()/4 +
deg2rad(1)/2*$lat));
688 function size_of_city($nb)
690 $s = round(log($nb +
1)*2,2);
697 function size_of_territory($nb)
699 return size_of_city($nb);
702 function geoloc_getData_subcities($mapid, $SFields, &$cities, $direct=true
)
704 if ($SFields instanceof UserSet
) {
708 $set = new UserSet();
710 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++
) {
711 if ($SFields[$i_mapfield]->fieldFormName
== 'mapid') {
715 $SFields[$i_mapfield] = new MapSField('mapid',
716 array('gcim.map_id'),
717 array('adresses','geoloc_city_in_maps'),
719 array(getadr_join('am'), 'am.cityid = gcim.city_id'),
721 $fields = new SFieldGroup(true
, $SFields);
722 $where = $fields->get_where_statement();
723 $joins = $fields->get_select_statement();
727 $cityres = $set->get('gc.id,
728 gc.lon / 100000 AS x, gc.lat/100000 AS y,
730 COUNT(u.user_id) AS pop,
731 SUM(u.promo % 2) AS yellow',
733 LEFT JOIN geoloc_city AS gc ON(gcim.city_id = gc.id)",
734 $where . ($direct ?
"gcim.infos = 'smallest'" : '1'),
737 foreach($cityres as $c) {
740 $city['x'] = geoloc_to_x($c['x'], $c['y']);
741 $city['y'] = geoloc_to_y($c['x'], $c['y']);
742 $city['size'] = size_of_city($c['pop']);
743 $cities[$c['id']] = $city;
748 function geoloc_getData_subcountries($mapid, $sin, $minentities)
750 $countries = array();
753 if ($mapid === false
) {
754 $wheremapid = "WHERE gm.parent IS NULL";
756 $wheremapid = "WHERE gm.parent = {?}";
758 $submapres = XDB
::iterator(
759 "SELECT gm.map_id AS id, gm.name, gm.x, gm.y, gm.xclip, gm.yclip,
760 gm.width, gm.height, gm.scale, 1 AS rat
761 FROM geoloc_maps AS gm
762 ". $wheremapid, Env
::v('mapid',''));
766 while ($c = $submapres->next()) {
768 $country['color'] = 0xFFFFFF;
769 $country['swf'] = $globals->geoloc
->webservice_url
."maps/mercator/map_".$c['id'].".swf";
770 $countries[$c['id']] = $country;
773 if ($mapid === false
) {
774 return array($countries, $cities);
777 geoloc_getData_subcities(Env
::i('mapid'), $sin, $cities);
778 $nbcities = count($cities);
779 $nocity = $nbcities == 0;
780 if ($sin instanceof UserSet
) {
784 $set = new UserSet();
788 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++
) {
789 if ($SFields[$i_mapfield]->fieldFormName
== 'mapid') {
793 $SFields[$i_mapfield] = new MapSField('mapid',
795 array('adresses','geoloc_city_in_maps','geoloc_maps'),
796 array('am','gcim','map'),
797 array(getadr_join('am'),
798 'am.cityid = gcim.city_id',
799 'map.map_id = gcim.map_id'));
800 $fields = new SFieldGroup(true
, $SFields);
801 $where = $fields->get_where_statement();
802 $joins = $fields->get_select_statement();
803 $countryres = $set->get('map.map_id AS id,
804 COUNT(u.user_id) AS nbPop,
805 SUM(u.promo % 2) AS yellow,
806 COUNT(DISTINCT gcim.city_id) AS nbCities,
807 SUM(IF(u.user_id IS NULL,0,am.glng)) AS lonPop,
808 SUM(IF(u.user_id IS NULL, 0,am.glat)) AS latPop',
815 $nbentities = $nbcities +
count($countryres);
816 foreach ($countryres as $c) {
817 $c['latPop'] /= $c['nbPop'];
818 $c['lonPop'] /= $c['nbPop'];
819 $c['rad'] = size_of_territory($c['nbPop']);
820 if ($maxpop < $c['nbPop']) $maxpop = $c['nbPop'];
821 $c['xPop'] = geoloc_to_x($c['lonPop'], $c['latPop']);
822 $c['yPop'] = geoloc_to_y($c['lonPop'], $c['latPop']);
823 @$countries[$c['id']] = array_merge($countries[$c['id']], $c);
825 $nbcities +
= $c['nbCities'];
828 if ($nocity && $nbcities < $minentities){
829 foreach($countries as $i => $c) {
830 $countries[$i]['nbPop'] = 0;
831 if (@$c['nbCities'] > 0) {
832 geoloc_getData_subcities($c['id'], $sin, $cities, false
);
837 foreach ($countries as $i => $c) {
838 if (@$c['nbPop'] > 0) {
839 $lambda = pow($c['nbPop'] / $maxpop,0.3);
840 $countries[$i]['color'] = 0x0000FF +
round((1-$lambda) * 0xFF)*0x010100;
844 return array($countries, $cities);
847 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: