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