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