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