Job page should work
[platal.git] / include / geoloc.inc.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
5ddeb07c 3 * Copyright (C) 2003-2007 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
a7de4ef7 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é
0337d704 25 */
b536b5ae 26function geoloc_country($current, $avail_only = false)
27{
28 if ($avail_only) {
29 $res = XDB::iterRow('SELECT g.a2, g.pays
30 FROM geoloc_pays AS g
31 INNER JOIN adresses AS a ON(a.country = g.a2)
32 GROUP BY g.a2
33 ORDER BY g.pays');
34 } else {
35 $res = XDB::iterRow('SELECT a2,pays FROM geoloc_pays ORDER BY pays');
36 }
0337d704 37 $html = "";
38 while (list($my_id, $my_pays) = $res->next()) {
b536b5ae 39 $html .= sprintf("<option value=\"%s\" %s>%s</option>\n",
40 $my_id, ($current==$my_id?"selected='selected'":""), $my_pays);
0337d704 41 }
42 return $html;
43}
44
b536b5ae 45function _geoloc_country_smarty($params)
46{
90ccb062 47 echo "miqjfmeij";
8c4a0c30 48 if(!isset($params['country'])) {
b536b5ae 49 return;
8c4a0c30 50 }
b536b5ae 51 return geoloc_country($params['country'], @$params['available']);
0337d704 52}
b536b5ae 53
80ca1b4e 54$GLOBALS['page']->register_function('geoloc_country', '_geoloc_country_smarty');
0337d704 55
56/** donne la liste deroulante des regions pour un pays
57 * @param $pays le pays dont on veut afficher les regions
58 * @param $current la region actuellement selectionnee
59 */
b536b5ae 60function geoloc_region($country, $current, $avail_only = false)
61{
62 if ($avail_only) {
63 $res = XDB::iterRow('SELECT r.region, r.name
64 FROM geoloc_region AS r
65 INNER JOIN adresses AS a ON (a.country = r.a2 AND a.region = r.region)
66 WHERE r.a2 = {?}
67 GROUP BY r.region
68 ORDER BY r.name', $country);
69 } else {
70 $res = XDB::iterRow('SELECT region,name
71 FROM geoloc_region
72 WHERE a2 = {?}
73 ORDER BY name', $country);
74 }
0337d704 75 $html = "<option value=\"\"></option>";
76 while (list($regid, $regname) = $res->next()) {
b536b5ae 77 $html .= sprintf("<option value=\"%s\" %s>%s</option>\n",
78 $regid, ($current==$regid?"selected='selected'":""), $regname);
0337d704 79 }
80 return $html;
0337d704 81}
b536b5ae 82
90ccb062 83function _geoloc_region_smarty($params, &$smarty)
b536b5ae 84{
8c4a0c30 85 if(!isset($params['country']) || !isset($params['region'])) {
b536b5ae 86 return;
8c4a0c30 87 }
b536b5ae 88 return geoloc_region($params['country'], $params['region'], @$params['available']);
0337d704 89}
80ca1b4e 90$GLOBALS['page']->register_function('geoloc_region', '_geoloc_region_smarty');
0337d704 91// }}}
92
93// {{{ get_address_infos($txt)
94/** retrieve the infos on a text address
95 * store on the fly the info of the city concerned
96 * @param $txt the raw text of an address
97 */
787bb3d7 98function get_address_infos($txt)
8c4a0c30 99{
56670b6a 100 global $globals;
8c4a0c30 101 $url = $globals->geoloc->webservice_url."address.php?precise=1&txt=" . urlencode($txt);
0337d704 102 if (!($f = @fopen($url, 'r'))) return false;
103 $keys = explode('|',fgets($f));
104 $vals = explode('|',fgets($f));
105 $infos = array();
2b98ac11 106 foreach ($keys as $i=>$key) {
107 if($vals[$i]) {
108 if ($key == 'sql') {
109 $infos[$key] = $vals[$i];
110 } else {
111 $val = strtr($vals[$i], array(chr(197).chr(147) => "&oelig;"));
8c4a0c30 112 $infos[$key] = $val;
2b98ac11 113 }
114 }
115 }
5ee95138 116 if (isset($infos['sql']) && $infos['sql'])
08cce2ff 117 XDB::execute("REPLACE INTO geoloc_city VALUES ".$infos['sql']);
5ee95138 118 if (isset($infos['display']) && $infos['display'])
7f3ac007 119 XDB::execute("UPDATE geoloc_pays SET display = {?} WHERE a2 = {?}", $infos['display'], $infos['country']);
5ee95138 120 if (isset($infos['cityid']))
b536b5ae 121 fix_cities_not_on_map(1, $infos['cityid']);
0337d704 122 return $infos;
123}
124// }}}
125
56670b6a 126// {{{ get_cities_maps($array)
127/* get all the maps id of the cities contained in an array */
128function get_cities_maps($array)
129{
130 global $globals;
131 implode("\n",$array);
8c4a0c30 132 $url = $globals->geoloc->webservice_url."findMaps.php?datatext=".urlencode(implode("\n", $array));
56670b6a 133 if (!($f = @fopen($url, 'r'))) return false;
134 $maps = array();
135 while (!feof($f))
136 {
137 $l = trim(fgets($f));
138 $tab = explode(';', $l);
139 $i = $tab[0];
140 unset($tab[0]);
141 $maps[$i] = $tab;
142 }
143 return $maps;
144}
145// }}}
146
147// {{{ get_new_maps($url)
148/** set new maps from url **/
149function get_new_maps($url)
150{
a3a049fc 151 if (!($f = @fopen($url, 'r'))) {
152 return false;
153 }
154 XDB::query('TRUNCATE TABLE geoloc_maps');
155 $s = '';
156 while (!feof($f)) {
157 $l = fgetcsv($f, 1024, ';', '"');
158 foreach ($l as $i => $val) {
159 if ($val != 'NULL') {
160 $l[$i] = '\''.addslashes($val).'\'';
161 }
162 }
163 $s .= ',('.implode(',',$l).')';
164 }
165 XDB::execute('INSERT INTO geoloc_maps VALUES '.substr($s, 1));
166 return true;
56670b6a 167}
80244bbe 168// }}}
56670b6a 169
0337d704 170// {{{ get_address_text($adr)
171/** make the text of an address that can be read by a mailman
172 * @param $adr an array with all the usual fields
173 */
787bb3d7 174function get_address_text($adr)
8c4a0c30 175{
0337d704 176 $t = "";
5ee95138 177 if (isset($adr['adr1']) && $adr['adr1']) $t.= $adr['adr1'];
178 if (isset($adr['adr2']) && $adr['adr2']) $t.= "\n".$adr['adr2'];
179 if (isset($adr['adr3']) && $adr['adr3']) $t.= "\n".$adr['adr3'];
0337d704 180 $l = "";
5ee95138 181 if (isset($adr['display']) && $adr['display']) {
80ca1b4e 182 $keys = explode(' ', $adr['display']);
183 foreach ($keys as $key) {
8c4a0c30 184 if (isset($adr[$key])) {
80ca1b4e 185 $l .= " ".$adr[$key];
8c4a0c30 186 } else {
80ca1b4e 187 $l .= " ".$key;
8c4a0c30 188 }
80ca1b4e 189 }
8c4a0c30 190 if ($l) substr($l, 1);
191 } elseif ($adr['country'] == 'US' || $adr['country'] == 'CA' || $adr['country'] == 'GB') {
192 if ($adr['city']) $l .= $adr['city'].",\n";
193 if ($adr['region']) $l .= $adr['region']." ";
194 if ($adr['postcode']) $l .= $adr['postcode'];
195 } else {
196 if (isset($adr['postcode']) && $adr['postcode']) $l .= $adr['postcode']." ";
197 if (isset($adr['city']) && $adr['city']) $l .= $adr['city'];
0337d704 198 }
199 if ($l) $t .= "\n".trim($l);
200 if ($adr['country'] != '00' && (!$adr['countrytxt'] || $adr['countrytxt'] == strtoupper($adr['countrytxt']))) {
08cce2ff 201 $res = XDB::query("SELECT pays FROM geoloc_pays WHERE a2 = {?}", $adr['country']);
0337d704 202 $adr['countrytxt'] = $res->fetchOneCell();
203 }
8c4a0c30 204 if (isset($adr['countrytxt']) && $adr['countrytxt']) {
205 $t .= "\n".$adr['countrytxt'];
206 }
0337d704 207 return trim($t);
208}
209// }}}
210
211// {{{ compare_addresses_text($a, $b)
212/** compares if two address matches
213 * @param $a the raw text of an address
214 * @param $b the raw text of a complete valid address
215 */
8c4a0c30 216function compare_addresses_text($a, $b)
217{
0337d704 218 $ta = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $a));
219 $tb = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"), array("", "\n"), $b));
787bb3d7 220
0337d704 221 $la = explode("\n", $ta);
222 $lb = explode("\n", $tb);
223
8c4a0c30 224 if (count($lb) > count($la) + 1) {
225 return false;
226 }
227 foreach ($la as $i=>$l) {
37d44b3b 228 if (levenshtein(trim($l), trim($lb[$i])) > 3) {
8c4a0c30 229 return false;
230 }
231 }
0337d704 232 return true;
233}
234
235// }}}
236
237function empty_address() {
238 return Array(
239 "adr1" => "",
240 "adr2" => "",
241 "adr3" => "",
242 "cityid" => NULL,
243 "city" => "",
244 "postcode" => "",
245 "region" => "",
80ca1b4e 246 "regiontxt" => "",
0337d704 247 "country" => "00",
248 "countrytxt" => "");
249}
250
251// create a simple address from a text without geoloc
8c4a0c30 252function cut_address($txt)
253{
0337d704 254 $txt = str_replace("\r\n", "\n", $txt);
255 ereg("^([^\n]*)(\n([^\n]*)(\n(.*))?)?$", trim($txt), $a);
256 return array("adr1" => trim($a[1]), "adr2" => trim($a[3]), "adr3" => trim(str_replace("\n", " ", $a[5])));
257}
258
259// {{{ localize_addresses($uid)
260/* localize all the address of a user and modify the database
261 * if the new address match with the old one
262 * @param $uid the id of the user
263 */
8c4a0c30 264function localize_addresses($uid)
265{
266 $res = XDB::iterator("SELECT *
267 FROM adresses
268 WHERE uid = {?} and (cityid IS NULL OR cityid = 0)", $uid);
0337d704 269 $erreur = Array();
270
271 while ($a = $res->next()) {
272 $new = get_address_infos($ta = get_address_text($a));
273 if (compare_addresses_text($ta, get_address_text($new))) {
8c4a0c30 274 XDB::execute("UPDATE adresses
275 SET adr1 = {?}, adr2 = {?}, adr3 = {?},
276 cityid = {?}, city = {?}, postcode = {?},
277 region = {?}, regiontxt = {?}, country = {?},
278 glat = {?}, glng = {?}
279 WHERE uid = {?} AND adrid = {?}",
280 $new['adr1'], $new['adr2'], $new['adr3'],
281 $new['cityid'], $new['city'], $new['postcode'],
282 $new['region'], $new['regiontxt'], $new['country'],
283 $new['precise_lat'], $new['precise_lon'],
284 $uid, $a['adrid']);
285 $new['store'] = true;
286 if (!$new['cityid']) {
287 $erreur[$a['adrid']] = $new;
288 }
0337d704 289 } else {
290 $new['store'] = false;
291 $erreur[$a['adrid']] = $new;
292 }
293 }
294 return $erreur;
295}
296// }}}
297
298// {{{ synchro_city($id)
299/** synchronise the local geoloc_city base to geoloc.org
300 * @param $id the id of the city to synchronize
301 */
787bb3d7 302function synchro_city($id)
8c4a0c30 303{
56670b6a 304 global $globals;
305 $url = $globals->geoloc->webservice_url."cityFinder.php?method=id&id=".$id."&out=sql";
8c4a0c30 306 if (!($f = @fopen($url, 'r'))) {
307 return false;
308 }
0337d704 309 $s = fgets($f);
8c4a0c30 310 if ($s) {
08cce2ff 311 return XDB::execute("REPLACE INTO geoloc_city VALUES ".$s) > 0;
8c4a0c30 312 }
313}
0337d704 314 // }}}
315
56670b6a 316// {{{ function fix_cities_not_on_map($limit)
7f3ac007 317function fix_cities_not_on_map($limit=false, $cityid=false)
56670b6a 318{
8c4a0c30 319 $missing = XDB::query("SELECT c.id
320 FROM geoloc_city AS c
787bb3d7 321 LEFT JOIN geoloc_city_in_maps AS m ON(c.id = m.city_id)
8c4a0c30 322 WHERE m.city_id IS NULL"
323 . ($cityid ? " AND c.id = '" . $cityid . "'" : "" )
324 . ($limit ? " LIMIT $limit" : "" ));
56670b6a 325 $maps = get_cities_maps($missing->fetchColumn());
8c4a0c30 326 if ($maps) {
56670b6a 327 $values = "";
8c4a0c30 328 foreach ($maps as $cityid => $maps_c) {
329 foreach ($maps_c as $map_id) {
56670b6a 330 $values .= ",($cityid, $map_id, '')";
8c4a0c30 331 }
332 }
333 XDB::execute("REPLACE INTO geoloc_city_in_maps
334 VALUES ".substr($values, 1));
335 } else {
56670b6a 336 return false;
8c4a0c30 337 }
014c8464 338 return true;
339}
56670b6a 340
8c4a0c30 341function set_smallest_levels()
342{
343 $maxlengths = XDB::iterRow("SELECT MAX(LENGTH(gm.path)), gcim.city_id
344 FROM geoloc_city_in_maps AS gcim
345 INNER JOIN geoloc_maps AS gm USING ( map_id )
346 GROUP BY gcim.city_id");
014c8464 347 while (list($length, $id) = $maxlengths->next()) {
8c4a0c30 348 XDB::execute("UPDATE geoloc_city_in_maps AS gcim
349 INNER JOIN geoloc_maps AS gm USING(map_id)
350 SET gcim.infos = IF(LENGTH(gm.path) = {?}, 'smallest', '')
351 WHERE gcim.city_id = {?}", $length, $id);
014c8464 352 }
56670b6a 353 return true;
354}
355// }}}
356
357
8c4a0c30 358function geoloc_to_x($lon, $lat)
359{
360 return deg2rad(1) * $lon *100;
361}
362
363function geoloc_to_y($lon, $lat)
364{
365 if ($lat < -75) {
366 return latToY(-75);
367 }
368 if ($lat > 75) {
369 return latToY(75);
370 }
787bb3d7 371 return -100 * log(tan(pi()/4 + deg2rad(1)/2*$lat));
8c4a0c30 372}
56670b6a 373
8c4a0c30 374function size_of_city($nb)
375{
376 $s = round(log($nb + 1)*2,2);
377 if ($s < 1) {
378 return 1;
379 }
380 return $s;
56670b6a 381}
382
8c4a0c30 383function size_of_territory($nb)
384{
385 return size_of_city($nb);
386}
56670b6a 387
8c4a0c30 388function geoloc_getData_subcities($mapid, $SFields, &$cities, $direct=true)
389{
390 if ($SFields instanceof UserSet) {
391 $set = $SFields;
392 $SFields = array();
393 } else {
394 $set = new UserSet();
395 }
396 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++) {
397 if ($SFields[$i_mapfield]->fieldFormName == 'mapid') {
398 break;
399 }
400 }
401 $SFields[$i_mapfield] = new MapSField('mapid',
402 array('gcim.map_id'),
403 array('adresses','geoloc_city_in_maps'),
404 array('am','gcim'),
405 array(getadr_join('am'), 'am.cityid = gcim.city_id'),
406 $mapid);
2b105fb6 407 $fields = new SFieldGroup(true, $SFields);
408 $where = $fields->get_where_statement();
86b5c8f0 409 $joins = $fields->get_select_statement();
8c4a0c30 410 if ($where) {
411 $where .= ' AND ';
412 }
413 $cityres = $set->get('gc.id,
414 gc.lon / 100000 AS x, gc.lat/100000 AS y,
415 gc.name,
416 COUNT(u.user_id) AS pop,
417 SUM(u.promo % 2) AS yellow',
86b5c8f0 418 "$joins
8c4a0c30 419 LEFT JOIN geoloc_city AS gc ON(gcim.city_id = gc.id)",
420 $where . ($direct ? "gcim.infos = 'smallest'" : '1'),
421 'gc.id, gc.alias',
422 'pop DESC');
423 while ($c = $cityres->next()) {
424 if ($c['pop'] > 0) {
2b105fb6 425 $city = $c;
426 $city['x'] = geoloc_to_x($c['x'], $c['y']);
427 $city['y'] = geoloc_to_y($c['x'], $c['y']);
428 $city['size'] = size_of_city($c['pop']);
429 $cities[$c['id']] = $city;
430 }
8c4a0c30 431 }
2b105fb6 432}
433
787bb3d7 434function geoloc_getData_subcountries($mapid, $sin, $minentities)
8c4a0c30 435{
2b105fb6 436 $countries = array();
437 $cities = array();
787bb3d7 438
8c4a0c30 439 if ($mapid === false) {
b536b5ae 440 $wheremapid = "WHERE gm.parent IS NULL";
8c4a0c30 441 } else {
b536b5ae 442 $wheremapid = "WHERE gm.parent = {?}";
8c4a0c30 443 }
08cce2ff 444 $submapres = XDB::iterator(
787bb3d7 445 "SELECT gm.map_id AS id, gm.name, gm.x, gm.y, gm.xclip, gm.yclip,
8c4a0c30 446 gm.width, gm.height, gm.scale, 1 AS rat
447 FROM geoloc_maps AS gm
448 ". $wheremapid, Env::v('mapid',''));
2b105fb6 449
edfc872d 450 global $globals;
451
8c4a0c30 452 while ($c = $submapres->next()) {
2b105fb6 453 $country = $c;
2b105fb6 454 $country['color'] = 0xFFFFFF;
455 $country['swf'] = $globals->geoloc->webservice_url."maps/mercator/map_".$c['id'].".swf";
456 $countries[$c['id']] = $country;
457 }
787bb3d7 458
8c4a0c30 459 if ($mapid === false) {
460 return array($countries, $cities);
461 }
2b105fb6 462
8c4a0c30 463 geoloc_getData_subcities(Env::i('mapid'), $sin, $cities);
b536b5ae 464 $nbcities = count($cities);
465 $nocity = $nbcities == 0;
8c4a0c30 466 if ($sin instanceof UserSet) {
467 $set = $sin;
468 $SFields = array();
469 } else {
470 $set = new UserSet();
471 $SFields = $sin;
472 }
2b105fb6 473
8c4a0c30 474 for ($i_mapfield=0; $i_mapfield < count($SFields) ; $i_mapfield++) {
475 if ($SFields[$i_mapfield]->fieldFormName == 'mapid') {
476 break;
477 }
478 }
479 $SFields[$i_mapfield] = new MapSField('mapid',
480 array('map.parent'),
481 array('adresses','geoloc_city_in_maps','geoloc_maps'),
482 array('am','gcim','map'),
787bb3d7
FB
483 array(getadr_join('am'),
484 'am.cityid = gcim.city_id',
8c4a0c30 485 'map.map_id = gcim.map_id'));
b536b5ae 486 $fields = new SFieldGroup(true, $SFields);
86b5c8f0 487 $where = $fields->get_where_statement();
488 $joins = $fields->get_select_statement();
8c4a0c30 489 $countryres = $set->get('map.map_id AS id,
490 COUNT(u.user_id) AS nbPop,
491 SUM(u.promo % 2) AS yellow,
492 COUNT(DISTINCT gcim.city_id) AS nbCities,
493 SUM(IF(u.user_id IS NULL,0,am.glng)) AS lonPop,
494 SUM(IF(u.user_id IS NULL, 0,am.glat)) AS latPop',
86b5c8f0 495 $joins,
496 $where,
8c4a0c30 497 'map.map_id',
498 'NULL');
787bb3d7 499
b536b5ae 500 $maxpop = 0;
501 $nbentities = $nbcities + $countryres->total();
8c4a0c30 502 while ($c = $countryres->next()) {
b536b5ae 503 $c['latPop'] /= $c['nbPop'];
504 $c['lonPop'] /= $c['nbPop'];
505 $c['rad'] = size_of_territory($c['nbPop']);
506 if ($maxpop < $c['nbPop']) $maxpop = $c['nbPop'];
507 $c['xPop'] = geoloc_to_x($c['lonPop'], $c['latPop']);
508 $c['yPop'] = geoloc_to_y($c['lonPop'], $c['latPop']);
86b5c8f0 509 @$countries[$c['id']] = array_merge($countries[$c['id']], $c);
787bb3d7 510
b536b5ae 511 $nbcities += $c['nbCities'];
787bb3d7
FB
512 }
513
8c4a0c30 514 if ($nocity && $nbcities < $minentities){
515 foreach($countries as $i => $c) {
b536b5ae 516 $countries[$i]['nbPop'] = 0;
86b5c8f0 517 if (@$c['nbCities'] > 0) {
8c4a0c30 518 geoloc_getData_subcities($c['id'], $sin, $cities, false);
787bb3d7 519 }
8c4a0c30 520 }
b536b5ae 521 }
787bb3d7 522
8c4a0c30 523 foreach ($countries as $i => $c) {
524 if ($c['nbPop'] > 0) {
525 $lambda = pow($c['nbPop'] / $maxpop,0.3);
526 $countries[$i]['color'] = 0x0000FF + round((1-$lambda) * 0xFF)*0x010100;
527 }
b536b5ae 528 }
787bb3d7
FB
529
530 return array($countries, $cities);
531}
138b3c8e 532// }}}
533
a7de4ef7 534// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 535?>