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