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         $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
 
  21         $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
 
  23         if ($iLimit > 100) $iLimit = 100;
 
  25         $iMaxAddressRank = 30;
 
  28         if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' ||  $_GET['format'] == 'jsonv2'))
 
  30                 $sOutputFormat = $_GET['format'];
 
  33         // Show / use polygons
 
  34         $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
 
  36         // Show address breakdown
 
  37         $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
 
  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;
 
  45         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
 
  47         if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
 
  49                 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
 
  51                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
  52                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
  56         // Only certain ranks of feature
 
  57         if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
 
  59         if (isset($_GET['featuretype']))
 
  61                 switch($_GET['featuretype'])
 
  64                         $iMinAddressRank = $iMaxAddressRank = 4;
 
  67                         $iMinAddressRank = $iMaxAddressRank = 8;
 
  70                         $iMinAddressRank = 14;
 
  71                         $iMaxAddressRank = 16;
 
  75                         $iMaxAddressRank = 20;
 
  80         if (isset($_GET['countrycodes']))
 
  82                 $aCountryCodes = array();
 
  83                 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
 
  85                         if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
 
  87                                 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
 
  90                 $sCountryCodesSQL = join(',', $aCountryCodes);
 
  94         $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
 
  95         if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
 
  97                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
 
  99                 // reverse order of '/' separated string
 
 100                 $aPhrases = explode('/', $sQuery);              
 
 101                 $aPhrases = array_reverse($aPhrases); 
 
 102                 $sQuery = join(', ',$aPhrases);
 
 106                 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
 
 108                 // Hack to make it handle "new york, ny" (and variants) correctly
 
 109                 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
 
 110                 if (isset($aLangPrefOrder['name:en']))          
 
 112                         $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
 
 113                         $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
 
 114                         $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
 
 117                 // If we have a view box create the SQL
 
 118                 // Small is the actual view box, Large is double (on each axis) that 
 
 119                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
 
 120                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
 
 122                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
 
 123                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
 
 125                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
 
 127                         $aCoOrdinates = explode(',',$_GET['viewbox']);
 
 128                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
 129                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
 
 130                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
 
 131                         $aCoOrdinates[0] += $fHeight;
 
 132                         $aCoOrdinates[2] -= $fHeight;
 
 133                         $aCoOrdinates[1] += $fWidth;
 
 134                         $aCoOrdinates[3] -= $fWidth;
 
 135                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
 137                         $bBoundingBoxSearch = false;
 
 139                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
 
 141                         $aPoints = explode(',',$_GET['route']);
 
 142                         if (sizeof($aPoints) % 2 != 0)
 
 144                                 echo "Uneven number of points";
 
 147                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
 
 149                         foreach($aPoints as $i => $fPoint)
 
 153                                         if ($i != 1) $sViewboxCentreSQL .= ",";
 
 154                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
 
 158                                         $fPrevCoord = (float)$fPoint;
 
 161                         $sViewboxCentreSQL .= ")'::geometry,4326)";
 
 163                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
 
 164                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
 
 165                         if (PEAR::isError($sViewboxSmallSQL))
 
 167                                 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
 
 169                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
 
 171                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
 
 172                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
 
 173                         if (PEAR::isError($sViewboxLargeSQL))
 
 175                                 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
 
 177                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
 
 180                 // Do we have anything that looks like a lat/lon pair?
 
 181                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
 
 183                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
 
 184                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
 
 185                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 187                                 $_GET['nearlat'] = $fQueryLat;
 
 188                                 $_GET['nearlon'] = $fQueryLon;
 
 189                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 192                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
 
 194                         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
 
 195                         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
 
 196                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 198                                 $_GET['nearlat'] = $fQueryLat;
 
 199                                 $_GET['nearlon'] = $fQueryLon;
 
 200                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 203                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
 
 205                         $fQueryLat = $aData[2];
 
 206                         $fQueryLon = $aData[3];
 
 207                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 209                                 $_GET['nearlat'] = $fQueryLat;
 
 210                                 $_GET['nearlon'] = $fQueryLon;
 
 211                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 217                         // Start with a blank search
 
 219                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 
 
 220                                         'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
 
 223                         $sNearPointSQL = false;
 
 224                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
 226                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
 
 227                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
 
 228                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
 
 229                                 $aSearches[0]['fRadius'] = 0.1;
 
 232                         $bSpecialTerms = false;
 
 233                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 234                         $aSpecialTerms = array();
 
 235                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 237                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 238                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
 
 241                         preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 242                         $aSpecialTerms = array();
 
 243                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 245                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 246                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
 
 247                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
 
 248                                 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\',\'highway\')) or country_code is not null';
 
 249                                 if (CONST_Debug) var_Dump($sSQL);
 
 250                                 $aSearchWords = $oDB->getAll($sSQL);
 
 251                                 $aNewSearches = array();
 
 252                                 foreach($aSearches as $aSearch)
 
 254                                         foreach($aSearchWords as $aSearchTerm)
 
 256                                                 $aNewSearch = $aSearch;                 
 
 257                                                 if ($aSearchTerm['country_code'])
 
 259                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 260                                                         $aNewSearches[] = $aNewSearch;
 
 261                                                         $bSpecialTerms = true;
 
 263                                                 if ($aSearchTerm['class'])
 
 265                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
 
 266                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
 
 267                                                         $aNewSearches[] = $aNewSearch;
 
 268                                                         $bSpecialTerms = true;
 
 272                                 $aSearches = $aNewSearches;
 
 275                         // Split query into phrases
 
 276                         // Commas are used to reduce the search space by indicating where phrases split
 
 277                         $aPhrases = explode(',',$sQuery);
 
 279                         // Convert each phrase to standard form
 
 280                         // Create a list of standard words
 
 281                         // Get all 'sets' of words
 
 282                         // Generate a complete list of all 
 
 284                         foreach($aPhrases as $iPhrase => $sPhrase)
 
 286                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
 
 287                                 if (PEAR::isError($aPhrase))
 
 289                                         echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
 
 290                                         if (CONST_Debug) var_dump($aPhrase);
 
 293                                 if (trim($aPhrase['string']))
 
 295                                         $aPhrases[$iPhrase] = $aPhrase;
 
 296                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
 
 297                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
 
 298                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
 302                                         unset($aPhrases[$iPhrase]);
 
 306                         // reindex phrases - we make assumptions later on
 
 307                         $aPhrases = array_values($aPhrases);
 
 309                         if (sizeof($aTokens))
 
 312                         // Check which tokens we have, get the ID numbers                       
 
 313                         $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
 
 314                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
 
 316                         // (mis)using search_name_count to exclude words that return too many
 
 317                         // search results. saerch_name_count is currently set to 1 by hand
 
 318                         // because there is no fast way to extract this count from a live database. 
 
 319                         $sSQL .= ' and search_name_count = 0';
 
 320 //                      $sSQL .= ' and (class is null or class not in (\'highway\'))';
 
 321 //                      $sSQL .= ' group by word_token, word, class, type, location, country_code';
 
 323                         if (CONST_Debug) var_Dump($sSQL);
 
 325                         $aValidTokens = array();
 
 326                         if (sizeof($aTokens))
 
 327                                 $aDatabaseWords = $oDB->getAll($sSQL);
 
 329                                 $aDatabaseWords = array();
 
 330                         if (PEAR::IsError($aDatabaseWords))
 
 332                                 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
 
 334                         $aPossibleMainWordIDs = array();
 
 335                         foreach($aDatabaseWords as $aToken)
 
 337                                 if (isset($aValidTokens[$aToken['word_token']]))
 
 339                                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
 343                                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
 345                                 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
 
 347                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
 349                         $aSuggestion = array();
 
 350                         $bSuggestion = false;
 
 351                         if (CONST_Suggestions_Enabled)
 
 353                                 foreach($aPhrases as $iPhrase => $aPhrase)
 
 355                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
 
 357                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
 
 358                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
 
 359                                                 $aRow = $aSuggestionWords[0];
 
 360                                                 if ($aRow && $aRow['word'])
 
 362                                                         $aSuggestion[] = $aRow['word'];
 
 367                                                         $aSuggestion[] = $aPhrase['string'];
 
 372                                                 $aSuggestion[] = $aPhrase['string'];
 
 376                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
 
 378                         // Try and calculate GB postcodes we might be missing
 
 379                         foreach($aTokens as $sToken)
 
 381                                 // Source of gb postcodes is now definitive - always use
 
 382                                 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
 
 384                                         if (substr($aData[1],-2,1) != ' ')
 
 386                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
 
 387                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
 
 389                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
 
 390                                         if ($aGBPostcodeLocation)
 
 392                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
 
 397                         foreach($aTokens as $sToken)
 
 399                                 // Unknown single word token with a number - assume it is a house number
 
 400                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
 
 402                                         $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
 
 406                         // Any words that have failed completely?
 
 409                         // Start the search process
 
 410                         $aResultPlaceIDs = array();
 
 413                                 Calculate all searches using aValidTokens i.e.
 
 415                                 'Wodsworth Road, Sheffield' =>
 
 419                                 0      1       (wodsworth)(road)
 
 422                                 Score how good the search is so they can be ordered
 
 424                                 foreach($aPhrases as $iPhrase => $sPhrase)
 
 426                                         $aNewPhraseSearches = array();
 
 428                                         foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
 
 430                                                 $aWordsetSearches = $aSearches;
 
 432                                                 // Add all words from this wordset
 
 433                                                 foreach($aWordset as $sToken)
 
 435 //echo "<br><b>$sToken</b>";
 
 436                                                         $aNewWordsetSearches = array();
 
 438                                                         foreach($aWordsetSearches as $aCurrentSearch)
 
 441 //var_dump($aCurrentSearch);
 
 444                                                                 // If the token is valid
 
 445                                                                 if (isset($aValidTokens[' '.$sToken]))
 
 447                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
 
 449                                                                                 $aSearch = $aCurrentSearch;
 
 450                                                                                 $aSearch['iSearchRank']++;
 
 451                                                                                 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
 
 453                                                                                         if ($aSearch['sCountryCode'] === false)
 
 455                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 456                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
 
 457                                                                                                 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
 
 458                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 461                                                                                 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
 
 463                                                                                         if ($aSearch['fLat'] === '')
 
 465                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
 
 466                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
 
 467                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
 
 468                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 471                                                                                 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
 
 473                                                                                         if ($aSearch['sHouseNumber'] === '')
 
 475                                                                                                 $aSearch['sHouseNumber'] = $sToken;
 
 476                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 478                                                                                                 // Fall back to not searching for this item (better than nothing)
 
 479                                                                                                 $aSearch = $aCurrentSearch;
 
 480                                                                                                 $aSearch['iSearchRank'] += 1;
 
 481                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 485                                                                                 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
 
 487                                                                                         if ($aSearch['sClass'] === '')
 
 489                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
 
 490                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
 
 491                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
 
 492                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
 
 493                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
 
 495                                                                                                 // Do we have a shortcut id?
 
 496                                                                                                 if ($aSearch['sOperator'] == 'name')
 
 498                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
 
 499                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
 
 501                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
 
 502                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
 
 503                                                                                                                 $aSearch['sClass'] = '';
 
 504                                                                                                                 $aSearch['sType'] = '';
 
 507                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 510                                                                                 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
 
 512                                                                                         if (sizeof($aSearch['aName']))
 
 514                                                                                                 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
 
 516                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 520                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
 
 525                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 526 //                                                                                              $aSearch['iNamePhrase'] = $iPhrase;
 
 528                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 532                                                                 if (isset($aValidTokens[$sToken]))
 
 534                                                                         // Allow searching for a word - but at extra cost
 
 535                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
 
 537                                                                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
 
 539 //var_Dump('<hr>',$aSearch['aName']);
 
 541                                                                                 if (sizeof($aCurrentSearch['aName'])  && strlen($sToken) >= 4)
 
 543                                                                                 $aSearch = $aCurrentSearch;
 
 544                                                                                         $aSearch['iSearchRank'] += 1;
 
 545                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 546                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 549                                                                                 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
 
 551                                                                                 $aSearch = $aCurrentSearch;
 
 552                                                                                         $aSearch['iSearchRank'] += 2;
 
 553                                                                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
 
 554                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 555                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
 
 556                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 563                                                                         // Allow skipping a word - but at EXTREAM cost
 
 564                                                                         //$aSearch = $aCurrentSearch;
 
 565                                                                         //$aSearch['iSearchRank']+=100;
 
 566                                                                         //$aNewWordsetSearches[] = $aSearch;
 
 570                                                         usort($aNewWordsetSearches, 'bySearchRank');
 
 571                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 573 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 575                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 576                                                 usort($aNewPhraseSearches, 'bySearchRank');
 
 578           $aSearchHash = array();
 
 579           foreach($aNewPhraseSearches as $iSearch => $aSearch)
 
 581             $sHash = serialize($aSearch);
 
 582             if (isset($aSearchHash[$sHash]))
 
 584               unset($aNewPhraseSearches[$iSearch]);
 
 588               $aSearchHash[$sHash] = 1;
 
 592                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 595                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 596                                         $aGroupedSearches = array();
 
 597                                         foreach($aNewPhraseSearches as $aSearch)
 
 599                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 601                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 602                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 605                                         ksort($aGroupedSearches);
 
 608                                         $aSearches = array();
 
 609                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
 
 611                                                 $iSearchCount += sizeof($aNewSearches);
 
 612                                                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 613                                                 if ($iSearchCount > 50) break;
 
 616 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 622                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 623                                         $aGroupedSearches = array();
 
 624                                         foreach($aSearches as $aSearch)
 
 626                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 628                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 629                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 632                                         ksort($aGroupedSearches);
 
 635                                 if (CONST_Debug) var_Dump($aGroupedSearches);
 
 639                                         $aCopyGroupedSearches = $aGroupedSearches;
 
 640                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
 
 642                                                 foreach($aSearches as $iSearch => $aSearch)
 
 644                                                         if (sizeof($aSearch['aAddress']))
 
 646                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
 
 647                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
 
 649                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
 
 650                                                                         $aSearch['aName'] = array($iReverseItem);
 
 651                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
 
 653 //                                                              $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
 
 654         //                                                      $aGroupedSearches[$iGroup][] = $aReverseSearch;
 
 660                                 // Filter out duplicate searches
 
 661                                 $aSearchHash = array();
 
 662                                 foreach($aGroupedSearches as $iGroup => $aSearches)
 
 664                                         foreach($aSearches as $iSearch => $aSearch)
 
 666                                                 $sHash = serialize($aSearch);
 
 667                                                 if (isset($aSearchHash[$sHash]))
 
 669                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
 670                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
 674                                                         $aSearchHash[$sHash] = 1;
 
 679                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 683                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
 
 686                                         foreach($aSearches as $aSearch)
 
 690                                                 // Must have a location term
 
 691                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
 
 693                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
 
 695                                                                 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
 
 697                                                                         $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
 
 698                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 699                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
 
 700                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 705                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
 
 706                                                                 if (!$aSearch['sClass']) continue;
 
 707                                                                 if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 708                                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 710                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 711                                                                 if ($oDB->getOne($sSQL))
 
 713                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
 714                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 715                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
 
 716                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 717                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
 
 718                                                                 $sSQL .= " limit $iLimit";
 
 719                                                                 if (CONST_Debug) var_dump($sSQL);
 
 720                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 722                                                                 if (!sizeof($aPlaceIDs))
 
 724                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
 725                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 726                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
 
 727                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 728                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
 
 729                                                                         $sSQL .= " limit $iLimit";
 
 730                                                                         if (CONST_Debug) var_dump($sSQL);
 
 731                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 736                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 737                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
 
 738                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 739                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 740                                                                 $sSQL .= " limit $iLimit";
 
 741                                                                 if (CONST_Debug) var_dump($sSQL);
 
 742                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 748                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 749                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 750                                                         $aPlaceIDs = array();
 
 752                                                         // First we need a position, either aName or fLat or both
 
 756                                                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
 
 757                                                         // they might be right - but they are just too darned expensive to run
 
 758                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
 
 759                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
 
 760                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
 
 761                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
 
 762                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
 
 764                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
 
 765                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
 
 767                                                         if (sizeof($aExcludePlaceIDs))
 
 769                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 771                                                         if ($sCountryCodesSQL)
 
 773                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
 
 776                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
 
 777                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
 
 779                                                         $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
 
 781                                                         if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
 
 782                                                         if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
 
 783                                                         $aOrder[] = "$sImportanceSQL DESC";
 
 787                                                                 $sSQL = "select place_id";
 
 788                                                                 $sSQL .= " from search_name";
 
 789                                                                 $sSQL .= " where ".join(' and ',$aTerms);
 
 790                                                                 $sSQL .= " order by ".join(', ',$aOrder);
 
 791                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
 
 792                                                                         $sSQL .= " limit 50";
 
 793                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
 
 796                                                                         $sSQL .= " limit ".$iLimit;
 
 798                                                                 if (CONST_Debug) var_dump($sSQL);
 
 799                                                                 $iStartTime = time();
 
 800                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
 
 801                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
 
 803                                                                         failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
 
 805                                                                 if (time() - $iStartTime > 60) {
 
 806                                                                         file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
 
 809 //var_dump($aViewBoxPlaceIDs);
 
 810                                                                 // Did we have an viewbox matches?
 
 811                                                                 $aPlaceIDs = array();
 
 812                                                                 $bViewBoxMatch = false;
 
 813                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
 
 815 //                                                                      if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
 
 816 //                                                                      if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
 
 817 //                                                                      if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
 
 818 //                                                                      else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
 
 819                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
 
 822 //var_Dump($aPlaceIDs);
 
 825                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
 
 827                                                                 $aRoadPlaceIDs = $aPlaceIDs;
 
 828                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 830                                                                 // Now they are indexed look for a house attached to a street we found
 
 831                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';                                                
 
 832                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
 
 833                                                                 if (sizeof($aExcludePlaceIDs))
 
 835                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 837                                                                 $sSQL .= " limit $iLimit";
 
 838                                                                 if (CONST_Debug) var_dump($sSQL);
 
 839                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 841                                                                 // If not try the aux fallback table
 
 842                                                                 if (!sizeof($aPlaceIDs))
 
 844                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 845                                                                         if (sizeof($aExcludePlaceIDs))
 
 847                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 849 //                                                                      $sSQL .= " limit $iLimit";
 
 850                                                                         if (CONST_Debug) var_dump($sSQL);
 
 851                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 854                                                                 if (!sizeof($aPlaceIDs))
 
 856                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 857                                                                         if (sizeof($aExcludePlaceIDs))
 
 859                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 861 //                                                                      $sSQL .= " limit $iLimit";
 
 862                                                                         if (CONST_Debug) var_dump($sSQL);
 
 863                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 866                                                                 // Fallback to the road
 
 867                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
 
 869                                                                         $aPlaceIDs = $aRoadPlaceIDs;
 
 874                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
 
 876                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 878                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
 
 880                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
 
 881                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 882                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 883                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
 
 884                                                                         if (CONST_Debug) var_dump($sSQL);
 
 885                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 888                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
 
 890                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 891                                                                         $bCacheTable = $oDB->getOne($sSQL);
 
 893                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
 
 895                                                                         if (CONST_Debug) var_dump($sSQL);
 
 896                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL));
 
 898                                                                         // For state / country level searches the normal radius search doesn't work very well
 
 900                                                                         if ($iMaxRank < 9 && $bCacheTable)
 
 902                                                                                 // Try and get a polygon to search in instead
 
 903         $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
 
 904         if (CONST_Debug) var_dump($sSQL);
 
 905         $sPlaceGeom = $oDB->getOne($sSQL);
 
 915                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 916                                                                         if (CONST_Debug) var_dump($sSQL);
 
 917                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 918                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
 
 921                                                                         if ($sPlaceIDs || $sPlaceGeom)
 
 927                                                                                 // More efficient - can make the range bigger
 
 931                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
 
 932                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
 
 933                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
 935                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
 
 936                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
 
 939                                                                                         $sSQL .= ",placex as f where ";
 
 940                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
 
 945                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
 
 947                                                                                 if (sizeof($aExcludePlaceIDs))
 
 949                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 951                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
 
 952                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
 953                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
 954                                                                                 $sSQL .= " limit $iLimit";
 
 955                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 956                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 960                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
 
 963                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
 
 964                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
 
 966                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
 
 967                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
 
 968                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
 
 969                                                                                 if (sizeof($aExcludePlaceIDs))
 
 971                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 973                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";                                                           
 
 974                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
 975                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
 976                                                                                 $sSQL .= " limit $iLimit";
 
 977                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 978                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 986                                                 if (PEAR::IsError($aPlaceIDs))
 
 988                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
 
 991                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
 
 993                                                 foreach($aPlaceIDs as $iPlaceID)
 
 995                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
 
 997                                                 if ($iQueryLoop > 20) break;
 
1000                                         if (sizeof($aResultPlaceIDs)) break;
 
1001                                         if ($iGroupLoop > 4) break;
 
1002                                         if ($iQueryLoop > 30) break;
 
1005                                 // Did we find anything?        
 
1006                                 if (sizeof($aResultPlaceIDs))
 
1008 //var_Dump($aResultPlaceIDs);exit;
 
1009                                         // Get the details for display (is this a redundant extra step?)
 
1010                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
1011                                         $sOrderSQL = 'CASE ';
 
1012                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
1014                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
1016                                         $sOrderSQL .= ' ELSE 10000000 END';
 
1017                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
1018                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1019                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
1020                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
1021                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
1022 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1023                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
1024                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
1025                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
1026                                         $sSQL .= "and linked_place_id is null ";
 
1027                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
1028                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1029                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1030                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1031                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1033                                         $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
1034                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1035                                         $sSQL .= "null as placename,";
 
1036                                         $sSQL .= "null as ref,";
 
1037                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1038 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1039                                         $sSQL .= "-0.15 as importance ";
 
1040                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1041                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1042                                         $sSQL .= "group by place_id";
 
1043                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1045                                         $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
1046                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1047                                         $sSQL .= "null as placename,";
 
1048                                         $sSQL .= "null as ref,";
 
1049                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1050 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1051                                         $sSQL .= "-0.10 as importance ";
 
1052                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1053                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1054                                         $sSQL .= "group by place_id";
 
1055                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1056                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1057                                         $sSQL .= "order by importance desc";
 
1058 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1059                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1060                                         $aSearchResults = $oDB->getAll($sSQL);
 
1061 //var_dump($sSQL,$aSearchResults);exit;
 
1063                                         if (PEAR::IsError($aSearchResults))
 
1065                                                 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
 
1068                         } // end if ($sQuery)
 
1071                                 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
 
1073                                         $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
 
1074                                         $aResultPlaceIDs = array($iPlaceID);
 
1076                                         // TODO: this needs refactoring!
 
1078                                         // Get the details for display (is this a redundant extra step?)
 
1079                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
1080                                         $sOrderSQL = 'CASE ';
 
1081                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
1083                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
1085                                         $sOrderSQL .= ' ELSE 10000000 END';
 
1086                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
1087                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1088                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
1089                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
1090                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
1091 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1092                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
1093                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
1094                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
1095                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
1096                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1097                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1098                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1099                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1101                                         $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
1102                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1103                                         $sSQL .= "null as placename,";
 
1104                                         $sSQL .= "null as ref,";
 
1105                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1106 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1107                                         $sSQL .= "-0.15 as importance ";
 
1108                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1109                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1110                                         $sSQL .= "group by place_id";
 
1111                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1113                                         $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
1114                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1115                                         $sSQL .= "null as placename,";
 
1116                                         $sSQL .= "null as ref,";
 
1117                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1118 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1119                                         $sSQL .= "-0.10 as importance ";
 
1120                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1121                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1122                                         $sSQL .= "group by place_id";
 
1123                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1124                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1125                                         $sSQL .= "order by importance desc";
 
1126 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1127                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1128                                         $aSearchResults = $oDB->getAll($sSQL);
 
1129 //var_dump($sSQL,$aSearchResults);exit;
 
1131                                         if (PEAR::IsError($aSearchResults))
 
1133                         failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
 
1139         $sSearchResult = '';
 
1140         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
 
1142                 $sSearchResult = 'No Results Found';
 
1144 //var_Dump($aSearchResults);
 
1146         $aClassType = getClassTypesWithImportance();
 
1147         $aRecheckWords = preg_split('/\b/',$sQuery);
 
1148         foreach($aRecheckWords as $i => $sWord)
 
1150                 if (!$sWord) unset($aRecheckWords[$i]);
 
1152         foreach($aSearchResults as $iResNum => $aResult)
 
1154                 if (CONST_Search_AreaPolygons)
 
1156                         // Get the bounding box and outline polygon
 
1157                         $sSQL = "select place_id,numfeatures,area,outline,";
 
1158                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
 
1159                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
 
1160                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
 
1162                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
 
1163                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
 
1164                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
 
1165                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon,";
 
1166                         $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
 
1167                         $aPointPolygon = $oDB->getRow($sSQL);
 
1168                         if (PEAR::IsError($aPointPolygon))
 
1170                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
 
1172                         if ($aPointPolygon['place_id'])
 
1174                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
 
1175                                         $aResult['lat'] = $aPointPolygon['centrelat'];
 
1176                                         $aResult['lon'] = $aPointPolygon['centrelon'];
 
1178                                 // Translate geometary string to point array
 
1179                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
 
1181                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
1183                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
 
1186                                         $iSteps = ($fRadius * 40000)^2;
 
1187                                         $fStepSize = (2*pi())/$iSteps;
 
1188                                         $aPolyPoints = array();
 
1189                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1191                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
 
1193                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
 
1194                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
 
1195                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
 
1196                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
 
1199                                 // Output data suitable for display (points and a bounding box)
 
1200                                 if ($bShowPolygons && isset($aPolyPoints))
 
1202                                         $aResult['aPolyPoints'] = array();
 
1203                                         foreach($aPolyPoints as $aPoint)
 
1205                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1208                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1212                 if (!isset($aResult['aBoundingBox']))
 
1215                         $fDiameter = 0.0001;
 
1217                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
 
1218                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
 
1220                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
 
1222                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
 
1223                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
 
1225                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
 
1227                         $fRadius = $fDiameter / 2;
 
1229                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
 
1230                         $fStepSize = (2*pi())/$iSteps;
 
1231                         $aPolyPoints = array();
 
1232                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1234                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
 
1236                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
 
1237                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
 
1238                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
 
1239                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
 
1241                         // Output data suitable for display (points and a bounding box)
 
1244                                 $aResult['aPolyPoints'] = array();
 
1245                                 foreach($aPolyPoints as $aPoint)
 
1247                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1250                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1253                 // Is there an icon set for this type of result?
 
1254                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
 
1255                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1257                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
1260                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) 
 
1261                         && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1263                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
1266                 if ($bShowAddressDetails)
 
1268                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
 
1269 //var_dump($aResult['address']);
 
1273                 // Adjust importance for the number of exact string matches in the result
 
1274                 $aResult['importance'] = max(0.001,$aResult['importance']);
 
1276                 $sAddress = $aResult['langaddress'];
 
1277                 foreach($aRecheckWords as $i => $sWord)
 
1279                         if (stripos($sAddress, $sWord)!==false) $iCountWords++;
 
1281                 $aResult['importance'] = $aResult['importance'] + $iCountWords;
 
1283 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
 
1285                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
 
1286                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
 
1288                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
 
1290                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
 
1291                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1293                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1297                         $aResult['importance'] = 1000000000000000;
 
1300                 $aResult['name'] = $aResult['langaddress'];
 
1301                 $aResult['foundorder'] = $iResNum;
 
1302                 $aSearchResults[$iResNum] = $aResult;
 
1304         uasort($aSearchResults, 'byImportance');
 
1306 //var_dump($aSearchResults);exit;
 
1308         $aOSMIDDone = array();
 
1309         $aClassTypeNameDone = array();
 
1310         $aToFilter = $aSearchResults;
 
1311         $aSearchResults = array();
 
1314         foreach($aToFilter as $iResNum => $aResult)
 
1316                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
 
1317                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1320                         $fLat = $aResult['lat'];
 
1321                         $fLon = $aResult['lon'];
 
1322                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1325                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1326                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
 
1328                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1329                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
 
1330                         $aSearchResults[] = $aResult;
 
1333                 // Absolute limit on number of results
 
1334                 if (sizeof($aSearchResults) >= $iLimit) break;
 
1337         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
 
1339         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
1341                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
 
1346                 logEnd($oDB, $hLog, sizeof($aToFilter));
 
1348         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
 
1349         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
 
1350         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
 
1351         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
 
1352         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
 
1353         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
 
1356                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
 
1358         $sMoreURL .= '&q='.urlencode($sQuery);
 
1360         if (CONST_Debug) exit;
 
1362         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');