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