]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
Allow option of structured search queries (params amenity,street,city,county,state...
[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)";
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)";
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)";
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                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
922                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
923                                                                         if (CONST_Debug) var_dump($sSQL);
924                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
925                                                                 }
926                                                                 
927                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
928                                                                 {
929                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
930                                                                         $bCacheTable = $oDB->getOne($sSQL);
931
932                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
933
934                                                                         if (CONST_Debug) var_dump($sSQL);
935                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL));
936
937                                                                         // For state / country level searches the normal radius search doesn't work very well
938                                                                         $sPlaceGeom = false;
939                                                                         if ($iMaxRank < 9 && $bCacheTable)
940                                                                         {
941                                                                                 // Try and get a polygon to search in instead
942         $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";
943         if (CONST_Debug) var_dump($sSQL);
944         $sPlaceGeom = $oDB->getOne($sSQL);
945                                                                         }
946                                                                         
947                                                                         if ($sPlaceGeom)
948                                                                         {
949                                                                                 $sPlaceIDs = false;
950                                                                         }
951                                                                         else
952                                                                         {
953                                                                                 $iMaxRank += 5;
954                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
955                                                                         if (CONST_Debug) var_dump($sSQL);
956                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
957                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
958                                                                         }
959
960                                                                         if ($sPlaceIDs || $sPlaceGeom)
961                                                                         {
962
963                                                                         $fRange = 0.01;
964                                                                         if ($bCacheTable)
965                                                                         {
966                                                                                 // More efficient - can make the range bigger
967                                                                                 $fRange = 0.05;
968
969                                                                                 $sOrderBySQL = '';
970                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
971                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
972                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
973                                                                                 
974                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
975                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
976                                                                                 if ($sPlaceIDs)
977                                                                                 {
978                                                                                         $sSQL .= ",placex as f where ";
979                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
980                                                                                 }
981                                                                                 if ($sPlaceGeom)
982                                                                                 {
983                                                                                         $sSQL .= " where ";
984                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
985                                                                                 }
986                                                                                 if (sizeof($aExcludePlaceIDs))
987                                                                                 {
988                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
989                                                                                 }
990                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
991                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
992                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
993                                                                                 $sSQL .= " limit $iLimit";
994                                                                                 if (CONST_Debug) var_dump($sSQL);
995                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
996                                                                         }
997                                                                         else
998                                                                         {
999                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1000
1001                                                                                 $sOrderBySQL = '';
1002                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1003                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1004
1005                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1006                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1007                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1008                                                                                 if (sizeof($aExcludePlaceIDs))
1009                                                                                 {
1010                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1011                                                                                 }
1012                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";                                                           
1013                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1014                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
1015                                                                                 $sSQL .= " limit $iLimit";
1016                                                                                 if (CONST_Debug) var_dump($sSQL);
1017                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
1018                                                                         }
1019                                                                         }
1020                                                                 }
1021                                                         }
1022                                                 
1023                                                 }
1024
1025                                                 if (PEAR::IsError($aPlaceIDs))
1026                                                 {
1027                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1028                                                 }
1029
1030                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
1031
1032                                                 foreach($aPlaceIDs as $iPlaceID)
1033                                                 {
1034                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1035                                                 }
1036                                                 if ($iQueryLoop > 20) break;
1037                                         }
1038                                         //exit;
1039                                         if (sizeof($aResultPlaceIDs)) break;
1040                                         if ($iGroupLoop > 4) break;
1041                                         if ($iQueryLoop > 30) break;
1042                                 }
1043 //exit;
1044                                 // Did we find anything?        
1045                                 if (sizeof($aResultPlaceIDs))
1046                                 {
1047 //var_Dump($aResultPlaceIDs);exit;
1048                                         // Get the details for display (is this a redundant extra step?)
1049                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
1050                                         $sOrderSQL = 'CASE ';
1051                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1052                                         {
1053                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1054                                         }
1055                                         $sOrderSQL .= ' ELSE 10000000 END';
1056                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1057                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1058                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1059                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1060                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1061 //                                      $sSQL .= $sOrderSQL." as porder, ";
1062                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1063                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1064                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1065                                         $sSQL .= "and linked_place_id is null ";
1066                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1067                                         if (!$bDeDupe) $sSQL .= ",place_id";
1068                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1069                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1070                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1071                                         $sSQL .= " union ";
1072                                         $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,";
1073                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1074                                         $sSQL .= "null as placename,";
1075                                         $sSQL .= "null as ref,";
1076                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1077 //                                      $sSQL .= $sOrderSQL." as porder, ";
1078                                         $sSQL .= "-0.15 as importance ";
1079                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1080                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1081                                         $sSQL .= "group by place_id";
1082                                         if (!$bDeDupe) $sSQL .= ",place_id";
1083                                         $sSQL .= " union ";
1084                                         $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,";
1085                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1086                                         $sSQL .= "null as placename,";
1087                                         $sSQL .= "null as ref,";
1088                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1089 //                                      $sSQL .= $sOrderSQL." as porder, ";
1090                                         $sSQL .= "-0.10 as importance ";
1091                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1092                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1093                                         $sSQL .= "group by place_id";
1094                                         if (!$bDeDupe) $sSQL .= ",place_id";
1095                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1096                                         $sSQL .= "order by importance desc";
1097 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
1098                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
1099                                         $aSearchResults = $oDB->getAll($sSQL);
1100 //var_dump($sSQL,$aSearchResults);exit;
1101
1102                                         if (PEAR::IsError($aSearchResults))
1103                                         {
1104                                                 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1105                                         }
1106                                 }
1107                         } // end if ($sQuery)
1108                         else
1109                         {
1110                                 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1111                                 {
1112                                         $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1113                                         $aResultPlaceIDs = array($iPlaceID);
1114
1115                                         // TODO: this needs refactoring!
1116
1117                                         // Get the details for display (is this a redundant extra step?)
1118                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
1119                                         $sOrderSQL = 'CASE ';
1120                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1121                                         {
1122                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1123                                         }
1124                                         $sOrderSQL .= ' ELSE 10000000 END';
1125                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1126                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1127                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1128                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1129                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1130 //                                      $sSQL .= $sOrderSQL." as porder, ";
1131                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1132                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1133                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1134                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1135                                         if (!$bDeDupe) $sSQL .= ",place_id";
1136                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1137                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1138                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1139                                         $sSQL .= " union ";
1140                                         $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,";
1141                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1142                                         $sSQL .= "null as placename,";
1143                                         $sSQL .= "null as ref,";
1144                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1145 //                                      $sSQL .= $sOrderSQL." as porder, ";
1146                                         $sSQL .= "-0.15 as importance ";
1147                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1148                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1149                                         $sSQL .= "group by place_id";
1150                                         if (!$bDeDupe) $sSQL .= ",place_id";
1151                                         $sSQL .= " union ";
1152                                         $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,";
1153                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1154                                         $sSQL .= "null as placename,";
1155                                         $sSQL .= "null as ref,";
1156                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1157 //                                      $sSQL .= $sOrderSQL." as porder, ";
1158                                         $sSQL .= "-0.10 as importance ";
1159                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1160                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1161                                         $sSQL .= "group by place_id";
1162                                         if (!$bDeDupe) $sSQL .= ",place_id";
1163                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1164                                         $sSQL .= "order by importance desc";
1165 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
1166                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
1167                                         $aSearchResults = $oDB->getAll($sSQL);
1168 //var_dump($sSQL,$aSearchResults);exit;
1169
1170                                         if (PEAR::IsError($aSearchResults))
1171                                         {
1172                         failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1173                                         }
1174                                 }
1175                         }
1176                 }
1177         
1178         $sSearchResult = '';
1179         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1180         {
1181                 $sSearchResult = 'No Results Found';
1182         }
1183 //var_Dump($aSearchResults);
1184 //exit;
1185         $aClassType = getClassTypesWithImportance();
1186         $aRecheckWords = preg_split('/\b/',$sQuery);
1187         foreach($aRecheckWords as $i => $sWord)
1188         {
1189                 if (!$sWord) unset($aRecheckWords[$i]);
1190         }
1191         foreach($aSearchResults as $iResNum => $aResult)
1192         {
1193                 if (CONST_Search_AreaPolygons)
1194                 {
1195                         // Get the bounding box and outline polygon
1196                         $sSQL = "select place_id,numfeatures,area,outline,";
1197                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1198                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1199                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1200
1201                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1202                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1203                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1204                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon,";
1205                         $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1206                         $aPointPolygon = $oDB->getRow($sSQL);
1207                         if (PEAR::IsError($aPointPolygon))
1208                         {
1209                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1210                         }
1211                         if ($aPointPolygon['place_id'])
1212                         {
1213                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1214                                         $aResult['lat'] = $aPointPolygon['centrelat'];
1215                                         $aResult['lon'] = $aPointPolygon['centrelon'];
1216                                 }
1217                                 // Translate geometary string to point array
1218                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1219                                 {
1220                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1221                                 }
1222                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1223                                 {
1224                                         $fRadius = 0.01;
1225                                         $iSteps = ($fRadius * 40000)^2;
1226                                         $fStepSize = (2*pi())/$iSteps;
1227                                         $aPolyPoints = array();
1228                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1229                                         {
1230                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1231                                         }
1232                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1233                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1234                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1235                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1236                                 }
1237
1238                                 // Output data suitable for display (points and a bounding box)
1239                                 if ($bShowPolygons && isset($aPolyPoints))
1240                                 {
1241                                         $aResult['aPolyPoints'] = array();
1242                                         foreach($aPolyPoints as $aPoint)
1243                                         {
1244                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1245                                         }
1246                                 }
1247                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1248                         }
1249                 }
1250
1251                 if (!isset($aResult['aBoundingBox']))
1252                 {
1253                         // Default
1254                         $fDiameter = 0.0001;
1255
1256                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
1257                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1258                         {
1259                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1260                         }
1261                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
1262                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1263                         {
1264                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1265                         }
1266                         $fRadius = $fDiameter / 2;
1267
1268                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1269                         $fStepSize = (2*pi())/$iSteps;
1270                         $aPolyPoints = array();
1271                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1272                         {
1273                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1274                         }
1275                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1276                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1277                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1278                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1279
1280                         // Output data suitable for display (points and a bounding box)
1281                         if ($bShowPolygons)
1282                         {
1283                                 $aResult['aPolyPoints'] = array();
1284                                 foreach($aPolyPoints as $aPoint)
1285                                 {
1286                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1287                                 }
1288                         }
1289                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1290                 }
1291
1292                 // Is there an icon set for this type of result?
1293                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
1294                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1295                 {
1296                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1297                 }
1298
1299                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) 
1300                         && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1301                 {
1302                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1303                 }
1304
1305                 if ($bShowAddressDetails)
1306                 {
1307                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1308 //var_dump($aResult['address']);
1309 //exit;
1310                 }
1311
1312                 // Adjust importance for the number of exact string matches in the result
1313                 $aResult['importance'] = max(0.001,$aResult['importance']);
1314                 $iCountWords = 0;
1315                 $sAddress = $aResult['langaddress'];
1316                 foreach($aRecheckWords as $i => $sWord)
1317                 {
1318                         if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1319                 }
1320                 $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
1321
1322 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1323 /*
1324                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
1325                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1326                 {
1327                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1328                 }
1329                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
1330                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1331                 {
1332                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1333                 }
1334                 else
1335                 {
1336                         $aResult['importance'] = 1000000000000000;
1337                 }
1338 */
1339                 $aResult['name'] = $aResult['langaddress'];
1340                 $aResult['foundorder'] = $iResNum;
1341                 $aSearchResults[$iResNum] = $aResult;
1342         }
1343         uasort($aSearchResults, 'byImportance');
1344
1345 //var_dump($aSearchResults);exit;
1346         
1347         $aOSMIDDone = array();
1348         $aClassTypeNameDone = array();
1349         $aToFilter = $aSearchResults;
1350         $aSearchResults = array();
1351
1352         $bFirst = true;
1353         foreach($aToFilter as $iResNum => $aResult)
1354         {
1355                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1356                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1357                 if ($bFirst)
1358                 {
1359                         $fLat = $aResult['lat'];
1360                         $fLon = $aResult['lon'];
1361                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1362                         $bFirst = false;
1363                 }
1364                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1365                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1366                 {
1367                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1368                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1369                         $aSearchResults[] = $aResult;
1370                 }
1371
1372                 // Absolute limit on number of results
1373                 if (sizeof($aSearchResults) >= $iLimit) break;
1374         }
1375
1376         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1377
1378         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1379         {
1380                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1381         }
1382
1383         if ($sQuery)
1384         {
1385                 logEnd($oDB, $hLog, sizeof($aToFilter));
1386         }
1387         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1388         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1389         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1390         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1391         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1392         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1393         if ($sSuggestion)
1394         {
1395                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1396         }
1397         $sMoreURL .= '&q='.urlencode($sQuery);
1398
1399         if (CONST_Debug) exit;
1400
1401         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');