]> git.openstreetmap.org Git - nominatim.git/blob - lib/lib.php
introduce accessor function for URL parameter
[nominatim.git] / lib / lib.php
1 <?php
2
3         function failInternalError($sError, $sSQL = false, $vDumpVar = false)
4         {
5                 header('HTTP/1.0 500 Internal Server Error');
6                 header('Content-type: text/html; charset=utf-8');
7                 echo "<html><body><h1>Internal Server Error</h1>";
8                 echo '<p>Nominatim has encountered an internal error while processing your request. This is most likely because of a bug in the software.</p>';
9                 echo "<p><b>Details:</b> ".$sError,"</p>";
10                 echo '<p>Feel free to report the bug in the <a href="http://trac.openstreetmap.org">OSM bug database</a>. Please include the error message above and the URL you used.</p>';
11                 if (CONST_Debug)
12                 {
13                         echo "<hr><h2>Debugging Information</h2><br>";
14                         if ($sSQL)
15                         {
16                                 echo "<h3>SQL query</h3><code>".$sSQL."</code>";
17                         }
18                         if ($vDumpVar)
19                         {
20                                 echo "<h3>Result</h3> <code>";
21                                 var_dump($vDumpVar);
22                                 echo "</code>";
23                         }
24                 }
25                 echo "\n</body></html>\n";
26                 exit;
27         }
28
29
30         function userError($sError)
31         {
32                 header('HTTP/1.0 400 Bad Request');
33                 header('Content-type: text/html; charset=utf-8');
34                 echo "<html><body><h1>Bad Request</h1>";
35                 echo '<p>Nominatim has encountered an error with your request.</p>';
36                 echo "<p><b>Details:</b> ".$sError,"</p>";
37                 echo '<p>If you feel this error is incorrect feel free to report the bug in the <a href="http://trac.openstreetmap.org">OSM bug database</a>. Please include the error message above and the URL you used.</p>';
38                 echo "\n</body></html>\n";
39                 exit;
40         }
41
42         function fail($sError, $sUserError = false)
43         {
44                 if (!$sUserError) $sUserError = $sError;
45                 error_log('ERROR: '.$sError);
46                 echo $sUserError."\n";
47                 exit(-1);
48         }
49
50
51         function getLoadAverage()
52         {
53                 $sLoadAverage = file_get_contents('/proc/loadavg');
54                 $aLoadAverage = explode(' ',$sLoadAverage);
55                 return (float)$aLoadAverage[0];
56         }
57
58
59         function getProcessorCount()
60         {
61                 $sCPU = file_get_contents('/proc/cpuinfo');
62                 preg_match_all('#processor\s+: [0-9]+#', $sCPU, $aMatches);
63                 return sizeof($aMatches[0]);
64         }
65
66
67         function getTotalMemoryMB()
68         {
69                 $sCPU = file_get_contents('/proc/meminfo');
70                 preg_match('#MemTotal: +([0-9]+) kB#', $sCPU, $aMatches);
71                 return (int)($aMatches[1]/1024);
72         }
73
74
75         function getCacheMemoryMB()
76         {
77                 $sCPU = file_get_contents('/proc/meminfo');
78                 preg_match('#Cached: +([0-9]+) kB#', $sCPU, $aMatches);
79                 return (int)($aMatches[1]/1024);
80         }
81
82
83         function bySearchRank($a, $b)
84         {
85                 if ($a['iSearchRank'] == $b['iSearchRank'])
86                         return strlen($a['sOperator']) + strlen($a['sHouseNumber']) - strlen($b['sOperator']) - strlen($b['sHouseNumber']);
87                 return ($a['iSearchRank'] < $b['iSearchRank']?-1:1);
88         }
89
90
91         function byImportance($a, $b)
92         {
93                 if ($a['importance'] != $b['importance'])
94                         return ($a['importance'] > $b['importance']?-1:1);
95
96                 return ($a['foundorder'] < $b['foundorder']?-1:1);
97         }
98
99
100         function getPreferredLanguages($sLangString=false)
101         {
102                 if (!$sLangString)
103                 {
104                         // If we have been provided the value in $_GET it overrides browser value
105                         if (isset($_GET['accept-language']) && $_GET['accept-language'])
106                         {
107                                 $_SERVER["HTTP_ACCEPT_LANGUAGE"] = $_GET['accept-language'];
108                                 $sLangString = $_GET['accept-language'];
109                         }
110                         else if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
111                         {
112                                 $sLangString = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
113                         }
114                 }
115
116                 $aLanguages = array();
117                 if ($sLangString)
118                 {
119                         if (preg_match_all('/(([a-z]{1,8})(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $sLangString, $aLanguagesParse, PREG_SET_ORDER))
120                         {
121                                 foreach($aLanguagesParse as $iLang => $aLanguage)
122                                 {
123                                         $aLanguages[$aLanguage[1]] = isset($aLanguage[5])?(float)$aLanguage[5]:1 - ($iLang/100);
124                                         if (!isset($aLanguages[$aLanguage[2]])) $aLanguages[$aLanguage[2]] = $aLanguages[$aLanguage[1]]/10;
125                                 }
126                                 arsort($aLanguages);
127                         }
128                 }
129                 if (!sizeof($aLanguages) && CONST_Default_Language) $aLanguages = array(CONST_Default_Language=>1);
130                 foreach($aLanguages as $sLangauge => $fLangauagePref)
131                 {
132                         $aLangPrefOrder['short_name:'.$sLangauge] = 'short_name:'.$sLangauge;
133                 }
134                 foreach($aLanguages as $sLangauge => $fLangauagePref)
135                 {
136                         $aLangPrefOrder['name:'.$sLangauge] = 'name:'.$sLangauge;
137                 }
138                 foreach($aLanguages as $sLangauge => $fLangauagePref)
139                 {
140                         $aLangPrefOrder['place_name:'.$sLangauge] = 'place_name:'.$sLangauge;
141                 }
142                 foreach($aLanguages as $sLangauge => $fLangauagePref)
143                 {
144                         $aLangPrefOrder['official_name:'.$sLangauge] = 'official_name:'.$sLangauge;
145                 }
146                 $aLangPrefOrder['short_name'] = 'short_name';
147                 $aLangPrefOrder['name'] = 'name';
148                 $aLangPrefOrder['place_name'] = 'place_name';
149                 $aLangPrefOrder['official_name'] = 'official_name';
150                 $aLangPrefOrder['ref'] = 'ref';
151                 $aLangPrefOrder['type'] = 'type';
152                 return $aLangPrefOrder;
153         }
154
155
156         function getWordSets($aWords, $iDepth)
157         {
158                 $aResult = array(array(join(' ',$aWords)));
159                 $sFirstToken = '';
160                 if ($iDepth < 8) {
161                         while(sizeof($aWords) > 1)
162                         {
163                                 $sWord = array_shift($aWords);
164                                 $sFirstToken .= ($sFirstToken?' ':'').$sWord;
165                                 $aRest = getWordSets($aWords, $iDepth+1);
166                                 foreach($aRest as $aSet)
167                                 {
168                                         $aResult[] = array_merge(array($sFirstToken),$aSet);
169                                 }
170                         }
171                 }
172                 return $aResult;
173         }
174
175         function getInverseWordSets($aWords, $iDepth)
176         {
177                 $aResult = array(array(join(' ',$aWords)));
178                 $sFirstToken = '';
179                 if ($iDepth < 8)
180                 {
181                         while(sizeof($aWords) > 1)
182                         {
183                                 $sWord = array_pop($aWords);
184                                 $sFirstToken = $sWord.($sFirstToken?' ':'').$sFirstToken;
185                                 $aRest = getInverseWordSets($aWords, $iDepth+1);
186                                 foreach($aRest as $aSet)
187                                 {
188                                         $aResult[] = array_merge(array($sFirstToken),$aSet);
189                                 }
190                         }
191                 }
192                 return $aResult;
193         }
194
195
196         function getTokensFromSets($aSets)
197         {
198                 $aTokens = array();
199                 foreach($aSets as $aSet)
200                 {
201                         foreach($aSet as $sWord)
202                         {
203                                 $aTokens[' '.$sWord] = ' '.$sWord;
204                                 $aTokens[$sWord] = $sWord;
205                         }
206                 }
207                 return $aTokens;
208         }
209
210
211         /*
212            GB Postcode functions
213          */
214
215         function gbPostcodeCalculate($sPostcode, $sPostcodeSector, $sPostcodeEnd, &$oDB)
216         {
217                 // Try an exact match on the gb_postcode table
218                 $sSQL = 'select \'AA\', ST_X(ST_Centroid(geometry)) as lon,ST_Y(ST_Centroid(geometry)) as lat from gb_postcode where postcode = \''.$sPostcode.'\'';
219                 $aNearPostcodes = $oDB->getAll($sSQL);
220                 if (PEAR::IsError($aNearPostcodes))
221                 {
222                         var_dump($sSQL, $aNearPostcodes);
223                         exit;
224                 }
225
226                 if (sizeof($aNearPostcodes))
227                 {
228                         $aPostcodes = array();
229                         foreach($aNearPostcodes as $aPostcode)
230                         {
231                                 $aPostcodes[] = array('lat' => $aPostcode['lat'], 'lon' => $aPostcode['lon'], 'radius' => 0.005);
232                         }
233
234                         return $aPostcodes;
235                 }
236
237                 return false;
238         }
239
240
241         function getClassTypes()
242         {
243                 return array(
244  'boundary:administrative:1' => array('label'=>'Continent','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
245  'boundary:administrative:2' => array('label'=>'Country','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
246  'place:country' => array('label'=>'Country','frequency'=>0,'icon'=>'poi_boundary_administrative','defzoom'=>6, 'defdiameter' => 15,),
247  'boundary:administrative:3' => array('label'=>'State','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
248  'boundary:administrative:4' => array('label'=>'State','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
249  'place:state' => array('label'=>'State','frequency'=>0,'icon'=>'poi_boundary_administrative','defzoom'=>8, 'defdiameter' => 5.12,),
250  'boundary:administrative:5' => array('label'=>'State District','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
251  'boundary:administrative:6' => array('label'=>'County','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
252  'boundary:administrative:7' => array('label'=>'County','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
253  'place:county' => array('label'=>'County','frequency'=>108,'icon'=>'poi_boundary_administrative','defzoom'=>10, 'defdiameter' => 1.28,),
254  'boundary:administrative:8' => array('label'=>'City','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
255  'place:city' => array('label'=>'City','frequency'=>66,'icon'=>'poi_place_city','defzoom'=>12, 'defdiameter' => 0.32,),
256  'boundary:administrative:9' => array('label'=>'City District','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
257  'boundary:administrative:10' => array('label'=>'Suburb','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
258  'boundary:administrative:11' => array('label'=>'Neighbourhood','frequency'=>0,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
259  'place:region' => array('label'=>'Region','frequency'=>0,'icon'=>'poi_boundary_administrative','defzoom'=>8, 'defdiameter' => 0.04,),
260  'place:island' => array('label'=>'Island','frequency'=>288,'icon'=>'','defzoom'=>11, 'defdiameter' => 0.64,),
261  'boundary:administrative' => array('label'=>'Administrative','frequency'=>413,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
262  'boundary:postal_code' => array('label'=>'Postcode','frequency'=>413,'icon'=>'poi_boundary_administrative', 'defdiameter' => 0.32,),
263  'place:town' => array('label'=>'Town','frequency'=>1497,'icon'=>'poi_place_town','defzoom'=>14, 'defdiameter' => 0.08,),
264  'place:village' => array('label'=>'Village','frequency'=>11230,'icon'=>'poi_place_village','defzoom'=>15, 'defdiameter' => 0.04,),
265  'place:hamlet' => array('label'=>'Hamlet','frequency'=>7075,'icon'=>'poi_place_village','defzoom'=>15, 'defdiameter' => 0.04,),
266  'place:suburb' => array('label'=>'Suburb','frequency'=>2528,'icon'=>'poi_place_village', 'defdiameter' => 0.04,),
267  'place:locality' => array('label'=>'Locality','frequency'=>4113,'icon'=>'poi_place_village', 'defdiameter' => 0.02,),
268  'landuse:farm' => array('label'=>'Farm','frequency'=>1201,'icon'=>'', 'defdiameter' => 0.02,),
269  'place:farm' => array('label'=>'Farm','frequency'=>1162,'icon'=>'', 'defdiameter' => 0.02,),
270
271  'highway:motorway_junction' => array('label'=>'Motorway Junction','frequency'=>1126,'icon'=>'','simplelabel'=>'Junction',),
272  'highway:motorway' => array('label'=>'Motorway','frequency'=>4627,'icon'=>'','simplelabel'=>'Road',),
273  'highway:trunk' => array('label'=>'Trunk','frequency'=>23084,'icon'=>'','simplelabel'=>'Road',),
274  'highway:primary' => array('label'=>'Primary','frequency'=>32138,'icon'=>'','simplelabel'=>'Road',),
275  'highway:secondary' => array('label'=>'Secondary','frequency'=>25807,'icon'=>'','simplelabel'=>'Road',),
276  'highway:tertiary' => array('label'=>'Tertiary','frequency'=>29829,'icon'=>'','simplelabel'=>'Road',),
277  'highway:residential' => array('label'=>'Residential','frequency'=>361498,'icon'=>'','simplelabel'=>'Road',),
278  'highway:unclassified' => array('label'=>'Unclassified','frequency'=>66441,'icon'=>'','simplelabel'=>'Road',),
279  'highway:living_street' => array('label'=>'Living Street','frequency'=>710,'icon'=>'','simplelabel'=>'Road',),
280  'highway:service' => array('label'=>'Service','frequency'=>9963,'icon'=>'','simplelabel'=>'Road',),
281  'highway:track' => array('label'=>'Track','frequency'=>2565,'icon'=>'','simplelabel'=>'Road',),
282  'highway:road' => array('label'=>'Road','frequency'=>591,'icon'=>'','simplelabel'=>'Road',),
283  'highway:byway' => array('label'=>'Byway','frequency'=>346,'icon'=>'','simplelabel'=>'Road',),
284  'highway:bridleway' => array('label'=>'Bridleway','frequency'=>1556,'icon'=>'',),
285  'highway:cycleway' => array('label'=>'Cycleway','frequency'=>2419,'icon'=>'',),
286  'highway:pedestrian' => array('label'=>'Pedestrian','frequency'=>2757,'icon'=>'',),
287  'highway:footway' => array('label'=>'Footway','frequency'=>15008,'icon'=>'',),
288  'highway:steps' => array('label'=>'Steps','frequency'=>444,'icon'=>'','simplelabel'=>'Footway',),
289  'highway:motorway_link' => array('label'=>'Motorway Link','frequency'=>795,'icon'=>'','simplelabel'=>'Road',),
290  'highway:trunk_link' => array('label'=>'Trunk Link','frequency'=>1258,'icon'=>'','simplelabel'=>'Road',),
291  'highway:primary_link' => array('label'=>'Primary Link','frequency'=>313,'icon'=>'','simplelabel'=>'Road',),
292
293  'landuse:industrial' => array('label'=>'Industrial','frequency'=>1062,'icon'=>'',),
294  'landuse:residential' => array('label'=>'Residential','frequency'=>886,'icon'=>'',),
295  'landuse:retail' => array('label'=>'Retail','frequency'=>754,'icon'=>'',),
296  'landuse:commercial' => array('label'=>'Commercial','frequency'=>657,'icon'=>'',),
297
298  'place:airport' => array('label'=>'Airport','frequency'=>36,'icon'=>'transport_airport2', 'defdiameter' => 0.03,),
299  'aeroway:aerodrome' => array('label'=>'Aerodrome','frequency'=>36,'icon'=>'transport_airport2', 'defdiameter' => 0.03,),
300  'aeroway' => array('label'=>'Aeroway','frequency'=>36,'icon'=>'transport_airport2', 'defdiameter' => 0.03,),
301  'railway:station' => array('label'=>'Station','frequency'=>3431,'icon'=>'transport_train_station2', 'defdiameter' => 0.01,),
302  'amenity:place_of_worship' => array('label'=>'Place Of Worship','frequency'=>9049,'icon'=>'place_of_worship_unknown3',),
303  'amenity:pub' => array('label'=>'Pub','frequency'=>18969,'icon'=>'food_pub',),
304  'amenity:bar' => array('label'=>'Bar','frequency'=>164,'icon'=>'food_bar',),
305  'amenity:university' => array('label'=>'University','frequency'=>607,'icon'=>'education_university',),
306  'tourism:museum' => array('label'=>'Museum','frequency'=>543,'icon'=>'tourist_museum',),
307  'amenity:arts_centre' => array('label'=>'Arts Centre','frequency'=>136,'icon'=>'tourist_art_gallery2',),
308  'tourism:zoo' => array('label'=>'Zoo','frequency'=>47,'icon'=>'tourist_zoo',),
309  'tourism:theme_park' => array('label'=>'Theme Park','frequency'=>24,'icon'=>'poi_point_of_interest',),
310  'tourism:attraction' => array('label'=>'Attraction','frequency'=>1463,'icon'=>'poi_point_of_interest',),
311  'leisure:golf_course' => array('label'=>'Golf Course','frequency'=>712,'icon'=>'sport_golf',),
312  'historic:castle' => array('label'=>'Castle','frequency'=>316,'icon'=>'tourist_castle',),
313  'amenity:hospital' => array('label'=>'Hospital','frequency'=>879,'icon'=>'health_hospital',),
314  'amenity:school' => array('label'=>'School','frequency'=>8192,'icon'=>'education_school',),
315  'amenity:theatre' => array('label'=>'Theatre','frequency'=>371,'icon'=>'tourist_theatre',),
316  'amenity:public_building' => array('label'=>'Public Building','frequency'=>985,'icon'=>'',),
317  'amenity:library' => array('label'=>'Library','frequency'=>794,'icon'=>'amenity_library',),
318  'amenity:townhall' => array('label'=>'Townhall','frequency'=>242,'icon'=>'',),
319  'amenity:community_centre' => array('label'=>'Community Centre','frequency'=>157,'icon'=>'',),
320  'amenity:fire_station' => array('label'=>'Fire Station','frequency'=>221,'icon'=>'amenity_firestation3',),
321  'amenity:police' => array('label'=>'Police','frequency'=>334,'icon'=>'amenity_police2',),
322  'amenity:bank' => array('label'=>'Bank','frequency'=>1248,'icon'=>'money_bank2',),
323  'amenity:post_office' => array('label'=>'Post Office','frequency'=>859,'icon'=>'amenity_post_office',),
324  'leisure:park' => array('label'=>'Park','frequency'=>2378,'icon'=>'',),
325  'amenity:park' => array('label'=>'Park','frequency'=>53,'icon'=>'',),
326  'landuse:park' => array('label'=>'Park','frequency'=>50,'icon'=>'',),
327  'landuse:recreation_ground' => array('label'=>'Recreation Ground','frequency'=>517,'icon'=>'',),
328  'tourism:hotel' => array('label'=>'Hotel','frequency'=>2150,'icon'=>'accommodation_hotel2',),
329  'tourism:motel' => array('label'=>'Motel','frequency'=>43,'icon'=>'',),
330  'amenity:cinema' => array('label'=>'Cinema','frequency'=>277,'icon'=>'tourist_cinema',),
331  'tourism:artwork' => array('label'=>'Artwork','frequency'=>171,'icon'=>'tourist_art_gallery2',),
332  'historic:archaeological_site' => array('label'=>'Archaeological Site','frequency'=>407,'icon'=>'tourist_archaeological2',),
333  'amenity:doctors' => array('label'=>'Doctors','frequency'=>581,'icon'=>'health_doctors',),
334  'leisure:sports_centre' => array('label'=>'Sports Centre','frequency'=>767,'icon'=>'sport_leisure_centre',),
335  'leisure:swimming_pool' => array('label'=>'Swimming Pool','frequency'=>24,'icon'=>'sport_swimming_outdoor',),
336  'shop:supermarket' => array('label'=>'Supermarket','frequency'=>2673,'icon'=>'shopping_supermarket',),
337  'shop:convenience' => array('label'=>'Convenience','frequency'=>1469,'icon'=>'shopping_convenience',),
338  'amenity:restaurant' => array('label'=>'Restaurant','frequency'=>3179,'icon'=>'food_restaurant',),
339  'amenity:fast_food' => array('label'=>'Fast Food','frequency'=>2289,'icon'=>'food_fastfood',),
340  'amenity:cafe' => array('label'=>'Cafe','frequency'=>1780,'icon'=>'food_cafe',),
341  'tourism:guest_house' => array('label'=>'Guest House','frequency'=>223,'icon'=>'accommodation_bed_and_breakfast',),
342  'amenity:pharmacy' => array('label'=>'Pharmacy','frequency'=>733,'icon'=>'health_pharmacy_dispensing',),
343  'amenity:fuel' => array('label'=>'Fuel','frequency'=>1308,'icon'=>'transport_fuel',),
344  'natural:peak' => array('label'=>'Peak','frequency'=>3212,'icon'=>'poi_peak',),
345  'waterway:waterfall' => array('label'=>'Waterfall','frequency'=>24,'icon'=>'',),
346  'natural:wood' => array('label'=>'Wood','frequency'=>1845,'icon'=>'landuse_coniferous_and_deciduous',),
347  'natural:water' => array('label'=>'Water','frequency'=>1790,'icon'=>'',),
348  'landuse:forest' => array('label'=>'Forest','frequency'=>467,'icon'=>'',),
349  'landuse:cemetery' => array('label'=>'Cemetery','frequency'=>463,'icon'=>'',),
350  'landuse:allotments' => array('label'=>'Allotments','frequency'=>408,'icon'=>'',),
351  'landuse:farmyard' => array('label'=>'Farmyard','frequency'=>397,'icon'=>'',),
352  'railway:rail' => array('label'=>'Rail','frequency'=>4894,'icon'=>'',),
353  'waterway:canal' => array('label'=>'Canal','frequency'=>1723,'icon'=>'',),
354  'waterway:river' => array('label'=>'River','frequency'=>4089,'icon'=>'',),
355  'waterway:stream' => array('label'=>'Stream','frequency'=>2684,'icon'=>'',),
356  'shop:bicycle' => array('label'=>'Bicycle','frequency'=>349,'icon'=>'shopping_bicycle',),
357  'shop:clothes' => array('label'=>'Clothes','frequency'=>315,'icon'=>'shopping_clothes',),
358  'shop:hairdresser' => array('label'=>'Hairdresser','frequency'=>312,'icon'=>'shopping_hairdresser',),
359  'shop:doityourself' => array('label'=>'Doityourself','frequency'=>247,'icon'=>'shopping_diy',),
360  'shop:estate_agent' => array('label'=>'Estate Agent','frequency'=>162,'icon'=>'shopping_estateagent2',),
361  'shop:car' => array('label'=>'Car','frequency'=>159,'icon'=>'shopping_car',),
362  'shop:garden_centre' => array('label'=>'Garden Centre','frequency'=>143,'icon'=>'shopping_garden_centre',),
363  'shop:car_repair' => array('label'=>'Car Repair','frequency'=>141,'icon'=>'shopping_car_repair',),
364  'shop:newsagent' => array('label'=>'Newsagent','frequency'=>132,'icon'=>'',),
365  'shop:bakery' => array('label'=>'Bakery','frequency'=>129,'icon'=>'shopping_bakery',),
366  'shop:furniture' => array('label'=>'Furniture','frequency'=>124,'icon'=>'',),
367  'shop:butcher' => array('label'=>'Butcher','frequency'=>105,'icon'=>'shopping_butcher',),
368  'shop:apparel' => array('label'=>'Apparel','frequency'=>98,'icon'=>'shopping_clothes',),
369  'shop:electronics' => array('label'=>'Electronics','frequency'=>96,'icon'=>'',),
370  'shop:department_store' => array('label'=>'Department Store','frequency'=>86,'icon'=>'',),
371  'shop:books' => array('label'=>'Books','frequency'=>85,'icon'=>'',),
372  'shop:yes' => array('label'=>'Shop','frequency'=>68,'icon'=>'',),
373  'shop:outdoor' => array('label'=>'Outdoor','frequency'=>67,'icon'=>'',),
374  'shop:mall' => array('label'=>'Mall','frequency'=>63,'icon'=>'',),
375  'shop:florist' => array('label'=>'Florist','frequency'=>61,'icon'=>'',),
376  'shop:charity' => array('label'=>'Charity','frequency'=>60,'icon'=>'',),
377  'shop:hardware' => array('label'=>'Hardware','frequency'=>59,'icon'=>'',),
378  'shop:laundry' => array('label'=>'Laundry','frequency'=>51,'icon'=>'shopping_laundrette',),
379  'shop:shoes' => array('label'=>'Shoes','frequency'=>49,'icon'=>'',),
380  'shop:beverages' => array('label'=>'Beverages','frequency'=>48,'icon'=>'shopping_alcohol',),
381  'shop:dry_cleaning' => array('label'=>'Dry Cleaning','frequency'=>46,'icon'=>'',),
382  'shop:carpet' => array('label'=>'Carpet','frequency'=>45,'icon'=>'',),
383  'shop:computer' => array('label'=>'Computer','frequency'=>44,'icon'=>'',),
384  'shop:alcohol' => array('label'=>'Alcohol','frequency'=>44,'icon'=>'shopping_alcohol',),
385  'shop:optician' => array('label'=>'Optician','frequency'=>55,'icon'=>'health_opticians',),
386  'shop:chemist' => array('label'=>'Chemist','frequency'=>42,'icon'=>'health_pharmacy',),
387  'shop:gallery' => array('label'=>'Gallery','frequency'=>38,'icon'=>'tourist_art_gallery2',),
388  'shop:mobile_phone' => array('label'=>'Mobile Phone','frequency'=>37,'icon'=>'',),
389  'shop:sports' => array('label'=>'Sports','frequency'=>37,'icon'=>'',),
390  'shop:jewelry' => array('label'=>'Jewelry','frequency'=>32,'icon'=>'shopping_jewelry',),
391  'shop:pet' => array('label'=>'Pet','frequency'=>29,'icon'=>'',),
392  'shop:beauty' => array('label'=>'Beauty','frequency'=>28,'icon'=>'',),
393  'shop:stationery' => array('label'=>'Stationery','frequency'=>25,'icon'=>'',),
394  'shop:shopping_centre' => array('label'=>'Shopping Centre','frequency'=>25,'icon'=>'',),
395  'shop:general' => array('label'=>'General','frequency'=>25,'icon'=>'',),
396  'shop:electrical' => array('label'=>'Electrical','frequency'=>25,'icon'=>'',),
397  'shop:toys' => array('label'=>'Toys','frequency'=>23,'icon'=>'',),
398  'shop:jeweller' => array('label'=>'Jeweller','frequency'=>23,'icon'=>'',),
399  'shop:betting' => array('label'=>'Betting','frequency'=>23,'icon'=>'',),
400  'shop:household' => array('label'=>'Household','frequency'=>21,'icon'=>'',),
401  'shop:travel_agency' => array('label'=>'Travel Agency','frequency'=>21,'icon'=>'',),
402  'shop:hifi' => array('label'=>'Hifi','frequency'=>21,'icon'=>'',),
403  'amenity:shop' => array('label'=>'Shop','frequency'=>61,'icon'=>'',),
404  'tourism:information' => array('label'=>'Information','frequency'=>224,'icon'=>'amenity_information',),
405
406  'place:house' => array('label'=>'House','frequency'=>2086,'icon'=>'','defzoom'=>18,),
407  'place:house_name' => array('label'=>'House','frequency'=>2086,'icon'=>'','defzoom'=>18,),
408  'place:house_number' => array('label'=>'House Number','frequency'=>2086,'icon'=>'','defzoom'=>18,),
409  'place:country_code' => array('label'=>'Country Code','frequency'=>2086,'icon'=>'','defzoom'=>18,),
410
411  //
412
413  'leisure:pitch' => array('label'=>'Pitch','frequency'=>762,'icon'=>'',),
414  'highway:unsurfaced' => array('label'=>'Unsurfaced','frequency'=>492,'icon'=>'',),
415  'historic:ruins' => array('label'=>'Ruins','frequency'=>483,'icon'=>'tourist_ruin',),
416  'amenity:college' => array('label'=>'College','frequency'=>473,'icon'=>'education_school',),
417  'historic:monument' => array('label'=>'Monument','frequency'=>470,'icon'=>'tourist_monument',),
418  'railway:subway' => array('label'=>'Subway','frequency'=>385,'icon'=>'',),
419  'historic:memorial' => array('label'=>'Memorial','frequency'=>382,'icon'=>'tourist_monument',),
420  'leisure:nature_reserve' => array('label'=>'Nature Reserve','frequency'=>342,'icon'=>'',),
421  'leisure:common' => array('label'=>'Common','frequency'=>322,'icon'=>'',),
422  'waterway:lock_gate' => array('label'=>'Lock Gate','frequency'=>321,'icon'=>'',),
423  'natural:fell' => array('label'=>'Fell','frequency'=>308,'icon'=>'',),
424  'amenity:nightclub' => array('label'=>'Nightclub','frequency'=>292,'icon'=>'',),
425  'highway:path' => array('label'=>'Path','frequency'=>287,'icon'=>'',),
426  'leisure:garden' => array('label'=>'Garden','frequency'=>285,'icon'=>'',),
427  'landuse:reservoir' => array('label'=>'Reservoir','frequency'=>276,'icon'=>'',),
428  'leisure:playground' => array('label'=>'Playground','frequency'=>264,'icon'=>'',),
429  'leisure:stadium' => array('label'=>'Stadium','frequency'=>212,'icon'=>'',),
430  'historic:mine' => array('label'=>'Mine','frequency'=>193,'icon'=>'poi_mine',),
431  'natural:cliff' => array('label'=>'Cliff','frequency'=>193,'icon'=>'',),
432  'tourism:caravan_site' => array('label'=>'Caravan Site','frequency'=>183,'icon'=>'accommodation_caravan_park',),
433  'amenity:bus_station' => array('label'=>'Bus Station','frequency'=>181,'icon'=>'transport_bus_station',),
434  'amenity:kindergarten' => array('label'=>'Kindergarten','frequency'=>179,'icon'=>'',),
435  'highway:construction' => array('label'=>'Construction','frequency'=>176,'icon'=>'',),
436  'amenity:atm' => array('label'=>'Atm','frequency'=>172,'icon'=>'money_atm2',),
437  'amenity:emergency_phone' => array('label'=>'Emergency Phone','frequency'=>164,'icon'=>'',),
438  'waterway:lock' => array('label'=>'Lock','frequency'=>146,'icon'=>'',),
439  'waterway:riverbank' => array('label'=>'Riverbank','frequency'=>143,'icon'=>'',),
440  'natural:coastline' => array('label'=>'Coastline','frequency'=>142,'icon'=>'',),
441  'tourism:viewpoint' => array('label'=>'Viewpoint','frequency'=>140,'icon'=>'tourist_view_point',),
442  'tourism:hostel' => array('label'=>'Hostel','frequency'=>140,'icon'=>'',),
443  'tourism:bed_and_breakfast' => array('label'=>'Bed And Breakfast','frequency'=>140,'icon'=>'accommodation_bed_and_breakfast',),
444  'railway:halt' => array('label'=>'Halt','frequency'=>135,'icon'=>'',),
445  'railway:platform' => array('label'=>'Platform','frequency'=>134,'icon'=>'',),
446  'railway:tram' => array('label'=>'Tram','frequency'=>130,'icon'=>'transport_tram_stop',),
447  'amenity:courthouse' => array('label'=>'Courthouse','frequency'=>129,'icon'=>'amenity_court',),
448  'amenity:recycling' => array('label'=>'Recycling','frequency'=>126,'icon'=>'amenity_recycling',),
449  'amenity:dentist' => array('label'=>'Dentist','frequency'=>124,'icon'=>'health_dentist',),
450  'natural:beach' => array('label'=>'Beach','frequency'=>121,'icon'=>'tourist_beach',),
451  'place:moor' => array('label'=>'Moor','frequency'=>118,'icon'=>'',),
452  'amenity:grave_yard' => array('label'=>'Grave Yard','frequency'=>110,'icon'=>'',),
453  'waterway:drain' => array('label'=>'Drain','frequency'=>108,'icon'=>'',),
454  'landuse:grass' => array('label'=>'Grass','frequency'=>106,'icon'=>'',),
455  'landuse:village_green' => array('label'=>'Village Green','frequency'=>106,'icon'=>'',),
456  'natural:bay' => array('label'=>'Bay','frequency'=>102,'icon'=>'',),
457  'railway:tram_stop' => array('label'=>'Tram Stop','frequency'=>101,'icon'=>'transport_tram_stop',),
458  'leisure:marina' => array('label'=>'Marina','frequency'=>98,'icon'=>'',),
459  'highway:stile' => array('label'=>'Stile','frequency'=>97,'icon'=>'',),
460  'natural:moor' => array('label'=>'Moor','frequency'=>95,'icon'=>'',),
461  'railway:light_rail' => array('label'=>'Light Rail','frequency'=>91,'icon'=>'',),
462  'railway:narrow_gauge' => array('label'=>'Narrow Gauge','frequency'=>90,'icon'=>'',),
463  'natural:land' => array('label'=>'Land','frequency'=>86,'icon'=>'',),
464  'amenity:village_hall' => array('label'=>'Village Hall','frequency'=>82,'icon'=>'',),
465  'waterway:dock' => array('label'=>'Dock','frequency'=>80,'icon'=>'',),
466  'amenity:veterinary' => array('label'=>'Veterinary','frequency'=>79,'icon'=>'',),
467  'landuse:brownfield' => array('label'=>'Brownfield','frequency'=>77,'icon'=>'',),
468  'leisure:track' => array('label'=>'Track','frequency'=>76,'icon'=>'',),
469  'railway:historic_station' => array('label'=>'Historic Station','frequency'=>74,'icon'=>'',),
470  'landuse:construction' => array('label'=>'Construction','frequency'=>72,'icon'=>'',),
471  'amenity:prison' => array('label'=>'Prison','frequency'=>71,'icon'=>'amenity_prison',),
472  'landuse:quarry' => array('label'=>'Quarry','frequency'=>71,'icon'=>'',),
473  'amenity:telephone' => array('label'=>'Telephone','frequency'=>70,'icon'=>'',),
474  'highway:traffic_signals' => array('label'=>'Traffic Signals','frequency'=>66,'icon'=>'',),
475  'natural:heath' => array('label'=>'Heath','frequency'=>62,'icon'=>'',),
476  'historic:house' => array('label'=>'House','frequency'=>61,'icon'=>'',),
477  'amenity:social_club' => array('label'=>'Social Club','frequency'=>61,'icon'=>'',),
478  'landuse:military' => array('label'=>'Military','frequency'=>61,'icon'=>'',),
479  'amenity:health_centre' => array('label'=>'Health Centre','frequency'=>59,'icon'=>'',),
480  'historic:building' => array('label'=>'Building','frequency'=>58,'icon'=>'',),
481  'amenity:clinic' => array('label'=>'Clinic','frequency'=>57,'icon'=>'',),
482  'highway:services' => array('label'=>'Services','frequency'=>56,'icon'=>'',),
483  'amenity:ferry_terminal' => array('label'=>'Ferry Terminal','frequency'=>55,'icon'=>'',),
484  'natural:marsh' => array('label'=>'Marsh','frequency'=>55,'icon'=>'',),
485  'natural:hill' => array('label'=>'Hill','frequency'=>54,'icon'=>'',),
486  'highway:raceway' => array('label'=>'Raceway','frequency'=>53,'icon'=>'',),
487  'amenity:taxi' => array('label'=>'Taxi','frequency'=>47,'icon'=>'',),
488  'amenity:take_away' => array('label'=>'Take Away','frequency'=>45,'icon'=>'',),
489  'amenity:car_rental' => array('label'=>'Car Rental','frequency'=>44,'icon'=>'',),
490  'place:islet' => array('label'=>'Islet','frequency'=>44,'icon'=>'',),
491  'amenity:nursery' => array('label'=>'Nursery','frequency'=>44,'icon'=>'',),
492  'amenity:nursing_home' => array('label'=>'Nursing Home','frequency'=>43,'icon'=>'',),
493  'amenity:toilets' => array('label'=>'Toilets','frequency'=>38,'icon'=>'',),
494  'amenity:hall' => array('label'=>'Hall','frequency'=>38,'icon'=>'',),
495  'waterway:boatyard' => array('label'=>'Boatyard','frequency'=>36,'icon'=>'',),
496  'highway:mini_roundabout' => array('label'=>'Mini Roundabout','frequency'=>35,'icon'=>'',),
497  'historic:manor' => array('label'=>'Manor','frequency'=>35,'icon'=>'',),
498  'tourism:chalet' => array('label'=>'Chalet','frequency'=>34,'icon'=>'',),
499  'amenity:bicycle_parking' => array('label'=>'Bicycle Parking','frequency'=>34,'icon'=>'',),
500  'amenity:hotel' => array('label'=>'Hotel','frequency'=>34,'icon'=>'',),
501  'waterway:weir' => array('label'=>'Weir','frequency'=>33,'icon'=>'',),
502  'natural:wetland' => array('label'=>'Wetland','frequency'=>33,'icon'=>'',),
503  'natural:cave_entrance' => array('label'=>'Cave Entrance','frequency'=>32,'icon'=>'',),
504  'amenity:crematorium' => array('label'=>'Crematorium','frequency'=>31,'icon'=>'',),
505  'tourism:picnic_site' => array('label'=>'Picnic Site','frequency'=>31,'icon'=>'',),
506  'landuse:wood' => array('label'=>'Wood','frequency'=>30,'icon'=>'',),
507  'landuse:basin' => array('label'=>'Basin','frequency'=>30,'icon'=>'',),
508  'natural:tree' => array('label'=>'Tree','frequency'=>30,'icon'=>'',),
509  'leisure:slipway' => array('label'=>'Slipway','frequency'=>29,'icon'=>'',),
510  'landuse:meadow' => array('label'=>'Meadow','frequency'=>29,'icon'=>'',),
511  'landuse:piste' => array('label'=>'Piste','frequency'=>28,'icon'=>'',),
512  'amenity:care_home' => array('label'=>'Care Home','frequency'=>28,'icon'=>'',),
513  'amenity:club' => array('label'=>'Club','frequency'=>28,'icon'=>'',),
514  'amenity:medical_centre' => array('label'=>'Medical Centre','frequency'=>27,'icon'=>'',),
515  'historic:roman_road' => array('label'=>'Roman Road','frequency'=>27,'icon'=>'',),
516  'historic:fort' => array('label'=>'Fort','frequency'=>26,'icon'=>'',),
517  'railway:subway_entrance' => array('label'=>'Subway Entrance','frequency'=>26,'icon'=>'',),
518  'historic:yes' => array('label'=>'Historic','frequency'=>25,'icon'=>'',),
519  'highway:gate' => array('label'=>'Gate','frequency'=>25,'icon'=>'',),
520  'leisure:fishing' => array('label'=>'Fishing','frequency'=>24,'icon'=>'',),
521  'historic:museum' => array('label'=>'Museum','frequency'=>24,'icon'=>'',),
522  'amenity:car_wash' => array('label'=>'Car Wash','frequency'=>24,'icon'=>'',),
523  'railway:level_crossing' => array('label'=>'Level Crossing','frequency'=>23,'icon'=>'',),
524  'leisure:bird_hide' => array('label'=>'Bird Hide','frequency'=>23,'icon'=>'',),
525  'natural:headland' => array('label'=>'Headland','frequency'=>21,'icon'=>'',),
526  'tourism:apartments' => array('label'=>'Apartments','frequency'=>21,'icon'=>'',),
527  'amenity:shopping' => array('label'=>'Shopping','frequency'=>21,'icon'=>'',),
528  'natural:scrub' => array('label'=>'Scrub','frequency'=>20,'icon'=>'',),
529  'natural:fen' => array('label'=>'Fen','frequency'=>20,'icon'=>'',),
530  'building:yes' => array('label'=>'Building','frequency'=>200,'icon'=>'',),
531  'mountain_pass:yes' => array('label'=>'Mountain Pass','frequency'=>200,'icon'=>'',),
532
533  'amenity:parking' => array('label'=>'Parking','frequency'=>3157,'icon'=>'',),
534  'highway:bus_stop' => array('label'=>'Bus Stop','frequency'=>35777,'icon'=>'transport_bus_stop2',),
535  'place:postcode' => array('label'=>'Postcode','frequency'=>27267,'icon'=>'',),
536  'amenity:post_box' => array('label'=>'Post Box','frequency'=>9613,'icon'=>'',),
537
538  'place:houses' => array('label'=>'Houses','frequency'=>85,'icon'=>'',),
539  'railway:preserved' => array('label'=>'Preserved','frequency'=>227,'icon'=>'',),
540  'waterway:derelict_canal' => array('label'=>'Derelict Canal','frequency'=>21,'icon'=>'',),
541  'amenity:dead_pub' => array('label'=>'Dead Pub','frequency'=>20,'icon'=>'',),
542  'railway:disused_station' => array('label'=>'Disused Station','frequency'=>114,'icon'=>'',),
543  'railway:abandoned' => array('label'=>'Abandoned','frequency'=>641,'icon'=>'',),
544  'railway:disused' => array('label'=>'Disused','frequency'=>72,'icon'=>'',),
545                                 );
546         }
547
548
549         function getClassTypesWithImportance()
550         {
551                 $aOrders = getClassTypes();
552                 $i = 1;
553                 foreach($aOrders as $sID => $a)
554                 {
555                         $aOrders[$sID]['importance'] = $i++;
556                 }
557                 return $aOrders;
558         }
559
560         function getResultDiameter($aResult)
561         {
562                 $aClassType = getClassTypes();
563
564                 $fDiameter = 0.0001;
565
566                 if (isset($aResult['class'])
567                           && isset($aResult['type'])
568                           && isset($aResult['admin_level'])
569                           && isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
570                                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
571                 {
572                         $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
573                 }
574                 elseif (isset($aResult['class'])
575                           && isset($aResult['type'])
576                           && isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
577                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
578                 {
579                         $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
580                 }
581
582                 return $fDiameter;
583         }
584
585
586         function javascript_renderData($xVal, $iOptions = 0)
587         {
588                 if (defined('PHP_VERSION_ID') && PHP_VERSION_ID > 50400)
589                         $iOptions |= JSON_UNESCAPED_UNICODE;
590                 $jsonout = json_encode($xVal, $iOptions);
591
592                 if( ! isset($_GET['json_callback']))
593                 {
594                         header("Content-Type: application/json; charset=UTF-8");
595                         echo $jsonout;
596                 } else
597                 {
598                         if (preg_match('/^[$_\p{L}][$_\p{L}\p{Nd}.[\]]*$/u',$_GET['json_callback']))
599                         {
600                                 header("Content-Type: application/javascript; charset=UTF-8");
601                                 echo $_GET['json_callback'].'('.$jsonout.')';
602                         }
603                         else
604                         {
605                                 header('HTTP/1.0 400 Bad Request');
606                         }
607                 }
608         }
609
610
611         function _debugDumpGroupedSearches($aData, $aTokens)
612         {
613                 $aWordsIDs = array();
614                 if ($aTokens)
615                 {
616                         foreach($aTokens as $sToken => $aWords)
617                         {
618                                 if ($aWords)
619                                 {
620                                         foreach($aWords as $aToken)
621                                         {
622                                                 $aWordsIDs[$aToken['word_id']] = $sToken.'('.$aToken['word_id'].')';
623                                         }
624                                 }
625                         }
626                 }
627                 echo "<table border=\"1\">";
628                 echo "<tr><th>rank</th><th>Name Tokens</th><th>Name Not</th><th>Address Tokens</th><th>Address Not</th><th>country</th><th>operator</th><th>class</th><th>type</th><th>house#</th><th>Lat</th><th>Lon</th><th>Radius</th></tr>";
629                 foreach($aData as $iRank => $aRankedSet)
630                 {
631                         foreach($aRankedSet as $aRow)
632                         {
633                                 echo "<tr>";
634                                 echo "<td>$iRank</td>";
635
636                                 echo "<td>";
637                                 $sSep = '';
638                                 foreach($aRow['aName'] as $iWordID)
639                                 {
640                                         echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
641                                         $sSep = ', ';
642                                 }
643                                 echo "</td>";
644
645                                 echo "<td>";
646                                 $sSep = '';
647                                 foreach($aRow['aNameNonSearch'] as $iWordID)
648                                 {
649                                         echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
650                                         $sSep = ', ';
651                                 }
652                                 echo "</td>";
653
654                                 echo "<td>";
655                                 $sSep = '';
656                                 foreach($aRow['aAddress'] as $iWordID)
657                                 {
658                                         echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
659                                         $sSep = ', ';
660                                 }
661                                 echo "</td>";
662
663                                 echo "<td>";
664                                 $sSep = '';
665                                 foreach($aRow['aAddressNonSearch'] as $iWordID)
666                                 {
667                                         echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
668                                         $sSep = ', ';
669                                 }
670                                 echo "</td>";
671
672                                 echo "<td>".$aRow['sCountryCode']."</td>";
673
674                                 echo "<td>".$aRow['sOperator']."</td>";
675                                 echo "<td>".$aRow['sClass']."</td>";
676                                 echo "<td>".$aRow['sType']."</td>";
677
678                                 echo "<td>".$aRow['sHouseNumber']."</td>";
679
680                                 echo "<td>".$aRow['fLat']."</td>";
681                                 echo "<td>".$aRow['fLon']."</td>";
682                                 echo "<td>".$aRow['fRadius']."</td>";
683
684                                 echo "</tr>";
685                         }
686                 }
687                 echo "</table>";
688         }
689
690
691         function getAddressDetails(&$oDB, $sLanguagePrefArraySQL, $iPlaceID, $sCountryCode = false, $housenumber = -1, $bRaw = false)
692         {
693                 $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata($iPlaceID, $housenumber)";
694                 if (!$bRaw) $sSQL .= " WHERE isaddress OR type = 'country_code'";
695                 $sSQL .= " order by rank_address desc,isaddress desc";
696
697                 $aAddressLines = $oDB->getAll($sSQL);
698                 if (PEAR::IsError($aAddressLines))
699                 {
700                         var_dump($aAddressLines);
701                         exit;
702                 }
703                 if ($bRaw) return $aAddressLines;
704                 //echo "<pre>";
705                 //var_dump($aAddressLines);
706                 $aAddress = array();
707                 $aFallback = array();
708                 $aClassType = getClassTypes();
709                 foreach($aAddressLines as $aLine)
710                 {
711                         $bFallback = false;
712                         $aTypeLabel = false;
713                         if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
714                         elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
715                         elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]))
716                         {
717                                 $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
718                                 $bFallback = true;
719                         }
720                         else
721                         {
722                                 $aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']);
723                                 $bFallback = true;
724                         }
725                         if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber'])))
726                         {
727                                 $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
728                                 $sTypeLabel = str_replace(' ','_',$sTypeLabel);
729                                 if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place')
730                                 {
731                                         $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
732                                 }
733                                 $aFallback[$sTypeLabel] = $bFallback;
734                         }
735                 }
736                 return $aAddress;
737         }
738
739
740         function geocodeReverse($fLat, $fLon, $iZoom=18)
741         {
742                 $oDB =& getDB();
743
744                 $sPointSQL = "ST_SetSRID(ST_Point($fLon,$fLat),4326)";
745
746                 // Zoom to rank, this could probably be calculated but a lookup gives fine control
747                 $aZoomRank = array(
748                                 0 => 2, // Continent / Sea
749                                 1 => 2,
750                                 2 => 2,
751                                 3 => 4, // Country
752                                 4 => 4,
753                                 5 => 8, // State
754                                 6 => 10, // Region
755                                 7 => 10,
756                                 8 => 12, // County
757                                 9 => 12,
758                                 10 => 17, // City
759                                 11 => 17,
760                                 12 => 18, // Town / Village
761                                 13 => 18,
762                                 14 => 22, // Suburb
763                                 15 => 22,
764                                 16 => 26, // Street, TODO: major street?
765                                 17 => 26,
766                                 18 => 30, // or >, Building
767                                 19 => 30, // or >, Building
768                                 );
769                 $iMaxRank = isset($aZoomRank[$iZoom])?$aZoomRank[$iZoom]:28;
770
771                 // Find the nearest point
772                 $fSearchDiam = 0.0001;
773                 $iPlaceID = null;
774                 $aArea = false;
775                 $fMaxAreaDistance = 1;
776                 while(!$iPlaceID && $fSearchDiam < $fMaxAreaDistance)
777                 {
778                         $fSearchDiam = $fSearchDiam * 2;
779
780                         // If we have to expand the search area by a large amount then we need a larger feature
781                         // then there is a limit to how small the feature should be
782                         if ($fSearchDiam > 2 && $iMaxRank > 4) $iMaxRank = 4;
783                         if ($fSearchDiam > 1 && $iMaxRank > 9) $iMaxRank = 8;
784                         if ($fSearchDiam > 0.8 && $iMaxRank > 10) $iMaxRank = 10;
785                         if ($fSearchDiam > 0.6 && $iMaxRank > 12) $iMaxRank = 12;
786                         if ($fSearchDiam > 0.2 && $iMaxRank > 17) $iMaxRank = 17;
787                         if ($fSearchDiam > 0.1 && $iMaxRank > 18) $iMaxRank = 18;
788                         if ($fSearchDiam > 0.008 && $iMaxRank > 22) $iMaxRank = 22;
789                         if ($fSearchDiam > 0.001 && $iMaxRank > 26) $iMaxRank = 26;
790
791                         $sSQL = 'select place_id,parent_place_id from placex';
792                         $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
793                         $sSQL .= ' and rank_search != 28 and rank_search >= '.$iMaxRank;
794                         $sSQL .= ' and (name is not null or housenumber is not null)';
795                         $sSQL .= ' and class not in (\'waterway\')';
796                         $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
797                         $sSQL .= ' OR ST_DWithin('.$sPointSQL.', ST_Centroid(geometry), '.$fSearchDiam.'))';
798                         $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
799                         //var_dump($sSQL);
800                         $aPlace = $oDB->getRow($sSQL);
801                         if (PEAR::IsError($aPlace))
802                         {
803                                 var_Dump($sSQL, $aPlace);
804                                 exit;
805                         }
806                         $iPlaceID = $aPlace['place_id'];
807                 }
808
809                 // The point we found might be too small - use the address to find what it is a child of
810                 if ($iPlaceID)
811                 {
812                         $sSQL = "select address_place_id from place_addressline where cached_rank_address <= $iMaxRank and place_id = $iPlaceID order by cached_rank_address desc,isaddress desc,distance desc limit 1";
813                         $iPlaceID = $oDB->getOne($sSQL);
814                         if (PEAR::IsError($iPlaceID))
815                         {
816                                 var_Dump($sSQL, $iPlaceID);
817                                 exit;
818                         }
819
820                         if ($iPlaceID && $aPlace['place_id'] && $iMaxRank < 28)
821                         {
822                                 $sSQL = "select address_place_id from place_addressline where cached_rank_address <= $iMaxRank and place_id = ".$aPlace['place_id']." order by cached_rank_address desc,isaddress desc,distance desc";
823                                 $iPlaceID = $oDB->getOne($sSQL);
824                                 if (PEAR::IsError($iPlaceID))
825                                 {
826                                         var_Dump($sSQL, $iPlaceID);
827                                         exit;
828                                 }
829                         }
830                         if (!$iPlaceID)
831                         {
832                                 $iPlaceID = $aPlace['place_id'];
833                         }
834                 }
835
836                 return $iPlaceID;
837         }
838
839         function addQuotes($s)
840         {
841                 return "'".$s."'";
842         }
843
844         // returns boolean
845         function validLatLon($fLat,$fLon)
846         {
847                 return ($fLat <= 90.1 && $fLat >= -90.1 && $fLon <= 180.1 && $fLon >= -180.1);
848         }
849
850         // Do we have anything that looks like a lat/lon pair?
851         // returns array(lat,lon,query_with_lat_lon_removed)
852         // or null
853         function looksLikeLatLonPair($sQuery)
854         {
855                 $sFound    = null;
856                 $fQueryLat = null;
857                 $fQueryLon = null;
858
859                 // degrees decimal minutes
860                 // N 40 26.767, W 79 58.933
861                 // N 40°26.767′, W 79°58.933′
862                 //                  1         2                   3                  4         5            6
863                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[° ]+([0-9.]+)?[′\']*[, ]+([EW])[ ]+([0-9]+)[° ]+([0-9]+[0-9.]*)[′\']*?\\b/', $sQuery, $aData))
864                 {
865                         $sFound    = $aData[0];
866                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
867                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
868                 }
869                 // degrees decimal minutes
870                 // 40 26.767 N, 79 58.933 W
871                 // 40° 26.767′ N 79° 58.933′ W
872                 //                      1             2                      3          4            5                    6
873                 elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+[0-9.]*)?[′\']*[ ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+[0-9.]*)?[′\' ]+([EW])\\b/', $sQuery, $aData))
874                 {
875                         $sFound    = $aData[0];
876                         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
877                         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
878                 }
879                 // degrees decimal seconds
880                 // N 40 26 46 W 79 58 56
881                 // N 40° 26′ 46″, W 79° 58′ 56″
882                 //                      1        2            3            4                5        6            7            8
883                 elseif (preg_match('/\\b([NS])[ ]([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″"]*[, ]+([EW])[ ]([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″"]*\\b/', $sQuery, $aData))
884                 {
885                         $sFound    = $aData[0];
886                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60 + $aData[4]/3600);
887                         $fQueryLon = ($aData[5]=='E'?1:-1) * ($aData[6] + $aData[7]/60 + $aData[8]/3600);
888                 }
889                 // degrees decimal seconds
890                 // 40 26 46 N 79 58 56 W
891                 // 40° 26′ 46″ N, 79° 58′ 56″ W
892                 //                      1            2            3            4          5            6            7            8
893                 elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″" ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″" ]+([EW])\\b/', $sQuery, $aData))
894                 {
895                         $sFound    = $aData[0];
896                         $fQueryLat = ($aData[4]=='N'?1:-1) * ($aData[1] + $aData[2]/60 + $aData[3]/3600);
897                         $fQueryLon = ($aData[8]=='E'?1:-1) * ($aData[5] + $aData[6]/60 + $aData[7]/3600);
898                 }
899                 // degrees decimal
900                 // N 40.446° W 79.982°
901                 //                      1        2                               3        4
902                 elseif (preg_match('/\\b([NS])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*[, ]+([EW])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*\\b/', $sQuery, $aData))
903                 {
904                         $sFound    = $aData[0];
905                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2]);
906                         $fQueryLon = ($aData[3]=='E'?1:-1) * ($aData[4]);
907                 }
908                 // degrees decimal
909                 // 40.446° N 79.982° W
910                 //                      1                           2          3                           4
911                 elseif (preg_match('/\\b([0-9]+[0-9]*\\.[0-9]+)[° ]+([NS])[, ]+([0-9]+[0-9]*\\.[0-9]+)[° ]+([EW])\\b/', $sQuery, $aData))
912                 {
913                         $sFound    = $aData[0];
914                         $fQueryLat = ($aData[2]=='N'?1:-1) * ($aData[1]);
915                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[3]);
916                 }
917                 // degrees decimal
918                 // 12.34, 56.78
919                 // [12.456,-78.90]
920                 //                   1          2                             3                        4
921                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData))
922                 {
923                         $sFound    = $aData[0];
924                         $fQueryLat = $aData[2];
925                         $fQueryLon = $aData[3];
926                 }
927
928                 if (!validLatLon($fQueryLat, $fQueryLon)) return;
929                 $sQuery = trim(str_replace($sFound, ' ', $sQuery));
930
931                 return array('lat' => $fQueryLat, 'lon' => $fQueryLon, 'query' => $sQuery);
932         }
933
934
935         function geometryText2Points($geometry_as_text, $fRadius)
936         {
937                 $aPolyPoints = NULL;
938                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
939                 {
940                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
941                 }
942                 elseif (preg_match('#LINESTRING\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
943                 {
944                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
945                 }
946                 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
947                 {
948                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
949                 }
950                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#', $geometry_as_text, $aMatch))
951                 {
952                         $aPolyPoints = createPointsAroundCenter($aMatch[1], $aMatch[2], $fRadius);
953                 }
954
955                 if (isset($aPolyPoints))
956                 {
957                         $aResultPoints = array();
958                         foreach($aPolyPoints as $aPoint)
959                         {
960                                 $aResultPoints[] = array($aPoint[1], $aPoint[2]);
961                         }
962                         return $aResultPoints;
963                 }
964
965                 return;
966         }
967
968         function createPointsAroundCenter($fLon, $fLat, $fRadius)
969         {
970                         $iSteps = max(8, min(100, ($fRadius * 40000)^2));
971                         $fStepSize = (2*pi())/$iSteps;
972                         $aPolyPoints = array();
973                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
974                         {
975                                 $aPolyPoints[] = array('', $fLon+($fRadius*sin($f)), $fLat+($fRadius*cos($f)) );
976                         }
977                         return $aPolyPoints;
978         }