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