]> git.openstreetmap.org Git - nominatim.git/blob - lib/lib.php
proper silence
[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 an 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_worship3',),
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'=>'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         function javascript_isarray($xVal)
630         {
631                 if (!is_array($xVal)) return false;
632                 for($i = 0; $i < sizeof($xVal); $i++)
633                 {
634                         if (!array_key_exists($i, $xVal)) return false;
635                 }
636                 return true;
637         }
638
639         function javascript_renderData($xVal, $bForceHash = false)
640         {
641                 if (is_array($xVal))
642                 {
643                         $aVals = array();
644                         if (javascript_isarray($xVal) && !$bForceHash)
645                         {
646                                 foreach($xVal as $sKey => $xData)
647                                 {
648                                         $aVals[] = javascript_renderData($xData);
649                                 }
650                                 return '['.join(',',$aVals).']';
651                         }
652                         else
653                         {
654                                 foreach($xVal as $sKey => $xData)
655                                 {
656                                         $aVals[] = '"'.addslashes($sKey).'"'.':'.javascript_renderData($xData);
657                                 }
658                                 return '{'.join(',',$aVals).'}';
659                         }
660                 }
661                 else
662                 {
663                         if (is_bool($xVal)) return $xVal?'true':'false';
664 //                      if (is_numeric($xVal)) return $xVal;
665                         return '"'.str_replace('>','\\>',str_replace(array("\n","\r"),'\\n',str_replace(array("\n\r","\r\n"),'\\n',str_replace('"','\\"',$xVal)))).'"';
666                 }
667         }
668
669         function _debugDumpGroupedSearches($aData, $aTokens)
670         {
671                 $aWordsIDs = array();
672                 if ($aTokens)
673                 {
674                         foreach($aTokens as $sToken => $aWords)
675                         {
676                                 if ($aWords)
677                                 {
678                                         foreach($aWords as $aToken)
679                                         {
680                                                 $aWordsIDs[$aToken['word_id']] = $sToken.'('.$aToken['word_id'].')';
681                                         }
682                                 }
683                         }
684                 }
685                 echo "<table border=\"1\">";
686                 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>";
687                 foreach($aData as $iRank => $aRankedSet)
688                 {
689                         foreach($aRankedSet as $aRow)
690                         {               
691                                 echo "<tr>";
692                                 echo "<td>$iRank</td>";
693
694                                 echo "<td>";
695                                 $sSep = '';
696                                 foreach($aRow['aName'] as $iWordID)
697                                 {
698                                         echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
699                                         $sSep = ', ';
700                                 }
701                                 echo "</td>";
702
703                                 echo "<td>";
704                                 $sSep = '';
705                                 foreach($aRow['aAddress'] as $iWordID)
706                                 {
707                                         echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
708                                         $sSep = ', ';
709                                 }
710                                 echo "</td>";
711
712                                 echo "<td>".$aRow['sCountryCode']."</td>";
713
714                                 echo "<td>".$aRow['sOperator']."</td>";
715                                 echo "<td>".$aRow['sClass']."</td>";
716                                 echo "<td>".$aRow['sType']."</td>";
717
718                                 echo "<td>".$aRow['sHouseNumber']."</td>";
719
720                                 echo "<td>".$aRow['fLat']."</td>";
721                                 echo "<td>".$aRow['fLon']."</td>";
722                                 echo "<td>".$aRow['fRadius']."</td>";
723         
724                                 echo "</tr>";
725                         }
726                 }
727                 echo "</table>";
728         }
729
730
731         function getAddressDetails(&$oDB, $sLanguagePrefArraySQL, $iPlaceID, $sCountryCode = false, $bRaw = false)
732         {
733                 $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata($iPlaceID)";
734                 IF (!$bRaw) $sSQL .= " WHERE isaddress OR type = 'country_code'";
735                 $sSQL .= " order by rank_address desc,isaddress desc";
736                 $aAddressLines = $oDB->getAll($sSQL);
737                 if (PEAR::IsError($aAddressLines))
738                 {
739                         var_dump($aAddressLines);
740                         exit;
741                 }
742                 if ($bRaw) return $aAddressLines;
743 //echo "<pre>";
744 //var_dump($aAddressLines);
745                 $aAddress = array();
746                 $aClassType = getClassTypes();
747                 foreach($aAddressLines as $aLine)
748                 {
749                         $aTypeLabel = false;
750                         if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
751                         elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
752                         else $aTypeLabel = array('simplelabel'=>$aLine['class']);
753                         if ($aTypeLabel && ($aLine['localname'] || $aLine['housenumber']))
754                         {
755                                 $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
756                                 $sTypeLabel = str_replace(' ','_',$sTypeLabel);
757                                 if (!isset($aAddress[$sTypeLabel]) && $aLine['localname']) $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
758                         }
759                 }
760 //var_dump($aAddress);
761 //exit;
762                 return $aAddress;
763
764                 $aHouseNumber = $oDB->getRow('select housenumber, get_name_by_language(name,ARRAY[\'addr:housename\']) as housename,rank_search,postcode from placex where place_id = '.$iPlaceID);
765                 $sHouseNumber = $aHouseNumber['housenumber'];
766                 $sHouseName = $aHouseNumber['housename'];
767                 $sPostcode = $aHouseNumber['postcode'];
768                 $iRank = $aHouseNumber['rank_search'];
769
770                 // Address
771                 $sSQL = "select country_code, placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, rank_search, ";
772                 $sSQL .= "get_searchrank_label(rank_search) as rank_search_label, fromarea, isaddress, distance, ";
773                 $sSQL .= " CASE WHEN type = 'postcode' THEN postcode ELSE get_name_by_language(name,$sLanguagePrefArraySQL) END as localname, ";
774                 $sSQL .= " length(name::text) as namelength ";
775                 $sSQL .= " from place_addressline join placex on (address_place_id = placex.place_id)";
776                 $sSQL .= " where place_addressline.place_id = $iPlaceID and (rank_address > 0 OR address_place_id = $iPlaceID)";
777                 if (!$bRaw) $sSQL .= " and isaddress";
778                 $sSQL .= " order by cached_rank_address desc,isaddress desc,fromarea desc,distance asc,rank_search desc,namelength desc";
779 //var_dump($sSQL);
780                 $aAddressLines = $oDB->getAll($sSQL);
781                 if (PEAR::IsError($aAddressLines))
782                 {
783                         var_dump($aAddressLines);
784                         exit;
785                 }
786                 if ($bRaw) return $aAddressLines;
787         
788                 $aClassType = getClassTypes();
789
790                 $iMinRank = 100;
791                 $aAddress = array();
792                 if ($iRank >= 28 && $sHouseNumber) $aAddress['house_number'] = $sHouseNumber;
793                 if ($iRank >= 28 && $sHouseName) $aAddress['house_name'] = $sHouseName;
794                 foreach($aAddressLines as $aLine)
795                 {
796                         if (!$sCountryCode) $sCountryCode = $aLine['country_code'];
797                         if ($aLine['rank_address'] < $iMinRank)
798                         {
799                                 $aTypeLabel = false;
800                                 if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
801                                 elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
802                                 else $aTypeLabel = array('simplelabel'=>$aLine['class']);
803                                 if ($aTypeLabel && ($aLine['localname'] || $aLine['housenumber']))
804                                 {
805                                         $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
806                                         $sTypeLabel = str_replace(' ','_',$sTypeLabel);
807                                         if (!isset($aAddress[$sTypeLabel]) && $aLine['localname']) $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
808                                 }
809                                 $iMinRank = $aLine['rank_address'];
810                         }
811                 }
812
813                 if ($sPostcode)
814                 {
815                         $aAddress['postcode'] = $sPostcode;
816                 }
817
818                 if ($iMinRank > 4 && $sCountryCode)
819                 {
820                         $sSQL = "select get_name_by_language(country_name.name,$sLanguagePrefArraySQL) as name";
821                         $sSQL .= " from country_name where country_code = '$sCountryCode'";
822                         $sCountryName = $oDB->getOne($sSQL);
823                         if ($sCountryName)
824                         {
825                                 $aAddress['country'] = $sCountryName;
826                         }
827                 }
828                 if ($sCountryCode)
829                 {
830                         $aAddress['country_code'] = $sCountryCode;
831                 }
832
833                 return $aAddress;
834         }
835
836         function getWordSuggestions(&$oDB, $sWord)
837         {
838                 $sWordQuoted = getDBQuoted(trim($sWord));
839                 $sSQL = "select *,levenshtein($sWordQuoted,word) from test_token ";
840                 $sSQL .= "where (metaphone = dmetaphone($sWordQuoted) or metaphonealt = dmetaphone($sWordQuoted) or ";
841                 $sSQL .= "metaphone = dmetaphone_alt($sWordQuoted) or metaphonealt = dmetaphone_alt($sWordQuoted)) ";
842                 $sSQL .= "and len between length($sWordQuoted)-2 and length($sWordQuoted)+2 ";
843                 $sSQL .= "and levenshtein($sWordQuoted,word) < 3 ";
844                 $sSQL .= "order by levenshtein($sWordQuoted,word) asc, abs(len - length($sWordQuoted)) asc limit 20";
845                 $aSimilar = $oDB->getAll($sSQL);
846                 return $aSimilar;
847         }
848
849         function geocodeReverse($fLat, $fLon, $iZoom=18)
850         {
851                 $oDB =& getDB();
852
853                 $sPointSQL = "ST_SetSRID(ST_Point($fLon,$fLat),4326)";
854
855                 // Zoom to rank, this could probably be calculated but a lookup gives fine control
856                 $aZoomRank = array(
857                         0 => 2, // Continent / Sea
858                         1 => 2,
859                         2 => 2,
860                         3 => 4, // Country
861                         4 => 4,
862                         5 => 8, // State
863                         6 => 10, // Region
864                         7 => 10, 
865                         8 => 12, // County
866                         9 => 12,  
867                         10 => 17, // City
868                         11 => 17, 
869                         12 => 18, // Town / Village
870                         13 => 18, 
871                         14 => 22, // Suburb
872                         15 => 22,
873                         16 => 26, // Street, TODO: major street?
874                         17 => 26, 
875                         18 => 30, // or >, Building
876                         19 => 30, // or >, Building
877                         );
878                 $iMaxRank = isset($aZoomRank[$iZoom])?$aZoomRank[$iZoom]:28;
879
880                 // Find the nearest point
881                 $fSearchDiam = 0.0001;
882                 $iPlaceID = null;
883                 $aArea = false;
884                 $fMaxAreaDistance = 1;
885                 while(!$iPlaceID && $fSearchDiam < $fMaxAreaDistance)
886                 {
887                         $fSearchDiam = $fSearchDiam * 2;
888
889                         // If we have to expand the search area by a large amount then we need a larger feature
890                         // then there is a limit to how small the feature should be
891                         if ($fSearchDiam > 2 && $iMaxRank > 4) $iMaxRank = 4;
892                         if ($fSearchDiam > 1 && $iMaxRank > 9) $iMaxRank = 8;
893                         if ($fSearchDiam > 0.8 && $iMaxRank > 10) $iMaxRank = 10;
894                         if ($fSearchDiam > 0.6 && $iMaxRank > 12) $iMaxRank = 12;
895                         if ($fSearchDiam > 0.2 && $iMaxRank > 17) $iMaxRank = 17;
896                         if ($fSearchDiam > 0.1 && $iMaxRank > 18) $iMaxRank = 18;
897                         if ($fSearchDiam > 0.008 && $iMaxRank > 22) $iMaxRank = 22;
898                         if ($fSearchDiam > 0.001 && $iMaxRank > 26) $iMaxRank = 26;
899
900                         $sSQL = 'select place_id,parent_place_id from placex';
901                         $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
902                         $sSQL .= ' and rank_search != 28 and rank_search >= '.$iMaxRank;
903                         $sSQL .= ' and (name is not null or housenumber is not null)';
904                         $sSQL .= ' and class not in (\'waterway\')';
905                         $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
906                         $sSQL .= ' OR ST_DWithin('.$sPointSQL.', ST_Centroid(geometry), '.$fSearchDiam.'))';
907                         $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
908 //var_dump($sSQL);
909                         $aPlace = $oDB->getRow($sSQL);
910                         $iPlaceID = $aPlace['place_id'];
911                         if (PEAR::IsError($iPlaceID))
912                         {
913                                 var_Dump($sSQL, $iPlaceID); 
914                                 exit;
915                         }
916                 }
917
918                 // The point we found might be too small - use the address to find what it is a child of
919                 if ($iPlaceID)
920                 {
921                         $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";
922                         $iPlaceID = $oDB->getOne($sSQL);
923                         if (PEAR::IsError($iPlaceID))
924                         {
925                                 var_Dump($sSQL, $iPlaceID); 
926                                 exit;
927                         }
928
929                         if ($iPlaceID && $aPlace['place_id'] && $iMaxRank < 28)
930                         {
931                                 $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";
932                                 $iPlaceID = $oDB->getOne($sSQL);
933                                 if (PEAR::IsError($iPlaceID))
934                                 {
935                                         var_Dump($sSQL, $iPlaceID); 
936                                         exit;
937                                 }
938                         }
939                         if (!$iPlaceID)
940                         {
941                                 $iPlaceID = $aPlace['place_id'];
942                         }
943                 }
944
945                 return $iPlaceID;
946         }