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