2         require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
 
   3         require_once(CONST_BasePath.'/lib/log.php');
 
   5         ini_set('memory_limit', '200M');
 
   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         $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
 
  21         $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
 
  23         if ($iFinalLimit > 50) $iFinalLimit = 50;
 
  24     $iLimit = $iFinalLimit + min($iFinalLimit, 10);
 
  26         $iMaxAddressRank = 30;
 
  29         if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' ||  $_GET['format'] == 'jsonv2'))
 
  31                 $sOutputFormat = $_GET['format'];
 
  34         // Show / use polygons
 
  35         $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
 
  36     if ($sOutputFormat == 'html') {
 
  37                 $bAsText = $bShowPolygons;
 
  38                 $bShowPolygons = false;
 
  43                 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
 
  44                 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
 
  45                 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
 
  46                 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
 
  47                 if ((($bShowPolygons?1:0)
 
  52                         ) > CONST_PolygonOutput_MaximumTypes) {
 
  53                         if (CONST_PolygonOutput_MaximumTypes) {
 
  54                                 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
 
  56                                 userError("Polygon output is disabled");
 
  62         // Show address breakdown
 
  63         $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
 
  66         $aLangPrefOrder = getPreferredLanguages();
 
  67         if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
 
  68         if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
 
  69         if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
 
  71         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
 
  73         if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
 
  75                 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
 
  77                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
  78                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
  82         // Only certain ranks of feature
 
  83         if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
 
  85         if (isset($_GET['featuretype']))
 
  87                 switch($_GET['featuretype'])
 
  90                         $iMinAddressRank = $iMaxAddressRank = 4;
 
  93                         $iMinAddressRank = $iMaxAddressRank = 8;
 
  96                         $iMinAddressRank = 14;
 
  97                         $iMaxAddressRank = 16;
 
 100                         $iMinAddressRank = 8;
 
 101                         $iMaxAddressRank = 20;
 
 106         if (isset($_GET['countrycodes']))
 
 108                 $aCountryCodes = array();
 
 109                 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
 
 111                         if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
 
 113                                 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
 
 116                 $sCountryCodesSQL = join(',', $aCountryCodes);
 
 120         $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
 
 121         if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
 
 123                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
 
 125                 // reverse order of '/' separated string
 
 126                 $aPhrases = explode('/', $sQuery);              
 
 127                 $aPhrases = array_reverse($aPhrases); 
 
 128                 $sQuery = join(', ',$aPhrases);
 
 131         function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
 
 133                 if (!isset($_GET[$sKey])) return false;
 
 134                 $sValue = trim($_GET[$sKey]);
 
 135                 if (!$sValue) return false;
 
 136                 $aStructuredQuery[$sKey] = $sValue;
 
 137                 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
 
 138                         $iMinAddressRank = $iNewMinAddressRank;
 
 139                         $iMaxAddressRank = $iNewMaxAddressRank;
 
 145         $aStructuredOptions = array(
 
 146                                 array('amenity', 26, 30),
 
 147                                 array('street', 26, 30),
 
 148                                 array('city', 14, 24),
 
 149                                 array('county', 9, 13),
 
 150                                 array('state', 8, 8),
 
 151                                 array('country', 4, 4),
 
 152                                 array('postalcode', 16, 25),
 
 154         $aStructuredQuery = array();
 
 155         foreach($aStructuredOptions as $aStructuredOption)
 
 157                 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
 
 159         if (sizeof($aStructuredQuery) > 0) {
 
 160                 $sQuery = join(', ', $aStructuredQuery);
 
 165                 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
 
 167                 // Hack to make it handle "new york, ny" (and variants) correctly
 
 168                 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
 
 169                 if (isset($aLangPrefOrder['name:en']))          
 
 171                         $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
 
 172                         $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
 
 173                         $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
 
 176                 // If we have a view box create the SQL
 
 177                 // Small is the actual view box, Large is double (on each axis) that 
 
 178                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
 
 179                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
 
 181                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
 
 182                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
 
 184                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
 
 186                         $aCoOrdinates = explode(',',$_GET['viewbox']);
 
 187                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
 188                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
 
 189                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
 
 190                         $aCoOrdinates[0] += $fHeight;
 
 191                         $aCoOrdinates[2] -= $fHeight;
 
 192                         $aCoOrdinates[1] += $fWidth;
 
 193                         $aCoOrdinates[3] -= $fWidth;
 
 194                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
 196                         $bBoundingBoxSearch = false;
 
 198                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
 
 200                         $aPoints = explode(',',$_GET['route']);
 
 201                         if (sizeof($aPoints) % 2 != 0)
 
 203                                 userError("Uneven number of points");
 
 206                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
 
 208                         foreach($aPoints as $i => $fPoint)
 
 212                                         if ($i != 1) $sViewboxCentreSQL .= ",";
 
 213                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
 
 217                                         $fPrevCoord = (float)$fPoint;
 
 220                         $sViewboxCentreSQL .= ")'::geometry,4326)";
 
 222                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
 
 223                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
 
 224                         if (PEAR::isError($sViewboxSmallSQL))
 
 226                                 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
 
 228                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
 
 230                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
 
 231                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
 
 232                         if (PEAR::isError($sViewboxLargeSQL))
 
 234                                 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
 
 236                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
 
 237                         $bBoundingBoxSearch = true;
 
 240                 // Do we have anything that looks like a lat/lon pair?
 
 241                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
 
 243                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
 
 244                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
 
 245                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 247                                 $_GET['nearlat'] = $fQueryLat;
 
 248                                 $_GET['nearlon'] = $fQueryLon;
 
 249                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 252                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
 
 254                         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
 
 255                         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
 
 256                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 258                                 $_GET['nearlat'] = $fQueryLat;
 
 259                                 $_GET['nearlon'] = $fQueryLon;
 
 260                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 263                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
 
 265                         $fQueryLat = $aData[2];
 
 266                         $fQueryLon = $aData[3];
 
 267                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 269                                 $_GET['nearlat'] = $fQueryLat;
 
 270                                 $_GET['nearlon'] = $fQueryLon;
 
 271                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 275                 if ($sQuery || $aStructuredQuery)
 
 277                         // Start with a blank search
 
 279                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 
 
 280                                         'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
 
 283                         $sNearPointSQL = false;
 
 284                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
 286                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
 
 287                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
 
 288                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
 
 289                                 $aSearches[0]['fRadius'] = 0.1;
 
 292                         $bSpecialTerms = false;
 
 293                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 294                         $aSpecialTerms = array();
 
 295                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 297                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 298                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
 
 301                         preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 302                         $aSpecialTerms = array();
 
 303                         if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
 
 305                                 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
 
 306                                 unset($aStructuredQuery['amenity']);
 
 308                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 310                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 311                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
 
 312                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
 
 313                                 $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';
 
 314                                 if (CONST_Debug) var_Dump($sSQL);
 
 315                                 $aSearchWords = $oDB->getAll($sSQL);
 
 316                                 $aNewSearches = array();
 
 317                                 foreach($aSearches as $aSearch)
 
 319                                         foreach($aSearchWords as $aSearchTerm)
 
 321                                                 $aNewSearch = $aSearch;                 
 
 322                                                 if ($aSearchTerm['country_code'])
 
 324                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 325                                                         $aNewSearches[] = $aNewSearch;
 
 326                                                         $bSpecialTerms = true;
 
 328                                                 if ($aSearchTerm['class'])
 
 330                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
 
 331                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
 
 332                                                         $aNewSearches[] = $aNewSearch;
 
 333                                                         $bSpecialTerms = true;
 
 337                                 $aSearches = $aNewSearches;
 
 340                         // Split query into phrases
 
 341                         // Commas are used to reduce the search space by indicating where phrases split
 
 342                         if (sizeof($aStructuredQuery) > 0)
 
 344                                 $aPhrases = $aStructuredQuery;
 
 345                                 $bStructuredPhrases = true;
 
 349                                 $aPhrases = explode(',',$sQuery);
 
 350                                 $bStructuredPhrases = false;
 
 354                         // Convert each phrase to standard form
 
 355                         // Create a list of standard words
 
 356                         // Get all 'sets' of words
 
 357                         // Generate a complete list of all 
 
 359                         foreach($aPhrases as $iPhrase => $sPhrase)
 
 361                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
 
 362                                 if (PEAR::isError($aPhrase))
 
 364                                         userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
 
 365                                         if (CONST_Debug) var_dump($aPhrase);
 
 368                                 if (trim($aPhrase['string']))
 
 370                                         $aPhrases[$iPhrase] = $aPhrase;
 
 371                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
 
 372                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
 
 373                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
 377                                         unset($aPhrases[$iPhrase]);
 
 381                         // reindex phrases - we make assumptions later on
 
 382                         $aPhraseTypes = array_keys($aPhrases);
 
 383                         $aPhrases = array_values($aPhrases);
 
 385                         if (sizeof($aTokens))
 
 388                         // Check which tokens we have, get the ID numbers                       
 
 389                         $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
 
 390                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
 
 391                         $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
 
 392 //                      $sSQL .= ' group by word_token, word, class, type, location, country_code';
 
 394                         if (CONST_Debug) var_Dump($sSQL);
 
 396                         $aValidTokens = array();
 
 397                         if (sizeof($aTokens))
 
 398                                 $aDatabaseWords = $oDB->getAll($sSQL);
 
 400                                 $aDatabaseWords = array();
 
 401                         if (PEAR::IsError($aDatabaseWords))
 
 403                                 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
 
 405                         $aPossibleMainWordIDs = array();
 
 406                         foreach($aDatabaseWords as $aToken)
 
 408                                 if (isset($aValidTokens[$aToken['word_token']]))
 
 410                                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
 414                                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
 416                                 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
 
 418                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
 420                         $aSuggestion = array();
 
 421                         $bSuggestion = false;
 
 422                         if (CONST_Suggestions_Enabled)
 
 424                                 foreach($aPhrases as $iPhrase => $aPhrase)
 
 426                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
 
 428                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
 
 429                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
 
 430                                                 $aRow = $aSuggestionWords[0];
 
 431                                                 if ($aRow && $aRow['word'])
 
 433                                                         $aSuggestion[] = $aRow['word'];
 
 438                                                         $aSuggestion[] = $aPhrase['string'];
 
 443                                                 $aSuggestion[] = $aPhrase['string'];
 
 447                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
 
 449                         // Try and calculate GB postcodes we might be missing
 
 450                         foreach($aTokens as $sToken)
 
 452                                 // Source of gb postcodes is now definitive - always use
 
 453                                 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
 
 455                                         if (substr($aData[1],-2,1) != ' ')
 
 457                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
 
 458                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
 
 460                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
 
 461                                         if ($aGBPostcodeLocation)
 
 463                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
 
 468                         foreach($aTokens as $sToken)
 
 470                                 // Unknown single word token with a number - assume it is a house number
 
 471                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
 
 473                                         $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
 
 477                         // Any words that have failed completely?
 
 480                         // Start the search process
 
 481                         $aResultPlaceIDs = array();
 
 484                                 Calculate all searches using aValidTokens i.e.
 
 486                                 'Wodsworth Road, Sheffield' =>
 
 490                                 0      1       (wodsworth)(road)
 
 493                                 Score how good the search is so they can be ordered
 
 495                                 foreach($aPhrases as $iPhrase => $sPhrase)
 
 497                                         $aNewPhraseSearches = array();
 
 498                                         if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
 
 499                                         else $sPhraseType = '';
 
 501                                         foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
 
 503                                                 $aWordsetSearches = $aSearches;
 
 505                                                 // Add all words from this wordset
 
 506                                                 foreach($aWordset as $iToken => $sToken)
 
 508 //echo "<br><b>$sToken</b>";
 
 509                                                         $aNewWordsetSearches = array();
 
 511                                                         foreach($aWordsetSearches as $aCurrentSearch)
 
 514 //var_dump($aCurrentSearch);
 
 517                                                                 // If the token is valid
 
 518                                                                 if (isset($aValidTokens[' '.$sToken]))
 
 520                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
 
 522                                                                                 $aSearch = $aCurrentSearch;
 
 523                                                                                 $aSearch['iSearchRank']++;
 
 524                                                                                 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
 
 526                                                                                         if ($aSearch['sCountryCode'] === false)
 
 528                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 529                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
 
 530                                                                                                 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
 
 531                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 534                                                                                 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
 
 536                                                                                         if ($aSearch['fLat'] === '')
 
 538                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
 
 539                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
 
 540                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
 
 541                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 544                                                                                 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
 
 546                                                                                         if ($aSearch['sHouseNumber'] === '')
 
 548                                                                                                 $aSearch['sHouseNumber'] = $sToken;
 
 549                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 551                                                                                                 // Fall back to not searching for this item (better than nothing)
 
 552                                                                                                 $aSearch = $aCurrentSearch;
 
 553                                                                                                 $aSearch['iSearchRank'] += 1;
 
 554                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 558                                                                                 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
 
 560                                                                                         if ($aSearch['sClass'] === '')
 
 562                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
 
 563                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
 
 564                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
 
 565                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
 
 566                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
 
 568                                                                                                 // Do we have a shortcut id?
 
 569                                                                                                 if ($aSearch['sOperator'] == 'name')
 
 571                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
 
 572                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
 
 574                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
 
 575                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
 
 576                                                                                                                 $aSearch['sClass'] = '';
 
 577                                                                                                                 $aSearch['sType'] = '';
 
 580                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 583                                                                                 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
 
 585                                                                                         if (sizeof($aSearch['aName']))
 
 587                                                                                                 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
 
 589                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 593                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
 
 598                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 599 //                                                                                              $aSearch['iNamePhrase'] = $iPhrase;
 
 601                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 605                                                                 if (isset($aValidTokens[$sToken]))
 
 607                                                                         // Allow searching for a word - but at extra cost
 
 608                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
 
 610                                                                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
 
 612                                                                                         if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
 
 614                                                                                                 $aSearch = $aCurrentSearch;
 
 615                                                                                                 $aSearch['iSearchRank'] += 1;
 
 616                                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 617                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 620                                                                                         if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
 
 622                                                                                                 $aSearch = $aCurrentSearch;
 
 623                                                                                                 $aSearch['iSearchRank'] += 2;
 
 624                                                                                                 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
 
 625                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 626                                                                                                 $aSearch['iNamePhrase'] = $iPhrase;
 
 627                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 634                                                                         // Allow skipping a word - but at EXTREAM cost
 
 635                                                                         //$aSearch = $aCurrentSearch;
 
 636                                                                         //$aSearch['iSearchRank']+=100;
 
 637                                                                         //$aNewWordsetSearches[] = $aSearch;
 
 641                                                         usort($aNewWordsetSearches, 'bySearchRank');
 
 642                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 644 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 646                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 647                                                 usort($aNewPhraseSearches, 'bySearchRank');
 
 649           $aSearchHash = array();
 
 650           foreach($aNewPhraseSearches as $iSearch => $aSearch)
 
 652             $sHash = serialize($aSearch);
 
 653             if (isset($aSearchHash[$sHash]))
 
 655               unset($aNewPhraseSearches[$iSearch]);
 
 659               $aSearchHash[$sHash] = 1;
 
 663                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 666                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 667                                         $aGroupedSearches = array();
 
 668                                         foreach($aNewPhraseSearches as $aSearch)
 
 670                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 672                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 673                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 676                                         ksort($aGroupedSearches);
 
 679                                         $aSearches = array();
 
 680                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
 
 682                                                 $iSearchCount += sizeof($aNewSearches);
 
 683                                                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 684                                                 if ($iSearchCount > 50) break;
 
 687 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 693                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 694                                         $aGroupedSearches = array();
 
 695                                         foreach($aSearches as $aSearch)
 
 697                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 699                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 700                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 703                                         ksort($aGroupedSearches);
 
 706                                 if (CONST_Debug) var_Dump($aGroupedSearches);
 
 710                                         $aCopyGroupedSearches = $aGroupedSearches;
 
 711                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
 
 713                                                 foreach($aSearches as $iSearch => $aSearch)
 
 715                                                         if (sizeof($aSearch['aAddress']))
 
 717                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
 
 718                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
 
 720                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
 
 721                                                                         $aSearch['aName'] = array($iReverseItem);
 
 722                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
 
 724 //                                                              $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
 
 725         //                                                      $aGroupedSearches[$iGroup][] = $aReverseSearch;
 
 731                                 // Filter out duplicate searches
 
 732                                 $aSearchHash = array();
 
 733                                 foreach($aGroupedSearches as $iGroup => $aSearches)
 
 735                                         foreach($aSearches as $iSearch => $aSearch)
 
 737                                                 $sHash = serialize($aSearch);
 
 738                                                 if (isset($aSearchHash[$sHash]))
 
 740                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
 741                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
 745                                                         $aSearchHash[$sHash] = 1;
 
 750                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 754                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
 
 757                                         foreach($aSearches as $aSearch)
 
 761                                                 // Must have a location term
 
 762                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
 
 764                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
 
 766                                                                 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
 
 768                                                                         $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
 
 769                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 770                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
 
 771                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 776                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
 
 777                                                                 if (!$aSearch['sClass']) continue;
 
 778                                                                 if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 779                                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 780                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 781                                                                 if ($oDB->getOne($sSQL))
 
 783                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
 784                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 785                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
 
 786                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 787                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
 
 788                                                                 $sSQL .= " limit $iLimit";
 
 789                                                                 if (CONST_Debug) var_dump($sSQL);
 
 790                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 792                                                                 if (!sizeof($aPlaceIDs))
 
 794                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
 795                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 796                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
 
 797                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 798                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
 
 799                                                                         $sSQL .= " limit $iLimit";
 
 800                                                                         if (CONST_Debug) var_dump($sSQL);
 
 801                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 806                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 807                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
 
 808                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 809                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 810                                                                 $sSQL .= " limit $iLimit";
 
 811                                                                 if (CONST_Debug) var_dump($sSQL);
 
 812                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 818                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 819                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 820                                                         $aPlaceIDs = array();
 
 822                                                         // First we need a position, either aName or fLat or both
 
 826                                                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
 
 827                                                         // they might be right - but they are just too darned expensive to run
 
 828                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
 
 829                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
 
 830                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
 
 831                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
 
 832                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
 
 834                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
 
 835                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
 
 837                                                         if (sizeof($aExcludePlaceIDs))
 
 839                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 841                                                         if ($sCountryCodesSQL)
 
 843                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
 
 846                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
 
 847                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
 
 849                                                         $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
 
 851                                                         if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
 
 852                                                         if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
 
 853                                                         $aOrder[] = "$sImportanceSQL DESC";
 
 857                                                                 $sSQL = "select place_id";
 
 858                                                                 $sSQL .= " from search_name";
 
 859                                                                 $sSQL .= " where ".join(' and ',$aTerms);
 
 860                                                                 $sSQL .= " order by ".join(', ',$aOrder);
 
 861                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
 
 862                                                                         $sSQL .= " limit 50";
 
 863                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
 
 866                                                                         $sSQL .= " limit ".$iLimit;
 
 868                                                                 if (CONST_Debug) { var_dump($sSQL); }
 
 869                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
 
 870                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
 
 872                                                                         failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
 
 874 //var_dump($aViewBoxPlaceIDs);
 
 875                                                                 // Did we have an viewbox matches?
 
 876                                                                 $aPlaceIDs = array();
 
 877                                                                 $bViewBoxMatch = false;
 
 878                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
 
 880 //                                                                      if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
 
 881 //                                                                      if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
 
 882 //                                                                      if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
 
 883 //                                                                      else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
 
 884                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
 
 887 //var_Dump($aPlaceIDs);
 
 890                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
 
 892                                                                 $aRoadPlaceIDs = $aPlaceIDs;
 
 893                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 895                                                                 // Now they are indexed look for a house attached to a street we found
 
 896                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';                                                
 
 897                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
 
 898                                                                 if (sizeof($aExcludePlaceIDs))
 
 900                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 902                                                                 $sSQL .= " limit $iLimit";
 
 903                                                                 if (CONST_Debug) var_dump($sSQL);
 
 904                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 906                                                                 // If not try the aux fallback table
 
 907                                                                 if (!sizeof($aPlaceIDs))
 
 909                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 910                                                                         if (sizeof($aExcludePlaceIDs))
 
 912                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 914 //                                                                      $sSQL .= " limit $iLimit";
 
 915                                                                         if (CONST_Debug) var_dump($sSQL);
 
 916                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 919                                                                 if (!sizeof($aPlaceIDs))
 
 921                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 922                                                                         if (sizeof($aExcludePlaceIDs))
 
 924                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 926 //                                                                      $sSQL .= " limit $iLimit";
 
 927                                                                         if (CONST_Debug) var_dump($sSQL);
 
 928                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 931                                                                 // Fallback to the road
 
 932                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
 
 934                                                                         $aPlaceIDs = $aRoadPlaceIDs;
 
 939                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
 
 941                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 943                                                                 $aClassPlaceIDs = array();
 
 945                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
 
 947                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
 
 948                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 949                                                                         $sSQL .= " and linked_place_id is null";
 
 950                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 951                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
 
 952                                                                         if (CONST_Debug) var_dump($sSQL);
 
 953                                                                         $aClassPlaceIDs = $oDB->getCol($sSQL);
 
 956                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
 
 958                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 959                                                                         $bCacheTable = $oDB->getOne($sSQL);
 
 961                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
 
 963                                                                         if (CONST_Debug) var_dump($sSQL);
 
 964                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL));
 
 966                                                                         // For state / country level searches the normal radius search doesn't work very well
 
 968                                                                         if ($iMaxRank < 9 && $bCacheTable)
 
 970                                                                                 // Try and get a polygon to search in instead
 
 971                                                                                 $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";
 
 972                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 973                                                                                 $sPlaceGeom = $oDB->getOne($sSQL);
 
 983                                                                                 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 984                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 985                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 986                                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 989                                                                         if ($sPlaceIDs || $sPlaceGeom)
 
 995                                                                                 // More efficient - can make the range bigger
 
 999                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
 
1000                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
 
1001                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
1003                                                                                 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
 
1004                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
 
1007                                                                                         $sSQL .= ",placex as f where ";
 
1008                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
 
1013                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
 
1015                                                                                 if (sizeof($aExcludePlaceIDs))
 
1017                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
1019                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
 
1020                                                                                 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
 
1021                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
1022                                                                                 $sSQL .= " limit $iLimit";
 
1023                                                                                 if (CONST_Debug) var_dump($sSQL);
 
1024                                                                                 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
 
1028                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
 
1031                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
 
1032                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
 
1034                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
 
1035                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
 
1036                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
 
1037                                                                                 if (sizeof($aExcludePlaceIDs))
 
1039                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
1041                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";                                                           
 
1042                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
1043                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
1044                                                                                 $sSQL .= " limit $iLimit";
 
1045                                                                                 if (CONST_Debug) var_dump($sSQL);
 
1046                                                                                 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
 
1051                                                                 $aPlaceIDs = $aClassPlaceIDs;
 
1057                                                 if (PEAR::IsError($aPlaceIDs))
 
1059                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
 
1062                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
 
1064                                                 foreach($aPlaceIDs as $iPlaceID)
 
1066                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
 
1068                                                 if ($iQueryLoop > 20) break;
 
1072                                         if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
 
1073                                         if ($iGroupLoop > 4) break;
 
1074                                         if ($iQueryLoop > 30) break;
 
1077                                 // Did we find anything?        
 
1078                                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
 
1080 //var_Dump($aResultPlaceIDs);exit;
 
1081                                         // Get the details for display (is this a redundant extra step?)
 
1082                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
1083                                         $sOrderSQL = 'CASE ';
 
1084                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
1086                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
1088                                         $sOrderSQL .= ' ELSE 10000000 END';
 
1089                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
1090                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1091                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
1092                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
1093                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
1094 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1095                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
1096                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
1097                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
1098                                         $sSQL .= "and linked_place_id is null ";
 
1099                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
1100                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1101                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1102                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1103                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1105                                         $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,";
 
1106                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1107                                         $sSQL .= "null as placename,";
 
1108                                         $sSQL .= "null as ref,";
 
1109                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1110 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1111                                         $sSQL .= "-0.15 as importance ";
 
1112                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1113                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1114                                         $sSQL .= "group by place_id";
 
1115                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1117                                         $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,";
 
1118                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1119                                         $sSQL .= "null as placename,";
 
1120                                         $sSQL .= "null as ref,";
 
1121                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1122 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1123                                         $sSQL .= "-0.10 as importance ";
 
1124                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1125                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1126                                         $sSQL .= "group by place_id";
 
1127                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1128                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1129                                         $sSQL .= "order by importance desc";
 
1130 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1131                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1132                                         $aSearchResults = $oDB->getAll($sSQL);
 
1133 //var_dump($sSQL,$aSearchResults);exit;
 
1135                                         if (PEAR::IsError($aSearchResults))
 
1137                                                 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
 
1140                         } // end if ($sQuery)
 
1143                                 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
 
1145                                         $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
 
1146                                         $aResultPlaceIDs = array($iPlaceID);
 
1148                                         // TODO: this needs refactoring!
 
1150                                         // Get the details for display (is this a redundant extra step?)
 
1151                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
1152                                         $sOrderSQL = 'CASE ';
 
1153                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
1155                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
1157                                         $sOrderSQL .= ' ELSE 10000000 END';
 
1158                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
1159                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1160                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
1161                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
1162                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
1163 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1164                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
1165                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
1166                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
1167                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
1168                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1169                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1170                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1171                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1173                                         $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,";
 
1174                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1175                                         $sSQL .= "null as placename,";
 
1176                                         $sSQL .= "null as ref,";
 
1177                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1178 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1179                                         $sSQL .= "-0.15 as importance ";
 
1180                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1181                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1182                                         $sSQL .= "group by place_id";
 
1183                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1185                                         $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,";
 
1186                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1187                                         $sSQL .= "null as placename,";
 
1188                                         $sSQL .= "null as ref,";
 
1189                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1190 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1191                                         $sSQL .= "-0.10 as importance ";
 
1192                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1193                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1194                                         $sSQL .= "group by place_id";
 
1195                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1196                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1197                                         $sSQL .= "order by importance desc";
 
1198 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1199                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1200                                         $aSearchResults = $oDB->getAll($sSQL);
 
1201 //var_dump($sSQL,$aSearchResults);exit;
 
1203                                         if (PEAR::IsError($aSearchResults))
 
1205                         failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
 
1211         $sSearchResult = '';
 
1212         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
 
1214                 $sSearchResult = 'No Results Found';
 
1216 //var_Dump($aSearchResults);
 
1218         $aClassType = getClassTypesWithImportance();
 
1219         $aRecheckWords = preg_split('/\b/',$sQuery);
 
1220         foreach($aRecheckWords as $i => $sWord)
 
1222                 if (!$sWord) unset($aRecheckWords[$i]);
 
1224         foreach($aSearchResults as $iResNum => $aResult)
 
1226                 if (CONST_Search_AreaPolygons)
 
1228                         // Get the bounding box and outline polygon
 
1229                         $sSQL = "select place_id,numfeatures,area,outline,";
 
1230                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
 
1231                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
 
1232                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
 
1234                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
 
1235                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
 
1236                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
 
1237                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
 
1238                         if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
 
1239                         if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
 
1240                         if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
 
1241                         if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
 
1242                         $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
 
1243                         $aPointPolygon = $oDB->getRow($sSQL);
 
1244                         if (PEAR::IsError($aPointPolygon))
 
1246                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
 
1248                         if ($aPointPolygon['place_id'])
 
1250                                 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
 
1251                                 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
 
1252                                 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
 
1253                                 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
 
1255                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
 
1256                                         $aResult['lat'] = $aPointPolygon['centrelat'];
 
1257                                         $aResult['lon'] = $aPointPolygon['centrelon'];
 
1261                                         // Translate geometary string to point array
 
1262                                         if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
 
1264                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
1266                                         elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
 
1268                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
1270                                         elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
 
1273                                                 $iSteps = ($fRadius * 40000)^2;
 
1274                                                 $fStepSize = (2*pi())/$iSteps;
 
1275                                                 $aPolyPoints = array();
 
1276                                                 for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1278                                                         $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
 
1280                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
 
1281                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
 
1282                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
 
1283                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
 
1287                                 // Output data suitable for display (points and a bounding box)
 
1288                                 if ($bShowPolygons && isset($aPolyPoints))
 
1290                                         $aResult['aPolyPoints'] = array();
 
1291                                         foreach($aPolyPoints as $aPoint)
 
1293                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1296                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1300                 if (!isset($aResult['aBoundingBox']))
 
1303                         $fDiameter = 0.0001;
 
1305                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
 
1306                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
 
1308                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
 
1310                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
 
1311                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
 
1313                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
 
1315                         $fRadius = $fDiameter / 2;
 
1317                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
 
1318                         $fStepSize = (2*pi())/$iSteps;
 
1319                         $aPolyPoints = array();
 
1320                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1322                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
 
1324                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
 
1325                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
 
1326                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
 
1327                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
 
1329                         // Output data suitable for display (points and a bounding box)
 
1332                                 $aResult['aPolyPoints'] = array();
 
1333                                 foreach($aPolyPoints as $aPoint)
 
1335                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1338                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1341                 // Is there an icon set for this type of result?
 
1342                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
 
1343                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1345                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
1348                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) 
 
1349                         && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1351                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
1354                 if ($bShowAddressDetails)
 
1356                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
 
1357 //var_dump($aResult['address']);
 
1361                 // Adjust importance for the number of exact string matches in the result
 
1362                 $aResult['importance'] = max(0.001,$aResult['importance']);
 
1364                 $sAddress = $aResult['langaddress'];
 
1365                 foreach($aRecheckWords as $i => $sWord)
 
1367                         if (stripos($sAddress, $sWord)!==false) $iCountWords++;
 
1369                 $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
 
1371 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
 
1373                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
 
1374                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
 
1376                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
 
1378                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
 
1379                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1381                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1385                         $aResult['importance'] = 1000000000000000;
 
1388                 $aResult['name'] = $aResult['langaddress'];
 
1389                 $aResult['foundorder'] = $iResNum;
 
1390                 $aSearchResults[$iResNum] = $aResult;
 
1392         uasort($aSearchResults, 'byImportance');
 
1394 //var_dump($aSearchResults);exit;
 
1396         $aOSMIDDone = array();
 
1397         $aClassTypeNameDone = array();
 
1398         $aToFilter = $aSearchResults;
 
1399         $aSearchResults = array();
 
1402         foreach($aToFilter as $iResNum => $aResult)
 
1404                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
 
1405                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1408                         $fLat = $aResult['lat'];
 
1409                         $fLon = $aResult['lon'];
 
1410                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1413                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1414                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
 
1416                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1417                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
 
1418                         $aSearchResults[] = $aResult;
 
1421                 // Absolute limit on number of results
 
1422                 if (sizeof($aSearchResults) >= $iFinalLimit) break;
 
1425         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
 
1427         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
1429                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
 
1434                 logEnd($oDB, $hLog, sizeof($aToFilter));
 
1436         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
 
1437         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
 
1438         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
 
1439         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
 
1440         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
 
1441         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
 
1444                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
 
1446         $sMoreURL .= '&q='.urlencode($sQuery);
 
1448         if (CONST_Debug) exit;
 
1450         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');