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