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