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