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