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