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