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