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