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