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