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