]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
Merge branch 'master' of http://github.com/twain47/Nominatim
[nominatim.git] / website / search.php
1 <?php
2         require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
3         require_once(CONST_BasePath.'/lib/log.php');
4
5         ini_set('memory_limit', '200M');
6         $oDB =& getDB();
7
8         // Display defaults
9         $fLat = CONST_Default_Lat;
10         $fLon = CONST_Default_Lon;
11         $iZoom = CONST_Default_Zoom;
12         $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
13         $sOutputFormat = 'html';
14         $aSearchResults = array();
15         $aExcludePlaceIDs = array();
16         $sCountryCodesSQL = false;
17         $sSuggestion = $sSuggestionURL = false;
18         $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
19         $bReverseInPlan = false;
20         $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21         $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
22         $iMaxRank = 20;
23         if ($iLimit > 100) $iLimit = 100;
24         $iMinAddressRank = 0;
25         $iMaxAddressRank = 30;
26
27         // Format for output
28         if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' ||  $_GET['format'] == 'jsonv2'))
29         {
30                 $sOutputFormat = $_GET['format'];
31         }
32
33         // Show / use polygons
34         $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
35
36         // Show address breakdown
37         $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
38
39         // Prefered language    
40         $aLangPrefOrder = getPrefferedLangauges();
41         if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
42         if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
43         if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
44
45         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
46
47         if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
48         {
49                 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
50                 {
51                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
52                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
53                 }
54         }
55
56   // Only certain ranks of feature
57         if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
58
59         if (isset($_GET['featuretype']))
60         {
61                 switch($_GET['featuretype'])
62                 {
63                 case 'country':
64                         $iMinAddressRank = $iMaxAddressRank = 4;
65                         break;
66                 case 'state':
67                         $iMinAddressRank = $iMaxAddressRank = 8;
68                         break;
69                 case 'city':
70                         $iMinAddressRank = 14;
71                         $iMaxAddressRank = 16;
72                         break;
73                 case 'settlement':
74                         $iMinAddressRank = 8;
75                         $iMaxAddressRank = 20;
76                         break;
77                 }
78         }
79
80         if (isset($_GET['countrycodes']))
81         {
82                 $aCountryCodes = array();
83                 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
84                 {
85                         if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
86                         {
87                                 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
88                         }
89                 }
90                 $sCountryCodesSQL = join(',', $aCountryCodes);
91         }
92                 
93         // Search query
94         $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
95         if (!$sQuery && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
96         {
97                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
98
99                 // reverse order of '/' seperated string
100                 $aPhrases = explode('/', $sQuery);              
101                 $aPhrases = array_reverse($aPhrases); 
102                 $sQuery = join(', ',$aPhrases);
103         }
104         if ($sQuery)
105         {
106                 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
107
108                 // Hack to make it handle "new york, ny" (and variants) correctly
109                 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
110                 if (isset($aLangPrefOrder['name:en']))          
111                 {
112                         $sQuery = preg_replace('/\\bil\\b/','illinois', $sQuery);
113                         $sQuery = preg_replace('/\\bal\\b/','alabama', $sQuery);
114                         $sQuery = preg_replace('/\\bla\\b/','louisiana', $sQuery);
115                         $sQuery = preg_replace('/\\bde louisiana\\b/','de la', $sQuery);
116                 }
117
118                 // If we have a view box create the SQL
119                 // Small is the actual view box, Large is double (on each axis) that 
120                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
121                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
122                 {
123                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
124                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
125                 }
126                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
127                 {
128                         $aCoOrdinates = explode(',',$_GET['viewbox']);
129                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
130                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
131                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
132                         $aCoOrdinates[0] += $fHeight;
133                         $aCoOrdinates[2] -= $fHeight;
134                         $aCoOrdinates[1] += $fWidth;
135                         $aCoOrdinates[3] -= $fWidth;
136                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
137                 }
138                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
139                 {
140                         $aPoints = explode(',',$_GET['route']);
141                         if (sizeof($aPoints) % 2 != 0)
142                         {
143                                 echo "Uneven number of points";
144                                 exit;
145                         }
146                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
147                         $fPrevCoord = false;
148                         foreach($aPoints as $i => $fPoint)
149                         {
150                                 if ($i%2)
151                                 {
152                                         if ($i != 1) $sViewboxCentreSQL .= ",";
153                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
154                                 }
155                                 else
156                                 {
157                                         $fPrevCoord = (float)$fPoint;
158                                 }
159                         }
160                         $sViewboxCentreSQL .= ")'::geometry,4326)";
161
162                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
163                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
164                         if (PEAR::isError($sViewboxSmallSQL))
165                         {
166                                 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
167                         }
168                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
169
170                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
171                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
172                         if (PEAR::isError($sViewboxLargeSQL))
173                         {
174                                 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
175                         }
176                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
177                 }
178
179                 // Do we have anything that looks like a lat/lon pair?
180                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
181                 {
182                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
183                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
184                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
185                         {
186                                 $_GET['nearlat'] = $fQueryLat;
187                                 $_GET['nearlon'] = $fQueryLon;
188                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
189                         }
190                 }
191                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
192                 {
193                         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
194                         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
195                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
196                         {
197                                 $_GET['nearlat'] = $fQueryLat;
198                                 $_GET['nearlon'] = $fQueryLon;
199                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
200                         }
201                 }
202                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
203                 {
204                         $fQueryLat = $aData[2];
205                         $fQueryLon = $aData[3];
206                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
207                         {
208                                 $_GET['nearlat'] = $fQueryLat;
209                                 $_GET['nearlon'] = $fQueryLon;
210                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
211                         }
212                 }
213
214                 if ($sQuery)
215                 {
216                         // Start with a blank search
217                         $aSearches = array(
218                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 
219                                         'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
220                         );
221
222                         $sNearPointSQL = false;
223                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
224                         {
225                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
226                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
227                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
228                                 $aSearches[0]['fRadius'] = 0.1;
229                         }
230
231                         $bSpecialTerms = false;
232                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
233                         $aSpecialTerms = array();
234                         foreach($aSpecialTermsRaw as $aSpecialTerm)
235                         {
236                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
237                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
238                         }
239
240                         preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
241                         $aSpecialTerms = array();
242                         foreach($aSpecialTermsRaw as $aSpecialTerm)
243                         {
244                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
245                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
246                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
247                                 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\',\'highway\')) or country_code is not null';
248                                 $aSearchWords = $oDB->getAll($sSQL);
249                                 $aNewSearches = array();
250                                 foreach($aSearches as $aSearch)
251                                 {
252                                         foreach($aSearchWords as $aSearchTerm)
253                                         {
254                                                 $aNewSearch = $aSearch;                 
255                                                 if ($aSearchTerm['country_code'])
256                                                 {
257                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
258                                                         $aNewSearches[] = $aNewSearch;
259                                                         $bSpecialTerms = true;
260                                                 }
261                                                 if ($aSearchTerm['class'])
262                                                 {
263                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
264                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
265                                                         $aNewSearches[] = $aNewSearch;
266                                                         $bSpecialTerms = true;
267                                                 }
268                                         }
269                                 }
270                                 $aSearches = $aNewSearches;
271                         }
272
273                         // Split query into phrases
274                         // Commas are used to reduce the search space by indicating where phrases split
275                         $aPhrases = explode(',',$sQuery);
276
277                         // Convert each phrase to standard form
278                         // Create a list of standard words
279                         // Get all 'sets' of words
280                         // Generate a complete list of all 
281                         $aTokens = array();
282                         foreach($aPhrases as $iPhrase => $sPhrase)
283                         {
284                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
285                                 if (PEAR::isError($aPhrase))
286                                 {
287                                         echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
288                                         if (CONST_Debug) var_dump($aPhrase);
289                                         exit;
290                                 }
291                                 if (trim($aPhrase['string']))
292                                 {
293                                         $aPhrases[$iPhrase] = $aPhrase;
294                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
295                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
296                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
297                                 }
298                                 else
299                                 {
300                                         unset($aPhrases[$iPhrase]);
301                                 }
302                         }
303
304                         // reindex phrases - we make assumptions later on
305                         $aPhrases = array_values($aPhrases);
306
307                         if (sizeof($aTokens))
308                         {
309
310                         // Check which tokens we have, get the ID numbers                       
311                         $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
312                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
313                         // HACK WARNING
314                         // (mis)using search_name_count to exclude words that return too many
315                         // search results. saerch_name_count is currently set to 1 by hand
316                         // because there is no fast way to extract this count from a live database. 
317                         $sSQL .= ' and search_name_count = 0';
318 //                      $sSQL .= ' and (class is null or class not in (\'highway\'))';
319 //                      $sSQL .= ' group by word_token, word, class, type, location, country_code';
320
321                         if (CONST_Debug) var_Dump($sSQL);
322
323                         $aValidTokens = array();
324                         if (sizeof($aTokens))
325                                 $aDatabaseWords = $oDB->getAll($sSQL);
326                         else
327                                 $aDatabaseWords = array();
328                         if (PEAR::IsError($aDatabaseWords))
329                         {
330                                 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
331                         }
332                         $aPossibleMainWordIDs = array();
333                         foreach($aDatabaseWords as $aToken)
334                         {
335                                 if (isset($aValidTokens[$aToken['word_token']]))
336                                 {
337                                         $aValidTokens[$aToken['word_token']][] = $aToken;
338                                 }
339                                 else
340                                 {
341                                         $aValidTokens[$aToken['word_token']] = array($aToken);
342                                 }
343                                 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
344                         }
345                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
346
347                         $aSuggestion = array();
348                         $bSuggestion = false;
349                         if (CONST_Suggestions_Enabled)
350                         {
351                                 foreach($aPhrases as $iPhrase => $aPhrase)
352                                 {
353                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
354                                         {
355                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
356                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
357                                                 $aRow = $aSuggestionWords[0];
358                                                 if ($aRow && $aRow['word'])
359                                                 {
360                                                         $aSuggestion[] = $aRow['word'];
361                                                         $bSuggestion = true;
362                                                 }
363                                                 else
364                                                 {
365                                                         $aSuggestion[] = $aPhrase['string'];
366                                                 }
367                                         }
368                                         else
369                                         {
370                                                 $aSuggestion[] = $aPhrase['string'];
371                                         }
372                                 }
373                         }
374                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
375
376                         // Try and calculate GB postcodes we might be missing
377                         foreach($aTokens as $sToken)
378                         {
379                                 if (!isset($aValidTokens[$sToken]) && !isset($aValidTokens[' '.$sToken]) && preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
380                                 {
381                                         if (substr($aData[1],-2,1) != ' ')
382                                         {
383                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
384                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
385                                         }
386                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
387                                         if ($aGBPostcodeLocation)
388                                         {
389                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
390                                         }
391                                 }
392                         }
393
394                         foreach($aTokens as $sToken)
395                         {
396                                 // Unknown single word token with a number - assume it is a house number
397                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
398                                 {
399                                         $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
400                                 }
401                         }
402
403                         // Any words that have failed completely?
404                         // TODO: suggestions
405
406                         // Start the search process
407                         $aResultPlaceIDs = array();
408
409                         /*
410                                 Calculate all searches using aValidTokens i.e.
411
412                                 'Wodsworth Road, Sheffield' =>
413                                         
414                                 Phrase Wordset
415                                 0      0       (wodsworth road)
416                                 0      1       (wodsworth)(road)
417                                 1      0       (sheffield)
418                                 
419                                 Score how good the search is so they can be ordered
420                         */
421
422                                 foreach($aPhrases as $iPhrase => $sPhrase)
423                                 {
424                                         $aNewPhraseSearches = array();
425
426                                         foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
427                                         {
428                                                 $aWordsetSearches = $aSearches;
429
430                                                 // Add all words from this wordset
431                                                 foreach($aWordset as $sToken)
432                                                 {
433 //echo "<br><b>$sToken</b>";
434                                                         $aNewWordsetSearches = array();
435                                                         
436                                                         foreach($aWordsetSearches as $aCurrentSearch)
437                                                         {
438 //echo "<i>";
439 //var_dump($aCurrentSearch);
440 //echo "</i>";
441
442                                                                 // If the token is valid
443                                                                 if (isset($aValidTokens[' '.$sToken]))
444                                                                 {
445                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
446                                                                         {
447                                                                                 $aSearch = $aCurrentSearch;
448                                                                                 $aSearch['iSearchRank']++;
449                                                                                 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
450                                                                                 {
451                                                                                         if ($aSearch['sCountryCode'] === false)
452                                                                                         {
453                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
454                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
455                                                                                                 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
456                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
457                                                                                         }
458                                                                                 }
459                                                                                 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
460                                                                                 {
461                                                                                         if ($aSearch['fLat'] === '')
462                                                                                         {
463                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
464                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
465                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
466                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
467                                                                                         }
468                                                                                 }
469                                                                                 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
470                                                                                 {
471                                                                                         if ($aSearch['sHouseNumber'] === '')
472                                                                                         {
473                                                                                                 $aSearch['sHouseNumber'] = $sToken;
474                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
475 /*
476                                                                                                 // Fall back to not searching for this item (better than nothing)
477                                                                                                 $aSearch = $aCurrentSearch;
478                                                                                                 $aSearch['iSearchRank'] += 1;
479                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
480 */
481                                                                                         }
482                                                                                 }
483                                                                                 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
484                                                                                 {
485                                                                                         if ($aSearch['sClass'] === '')
486                                                                                         {
487                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
488                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
489                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
490                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
491                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
492
493                                                                                                 // Do we have a shortcut id?
494                                                                                                 if ($aSearch['sOperator'] == 'name')
495                                                                                                 {
496                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
497                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
498                                                                                                         {
499                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
500                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
501                                                                                                                 $aSearch['sClass'] = '';
502                                                                                                                 $aSearch['sType'] = '';
503                                                                                                         }
504                                                                                                 }
505                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
506                                                                                         }
507                                                                                 }
508                                                                                 else
509                                                                                 {
510                                                                                         if (sizeof($aSearch['aName']))
511                                                                                         {
512                                                                                                 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
513                                                                                                 {
514                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
515                                                                                                 }
516                                                                                                 else
517                                                                                                 {
518                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
519                                                                                                 }
520                                                                                         }
521                                                                                         else
522                                                                                         {
523                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
524 //                                                                                              $aSearch['iNamePhrase'] = $iPhrase;
525                                                                                         }
526                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
527                                                                                 }
528                                                                         }
529                                                                 }
530                                                                 if (isset($aValidTokens[$sToken]))
531                                                                 {
532                                                                         // Allow searching for a word - but at extra cost
533                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
534                                                                         {
535 //var_Dump('<hr>',$aSearch['aName']);
536
537                                                                                 if (sizeof($aCurrentSearch['aName'])  && strlen($sToken) >= 4)
538                                                                                 {
539                                                                                 $aSearch = $aCurrentSearch;
540                                                                                         $aSearch['iSearchRank'] += 1;
541                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
542                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
543                                                                                 }
544
545                                                                                 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
546                                                                                 {
547                                                                                 $aSearch = $aCurrentSearch;
548                                                                                         $aSearch['iSearchRank'] += 2;
549                                                                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
550                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
551                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
552                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
553                                                                                 }
554                                                                         }
555                                                                 }
556                                                                 else
557                                                                 {
558                                                                         // Allow skipping a word - but at EXTREAM cost
559                                                                         //$aSearch = $aCurrentSearch;
560                                                                         //$aSearch['iSearchRank']+=100;
561                                                                         //$aNewWordsetSearches[] = $aSearch;
562                                                                 }
563                                                         }
564                                                         // Sort and cut
565                                                         usort($aNewWordsetSearches, 'bySearchRank');
566                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
567                                                 }                                               
568 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
569
570                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
571                                                 usort($aNewPhraseSearches, 'bySearchRank');
572
573           $aSearchHash = array();
574           foreach($aNewPhraseSearches as $iSearch => $aSearch)
575           {
576             $sHash = serialize($aSearch);
577             if (isset($aSearchHash[$sHash]))
578             {
579               unset($aNewPhraseSearches[$iSearch]);
580             }
581             else
582             {
583               $aSearchHash[$sHash] = 1;
584             }
585           }
586
587                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
588                                         }
589
590                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
591                                         $aGroupedSearches = array();
592                                         foreach($aNewPhraseSearches as $aSearch)
593                                         {
594                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
595                                                 {
596                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
597                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
598                                                 }
599                                         }
600                                         ksort($aGroupedSearches);
601
602                                         $iSearchCount = 0;
603                                         $aSearches = array();
604                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
605                                         {
606                                                 $iSearchCount += sizeof($aNewSearches);
607                                                 $aSearches = array_merge($aSearches, $aNewSearches);
608                                                 if ($iSearchCount > 50) break;
609                                         }
610
611 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
612
613                                 }
614                         }
615                         else
616                         {
617                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
618                                         $aGroupedSearches = array();
619                                         foreach($aSearches as $aSearch)
620                                         {
621                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
622                                                 {
623                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
624                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
625                                                 }
626                                         }
627                                         ksort($aGroupedSearches);
628                         }
629                                 
630                                 if (CONST_Debug) var_Dump($aGroupedSearches);
631
632                                 if ($bReverseInPlan)
633                                 {
634                                         $aCopyGroupedSearches = $aGroupedSearches;
635                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
636                                         {
637                                                 foreach($aSearches as $iSearch => $aSearch)
638                                                 {
639                                                         if (sizeof($aSearch['aAddress']))
640                                                         {
641                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
642                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
643                                                                 {
644                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
645                                                                         $aSearch['aName'] = array($iReverseItem);
646                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
647                                                                 }
648 //                                                              $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
649         //                                                      $aGroupedSearches[$iGroup][] = $aReverseSearch;
650                                                         }
651                                                 }
652                                         }
653                                 }
654
655                                 // Filter out duplicate searches
656                                 $aSearchHash = array();
657                                 foreach($aGroupedSearches as $iGroup => $aSearches)
658                                 {
659                                         foreach($aSearches as $iSearch => $aSearch)
660                                         {
661                                                 $sHash = serialize($aSearch);
662                                                 if (isset($aSearchHash[$sHash]))
663                                                 {
664                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
665                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
666                                                 }
667                                                 else
668                                                 {
669                                                         $aSearchHash[$sHash] = 1;
670                                                 }
671                                         }
672                                 }
673
674                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
675
676                                 $iGroupLoop = 0;
677                                 $iQueryLoop = 0;
678                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
679                                 {
680                                         $iGroupLoop++;
681                                         foreach($aSearches as $aSearch)
682                                         {
683                                                 $iQueryLoop++;
684
685                                                 // Must have a location term
686                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
687                                                 {
688                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
689                                                         {
690                                                                 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
691                                                                 {
692                                                                         $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
693                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
694                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
695                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
696                                                                 }
697                                                         }
698                                                         else
699                                                         {
700                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
701                                                                 if (!$aSearch['sClass']) continue;
702                                                                 if (CONST_Debug) var_dump('<hr>',$aSearch);
703                                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
704
705                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
706                                                                 if ($oDB->getOne($sSQL))
707                                                                 {
708                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
709                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
710                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
711                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
712                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
713                                                                 $sSQL .= " limit $iLimit";
714                                                                 if (CONST_Debug) var_dump($sSQL);
715                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
716
717                                                                 if (!sizeof($aPlaceIDs))
718                                                                 {
719                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
720                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
721                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
722                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
723                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
724                                                                         $sSQL .= " limit $iLimit";
725                                                                         if (CONST_Debug) var_dump($sSQL);
726                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
727                                                                 }
728                                                         }
729                                                         else
730                                                         {
731                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
732                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
733                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
734                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
735                                                                 $sSQL .= " limit $iLimit";
736                                                                 if (CONST_Debug) var_dump($sSQL);
737                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
738                                                         }
739                                                         }
740                                                 }
741                                                 else
742                                                 {
743                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
744                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
745                                                         $aPlaceIDs = array();
746                                                 
747                                                         // First we need a position, either aName or fLat or both
748                                                         $aTerms = array();
749                                                         $aOrder = array();
750                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
751                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
752                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
753                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
754                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
755                                                         {
756                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
757                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
758                                                         }
759                                                         if (sizeof($aExcludePlaceIDs))
760                                                         {
761                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
762                                                         }
763                                                         if ($sCountryCodesSQL)
764                                                         {
765                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
766                                                         }
767
768                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
769                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
770
771                                                         $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
772
773                                                         if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
774                                                         if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
775                                                         $aOrder[] = "$sImportanceSQL DESC";
776                                                 
777                                                         if (sizeof($aTerms))
778                                                         {
779                                                                 $sSQL = "select place_id";
780                                                                 $sSQL .= " from search_name";
781                                                                 $sSQL .= " where ".join(' and ',$aTerms);
782                                                                 $sSQL .= " order by ".join(', ',$aOrder);
783                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
784                                                                         $sSQL .= " limit 50";
785                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
786                                                                         $sSQL .= " limit 1";
787                                                                 else
788                                                                         $sSQL .= " limit ".$iLimit;
789
790                                                                 if (CONST_Debug) var_dump($sSQL);
791                                                                 $iStartTime = time();
792                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
793                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
794                                                                 {
795                                                                         failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
796                                                                 }
797                                                                 if (time() - $iStartTime > 60) {
798                                                                         file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
799                                                                 }
800
801 //var_dump($aViewBoxPlaceIDs);
802                                                                 // Did we have an viewbox matches?
803                                                                 $aPlaceIDs = array();
804                                                                 $bViewBoxMatch = false;
805                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
806                                                                 {
807 //                                                                      if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
808 //                                                                      if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
809 //                                                                      if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
810 //                                                                      else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
811                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
812                                                                 }
813                                                         }
814 //var_Dump($aPlaceIDs);
815 //exit;
816
817                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
818                                                         {
819                                                                 $aRoadPlaceIDs = $aPlaceIDs;
820                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
821         
822                                                                 // Now they are indexed look for a house attached to a street we found
823                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';                                         
824                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
825                                                                 if (sizeof($aExcludePlaceIDs))
826                                                                 {
827                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
828                                                                 }
829                                                                 $sSQL .= " limit $iLimit";
830                                                                 if (CONST_Debug) var_dump($sSQL);
831                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
832
833                                                                 // If not try the aux fallback table
834                                                                 if (!sizeof($aPlaceIDs))
835                                                                 {
836                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
837                                                                         if (sizeof($aExcludePlaceIDs))
838                                                                         {
839                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
840                                                                         }
841 //                                                                      $sSQL .= " limit $iLimit";
842                                                                         if (CONST_Debug) var_dump($sSQL);
843                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
844                                                                 }
845
846                                                                 if (!sizeof($aPlaceIDs))
847                                                                 {
848                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
849                                                                         if (sizeof($aExcludePlaceIDs))
850                                                                         {
851                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
852                                                                         }
853 //                                                                      $sSQL .= " limit $iLimit";
854                                                                         if (CONST_Debug) var_dump($sSQL);
855                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
856                                                                 }
857
858                                                                 // Fallback to the road
859                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
860                                                                 {
861                                                                         $aPlaceIDs = $aRoadPlaceIDs;
862                                                                 }
863                                                                 
864                                                         }
865                                                 
866                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
867                                                         {
868                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
869
870                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
871                                                                 {
872                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
873                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
874                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
875                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
876                                                                         if (CONST_Debug) var_dump($sSQL);
877                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
878                                                                 }
879                                                                 
880                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
881                                                                 {
882                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
883                                                                         $bCacheTable = $oDB->getOne($sSQL);
884
885                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
886
887                                                                         if (CONST_Debug) var_dump($sSQL);
888                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL));
889
890                                                                         // For state / country level searches the normal radius search doesn't work very well
891                                                                         $sPlaceGeom = false;
892                                                                         if ($iMaxRank < 9 && $bCacheTable)
893                                                                         {
894                                                                                 // Try and get a polygon to search in instead
895         $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
896         if (CONST_Debug) var_dump($sSQL);
897         $sPlaceGeom = $oDB->getOne($sSQL);
898                                                                         }
899                                                                         
900                                                                         if ($sPlaceGeom)
901                                                                         {
902                                                                                 $sPlaceIDs = false;
903                                                                         }
904                                                                         else
905                                                                         {
906                                                                                 $iMaxRank += 5;
907                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
908                                                                         if (CONST_Debug) var_dump($sSQL);
909                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
910                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
911                                                                         }
912
913                                                                         if ($sPlaceIDs || $sPlaceGeom)
914                                                                         {
915
916                                                                         $fRange = 0.01;
917                                                                         if ($bCacheTable)
918                                                                         {
919                                                                                 // More efficient - can make the range bigger
920                                                                                 $fRange = 0.05;
921
922                                                                                 $sOrderBySQL = '';
923                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
924                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
925                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
926                                                                                 
927                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
928                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
929                                                                                 if ($sPlaceIDs)
930                                                                                 {
931                                                                                         $sSQL .= ",placex as f where ";
932                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
933                                                                                 }
934                                                                                 if ($sPlaceGeom)
935                                                                                 {
936                                                                                         $sSQL .= " where ";
937                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
938                                                                                 }
939                                                                                 if (sizeof($aExcludePlaceIDs))
940                                                                                 {
941                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
942                                                                                 }
943                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
944                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
945                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
946                                                                                 $sSQL .= " limit $iLimit";
947                                                                                 if (CONST_Debug) var_dump($sSQL);
948                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
949                                                                         }
950                                                                         else
951                                                                         {
952                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
953
954                                                                                 $sOrderBySQL = '';
955                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
956                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
957
958                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
959                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
960                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
961                                                                                 if (sizeof($aExcludePlaceIDs))
962                                                                                 {
963                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
964                                                                                 }
965                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";                                                           
966                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
967                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
968                                                                                 $sSQL .= " limit $iLimit";
969                                                                                 if (CONST_Debug) var_dump($sSQL);
970                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
971                                                                         }
972                                                                         }
973                                                                 }
974                                                         }
975                                                 
976                                                 }
977
978                                                 if (PEAR::IsError($aPlaceIDs))
979                                                 {
980                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
981                                                 }
982
983                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
984
985                                                 foreach($aPlaceIDs as $iPlaceID)
986                                                 {
987                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
988                                                 }
989                                                 if ($iQueryLoop > 20) break;
990                                         }
991                                         //exit;
992                                         if (sizeof($aResultPlaceIDs)) break;
993                                         if ($iGroupLoop > 4) break;
994                                         if ($iQueryLoop > 30) break;
995                                 }
996 //exit;
997                                 // Did we find anything?        
998                                 if (sizeof($aResultPlaceIDs))
999                                 {
1000 //var_Dump($aResultPlaceIDs);exit;
1001                                         // Get the details for display (is this a redundant extra step?)
1002                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
1003                                         $sOrderSQL = 'CASE ';
1004                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1005                                         {
1006                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1007                                         }
1008                                         $sOrderSQL .= ' ELSE 10000000 END';
1009                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1010                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1011                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1012                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1013                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1014 //                                      $sSQL .= $sOrderSQL." as porder, ";
1015                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1016                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1017                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1018                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1019                                         if (!$bDeDupe) $sSQL .= ",place_id";
1020                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1021                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1022                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1023                                         $sSQL .= " union ";
1024                                         $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1025                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1026                                         $sSQL .= "null as placename,";
1027                                         $sSQL .= "null as ref,";
1028                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1029 //                                      $sSQL .= $sOrderSQL." as porder, ";
1030                                         $sSQL .= "-0.15 as importance ";
1031                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1032                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1033                                         $sSQL .= "group by place_id";
1034                                         if (!$bDeDupe) $sSQL .= ",place_id";
1035                                         $sSQL .= " union ";
1036                                         $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1037                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1038                                         $sSQL .= "null as placename,";
1039                                         $sSQL .= "null as ref,";
1040                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1041 //                                      $sSQL .= $sOrderSQL." as porder, ";
1042                                         $sSQL .= "-0.10 as importance ";
1043                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1044                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1045                                         $sSQL .= "group by place_id";
1046                                         if (!$bDeDupe) $sSQL .= ",place_id";
1047                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1048                                         $sSQL .= "order by importance desc";
1049 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
1050                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
1051                                         $aSearchResults = $oDB->getAll($sSQL);
1052 //var_dump($sSQL,$aSearchResults);exit;
1053
1054                                         if (PEAR::IsError($aSearchResults))
1055                                         {
1056                                                 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1057                                         }
1058                                 }
1059                         } // end if ($sQuery)
1060                         else
1061                         {
1062                                 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1063                                 {
1064                                         $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1065                                         $aResultPlaceIDs = array($iPlaceID);
1066
1067                                         // TODO: this needs refactoring!
1068
1069                                         // Get the details for display (is this a redundant extra step?)
1070                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
1071                                         $sOrderSQL = 'CASE ';
1072                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1073                                         {
1074                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1075                                         }
1076                                         $sOrderSQL .= ' ELSE 10000000 END';
1077                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1078                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1079                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1080                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1081                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1082 //                                      $sSQL .= $sOrderSQL." as porder, ";
1083                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1084                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1085                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1086                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1087                                         if (!$bDeDupe) $sSQL .= ",place_id";
1088                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1089                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1090                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1091                                         $sSQL .= " union ";
1092                                         $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1093                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1094                                         $sSQL .= "null as placename,";
1095                                         $sSQL .= "null as ref,";
1096                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1097 //                                      $sSQL .= $sOrderSQL." as porder, ";
1098                                         $sSQL .= "-0.15 as importance ";
1099                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1100                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1101                                         $sSQL .= "group by place_id";
1102                                         if (!$bDeDupe) $sSQL .= ",place_id";
1103                                         $sSQL .= " union ";
1104                                         $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1105                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1106                                         $sSQL .= "null as placename,";
1107                                         $sSQL .= "null as ref,";
1108                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1109 //                                      $sSQL .= $sOrderSQL." as porder, ";
1110                                         $sSQL .= "-0.10 as importance ";
1111                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1112                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1113                                         $sSQL .= "group by place_id";
1114                                         if (!$bDeDupe) $sSQL .= ",place_id";
1115                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1116                                         $sSQL .= "order by importance desc";
1117 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
1118                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
1119                                         $aSearchResults = $oDB->getAll($sSQL);
1120 //var_dump($sSQL,$aSearchResults);exit;
1121
1122                                         if (PEAR::IsError($aSearchResults))
1123                                         {
1124                         failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1125                                         }
1126                                 }
1127                         }
1128                 }
1129         
1130         $sSearchResult = '';
1131         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1132         {
1133                 $sSearchResult = 'No Results Found';
1134         }
1135 //var_Dump($aSearchResults);
1136 //exit;
1137         $aClassType = getClassTypesWithImportance();
1138         foreach($aSearchResults as $iResNum => $aResult)
1139         {
1140                 if (CONST_Search_AreaPolygons || true)
1141                 {
1142                         // Get the bounding box and outline polygon
1143                         $sSQL = "select place_id,numfeatures,area,outline,";
1144                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
1145                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
1146                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1147
1148                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1149                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
1150                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
1151                         $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
1152                         $aPointPolygon = $oDB->getRow($sSQL);
1153                         if (PEAR::IsError($aPointPolygon))
1154                         {
1155                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1156                         }
1157                         if ($aPointPolygon['place_id'])
1158                         {
1159                                 // Translate geometary string to point array
1160                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1161                                 {
1162                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1163                                 }
1164                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1165                                 {
1166                                         $fRadius = 0.01;
1167                                         $iSteps = ($fRadius * 40000)^2;
1168                                         $fStepSize = (2*pi())/$iSteps;
1169                                         $aPolyPoints = array();
1170                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1171                                         {
1172                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1173                                         }
1174                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1175                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1176                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1177                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1178                                 }
1179
1180                                 // Output data suitable for display (points and a bounding box)
1181                                 if ($bShowPolygons && isset($aPolyPoints))
1182                                 {
1183                                         $aResult['aPolyPoints'] = array();
1184                                         foreach($aPolyPoints as $aPoint)
1185                                         {
1186                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1187                                         }
1188                                 }
1189                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1190                         }
1191                 }
1192
1193                 if (!isset($aResult['aBoundingBox']))
1194                 {
1195                         // Default
1196                         $fDiameter = 0.0001;
1197
1198                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
1199                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1200                         {
1201                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1202                         }
1203                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
1204                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1205                         {
1206                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1207                         }
1208                         $fRadius = $fDiameter / 2;
1209
1210                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1211                         $fStepSize = (2*pi())/$iSteps;
1212                         $aPolyPoints = array();
1213                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1214                         {
1215                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1216                         }
1217                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1218                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1219                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1220                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1221
1222                         // Output data suitable for display (points and a bounding box)
1223                         if ($bShowPolygons)
1224                         {
1225                                 $aResult['aPolyPoints'] = array();
1226                                 foreach($aPolyPoints as $aPoint)
1227                                 {
1228                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1229                                 }
1230                         }
1231                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1232                 }
1233
1234                 // Is there an icon set for this type of result?
1235                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
1236                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1237                 {
1238                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1239                 }
1240
1241                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) 
1242                         && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1243                 {
1244                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1245                 }
1246
1247                 if ($bShowAddressDetails)
1248                 {
1249                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1250 //var_dump($aResult['address']);
1251 //exit;
1252                 }
1253
1254 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1255 /*
1256                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
1257                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1258                 {
1259                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1260                 }
1261                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
1262                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1263                 {
1264                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1265                 }
1266                 else
1267                 {
1268                         $aResult['importance'] = 1000000000000000;
1269                 }
1270 */
1271                 $aResult['name'] = $aResult['langaddress'];
1272                 $aResult['foundorder'] = $iResNum;
1273                 $aSearchResults[$iResNum] = $aResult;
1274         }
1275         
1276         uasort($aSearchResults, 'byImportance');
1277
1278 //var_dump($aSearchResults);exit;
1279         
1280         $aOSMIDDone = array();
1281         $aClassTypeNameDone = array();
1282         $aToFilter = $aSearchResults;
1283         $aSearchResults = array();
1284
1285         $bFirst = true;
1286         foreach($aToFilter as $iResNum => $aResult)
1287         {
1288                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1289                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1290                 if ($bFirst)
1291                 {
1292                         $fLat = $aResult['lat'];
1293                         $fLon = $aResult['lon'];
1294                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1295                         $bFirst = false;
1296                 }
1297                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1298                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1299                 {
1300                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1301                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1302                         $aSearchResults[] = $aResult;
1303                 }
1304
1305                 // Absolute limit on number of results
1306                 if (sizeof($aSearchResults) >= $iLimit) break;
1307         }
1308
1309         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1310
1311         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1312         {
1313                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1314         }
1315
1316         if ($sQuery)
1317         {
1318                 logEnd($oDB, $hLog, sizeof($aToFilter));
1319         }
1320         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1321         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1322         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1323         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1324         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1325         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1326         if ($sSuggestion)
1327         {
1328                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1329         }
1330         $sMoreURL .= '&q='.urlencode($sQuery);
1331
1332         if (CONST_Debug) exit;
1333
1334         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');