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