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 = getPrefferedLangauges();
 
  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 && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
 
  97                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
 
  99                 // reverse order of '/' seperated 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('/\\bil\\b/','illinois', $sQuery);
 
 113                         $sQuery = preg_replace('/\\bal\\b/','alabama', $sQuery);
 
 114                         $sQuery = preg_replace('/\\bla\\b/','louisiana', $sQuery);
 
 115                         $sQuery = preg_replace('/\\bde louisiana\\b/','de la', $sQuery);
 
 118                 // If we have a view box create the SQL
 
 119                 // Small is the actual view box, Large is double (on each axis) that 
 
 120                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
 
 121                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
 
 123                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
 
 124                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
 
 126                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
 
 128                         $aCoOrdinates = explode(',',$_GET['viewbox']);
 
 129                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
 130                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
 
 131                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
 
 132                         $aCoOrdinates[0] += $fHeight;
 
 133                         $aCoOrdinates[2] -= $fHeight;
 
 134                         $aCoOrdinates[1] += $fWidth;
 
 135                         $aCoOrdinates[3] -= $fWidth;
 
 136                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
 138                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
 
 140                         $aPoints = explode(',',$_GET['route']);
 
 141                         if (sizeof($aPoints) % 2 != 0)
 
 143                                 echo "Uneven number of points";
 
 146                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
 
 148                         foreach($aPoints as $i => $fPoint)
 
 152                                         if ($i != 1) $sViewboxCentreSQL .= ",";
 
 153                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
 
 157                                         $fPrevCoord = (float)$fPoint;
 
 160                         $sViewboxCentreSQL .= ")'::geometry,4326)";
 
 162                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
 
 163                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
 
 164                         if (PEAR::isError($sViewboxSmallSQL))
 
 166                                 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
 
 168                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
 
 170                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
 
 171                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
 
 172                         if (PEAR::isError($sViewboxLargeSQL))
 
 174                                 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
 
 176                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
 
 179                 // Do we have anything that looks like a lat/lon pair?
 
 180                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
 
 182                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
 
 183                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
 
 184                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 186                                 $_GET['nearlat'] = $fQueryLat;
 
 187                                 $_GET['nearlon'] = $fQueryLon;
 
 188                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 191                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
 
 193                         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
 
 194                         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
 
 195                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 197                                 $_GET['nearlat'] = $fQueryLat;
 
 198                                 $_GET['nearlon'] = $fQueryLon;
 
 199                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 202                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
 
 204                         $fQueryLat = $aData[2];
 
 205                         $fQueryLon = $aData[3];
 
 206                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 208                                 $_GET['nearlat'] = $fQueryLat;
 
 209                                 $_GET['nearlon'] = $fQueryLon;
 
 210                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 216                         // Start with a blank search
 
 218                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 
 
 219                                         'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
 
 222                         $sNearPointSQL = false;
 
 223                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
 225                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
 
 226                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
 
 227                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
 
 228                                 $aSearches[0]['fRadius'] = 0.1;
 
 231                         $bSpecialTerms = false;
 
 232                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 233                         $aSpecialTerms = array();
 
 234                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 236                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 237                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
 
 240                         preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 241                         $aSpecialTerms = array();
 
 242                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 244                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 245                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
 
 246                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
 
 247                                 $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';
 
 248                                 $aSearchWords = $oDB->getAll($sSQL);
 
 249                                 $aNewSearches = array();
 
 250                                 foreach($aSearches as $aSearch)
 
 252                                         foreach($aSearchWords as $aSearchTerm)
 
 254                                                 $aNewSearch = $aSearch;                 
 
 255                                                 if ($aSearchTerm['country_code'])
 
 257                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 258                                                         $aNewSearches[] = $aNewSearch;
 
 259                                                         $bSpecialTerms = true;
 
 261                                                 if ($aSearchTerm['class'])
 
 263                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
 
 264                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
 
 265                                                         $aNewSearches[] = $aNewSearch;
 
 266                                                         $bSpecialTerms = true;
 
 270                                 $aSearches = $aNewSearches;
 
 273                         // Split query into phrases
 
 274                         // Commas are used to reduce the search space by indicating where phrases split
 
 275                         $aPhrases = explode(',',$sQuery);
 
 277                         // Convert each phrase to standard form
 
 278                         // Create a list of standard words
 
 279                         // Get all 'sets' of words
 
 280                         // Generate a complete list of all 
 
 282                         foreach($aPhrases as $iPhrase => $sPhrase)
 
 284                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
 
 285                                 if (PEAR::isError($aPhrase))
 
 287                                         echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
 
 288                                         if (CONST_Debug) var_dump($aPhrase);
 
 291                                 if (trim($aPhrase['string']))
 
 293                                         $aPhrases[$iPhrase] = $aPhrase;
 
 294                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
 
 295                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
 
 296                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
 300                                         unset($aPhrases[$iPhrase]);
 
 304                         // reindex phrases - we make assumptions later on
 
 305                         $aPhrases = array_values($aPhrases);
 
 307                         if (sizeof($aTokens))
 
 310                         // Check which tokens we have, get the ID numbers                       
 
 311                         $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
 
 312                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
 
 313                         $sSQL .= ' and (class is null or class not in (\'highway\'))';
 
 314 //                      $sSQL .= ' group by word_token, word, class, type, location, country_code';
 
 316                         if (CONST_Debug) var_Dump($sSQL);
 
 318                         $aValidTokens = array();
 
 319                         if (sizeof($aTokens))
 
 320                                 $aDatabaseWords = $oDB->getAll($sSQL);
 
 322                                 $aDatabaseWords = array();
 
 323                         if (PEAR::IsError($aDatabaseWords))
 
 325                                 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
 
 327                         $aPossibleMainWordIDs = array();
 
 328                         foreach($aDatabaseWords as $aToken)
 
 330                                 if (isset($aValidTokens[$aToken['word_token']]))
 
 332                                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
 336                                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
 338                                 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
 
 340                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
 342                         $aSuggestion = array();
 
 343                         $bSuggestion = false;
 
 344                         if (CONST_Suggestions_Enabled)
 
 346                                 foreach($aPhrases as $iPhrase => $aPhrase)
 
 348                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
 
 350                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
 
 351                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
 
 352                                                 $aRow = $aSuggestionWords[0];
 
 353                                                 if ($aRow && $aRow['word'])
 
 355                                                         $aSuggestion[] = $aRow['word'];
 
 360                                                         $aSuggestion[] = $aPhrase['string'];
 
 365                                                 $aSuggestion[] = $aPhrase['string'];
 
 369                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
 
 371                         // Try and calculate GB postcodes we might be missing
 
 372                         foreach($aTokens as $sToken)
 
 374                                 if (!isset($aValidTokens[$sToken]) && !isset($aValidTokens[' '.$sToken]) && preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
 
 376                                         if (substr($aData[1],-2,1) != ' ')
 
 378                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
 
 379                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
 
 381                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
 
 382                                         if ($aGBPostcodeLocation)
 
 384                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
 
 389                         foreach($aTokens as $sToken)
 
 391                                 // Unknown single word token with a number - assume it is a house number
 
 392                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
 
 394                                         $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
 
 398                         // Any words that have failed completely?
 
 401                         // Start the search process
 
 402                         $aResultPlaceIDs = array();
 
 405                                 Calculate all searches using aValidTokens i.e.
 
 407                                 'Wodsworth Road, Sheffield' =>
 
 411                                 0      1       (wodsworth)(road)
 
 414                                 Score how good the search is so they can be ordered
 
 417                                 foreach($aPhrases as $iPhrase => $sPhrase)
 
 419                                         $aNewPhraseSearches = array();
 
 421                                         foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
 
 423                                                 $aWordsetSearches = $aSearches;
 
 425                                                 // Add all words from this wordset
 
 426                                                 foreach($aWordset as $sToken)
 
 428 //echo "<br><b>$sToken</b>";
 
 429                                                         $aNewWordsetSearches = array();
 
 431                                                         foreach($aWordsetSearches as $aCurrentSearch)
 
 434 //var_dump($aCurrentSearch);
 
 437                                                                 // If the token is valid
 
 438                                                                 if (isset($aValidTokens[' '.$sToken]))
 
 440                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
 
 442                                                                                 $aSearch = $aCurrentSearch;
 
 443                                                                                 $aSearch['iSearchRank']++;
 
 444                                                                                 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
 
 446                                                                                         if ($aSearch['sCountryCode'] === false)
 
 448                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 449                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
 
 450                                                                                                 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
 
 451                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 454                                                                                 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
 
 456                                                                                         if ($aSearch['fLat'] === '')
 
 458                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
 
 459                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
 
 460                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
 
 461                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 464                                                                                 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
 
 466                                                                                         if ($aSearch['sHouseNumber'] === '')
 
 468                                                                                                 $aSearch['sHouseNumber'] = $sToken;
 
 469                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 471                                                                                                 // Fall back to not searching for this item (better than nothing)
 
 472                                                                                                 $aSearch = $aCurrentSearch;
 
 473                                                                                                 $aSearch['iSearchRank'] += 1;
 
 474                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 478                                                                                 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
 
 480                                                                                         if ($aSearch['sClass'] === '')
 
 482                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
 
 483                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
 
 484                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
 
 485                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
 
 486                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
 
 488                                                                                                 // Do we have a shortcut id?
 
 489                                                                                                 if ($aSearch['sOperator'] == 'name')
 
 491                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
 
 492                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
 
 494                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
 
 495                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
 
 496                                                                                                                 $aSearch['sClass'] = '';
 
 497                                                                                                                 $aSearch['sType'] = '';
 
 500                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 505                                                                                         if (sizeof($aSearch['aName']))
 
 507                                                                                                 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
 
 509                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 513                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
 
 518                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 519 //                                                                                              $aSearch['iNamePhrase'] = $iPhrase;
 
 521                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 525                                                                 if (isset($aValidTokens[$sToken]))
 
 527                                                                         // Allow searching for a word - but at extra cost
 
 528                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
 
 530 //var_Dump('<hr>',$aSearch['aName']);
 
 532                                                                                 if (sizeof($aCurrentSearch['aName'])  && strlen($sToken) >= 4)
 
 534                                                                                 $aSearch = $aCurrentSearch;
 
 535                                                                                         $aSearch['iSearchRank'] += 1;
 
 536                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 537                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 540                                                                                 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
 
 542                                                                                 $aSearch = $aCurrentSearch;
 
 543                                                                                         $aSearch['iSearchRank'] += 2;
 
 544                                                                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
 
 545                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 546                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
 
 547                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 553                                                                         // Allow skipping a word - but at EXTREAM cost
 
 554                                                                         //$aSearch = $aCurrentSearch;
 
 555                                                                         //$aSearch['iSearchRank']+=100;
 
 556                                                                         //$aNewWordsetSearches[] = $aSearch;
 
 560                                                         usort($aNewWordsetSearches, 'bySearchRank');
 
 561                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 563 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 565                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 566                                                 usort($aNewPhraseSearches, 'bySearchRank');
 
 568           $aSearchHash = array();
 
 569           foreach($aNewPhraseSearches as $iSearch => $aSearch)
 
 571             $sHash = serialize($aSearch);
 
 572             if (isset($aSearchHash[$sHash]))
 
 574               unset($aNewPhraseSearches[$iSearch]);
 
 578               $aSearchHash[$sHash] = 1;
 
 582                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 585                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 586                                         $aGroupedSearches = array();
 
 587                                         foreach($aNewPhraseSearches as $aSearch)
 
 589                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 591                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 592                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 595                                         ksort($aGroupedSearches);
 
 598                                         $aSearches = array();
 
 599                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
 
 601                                                 $iSearchCount += sizeof($aNewSearches);
 
 602                                                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 603                                                 if ($iSearchCount > 50) break;
 
 606 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 612                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 613                                         $aGroupedSearches = array();
 
 614                                         foreach($aSearches as $aSearch)
 
 616                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 618                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 619                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 622                                         ksort($aGroupedSearches);
 
 625                                 if (CONST_Debug) var_Dump($aGroupedSearches);
 
 629                                         $aCopyGroupedSearches = $aGroupedSearches;
 
 630                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
 
 632                                                 foreach($aSearches as $iSearch => $aSearch)
 
 634                                                         if (sizeof($aSearch['aAddress']))
 
 636                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
 
 637                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
 
 639                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
 
 640                                                                         $aSearch['aName'] = array($iReverseItem);
 
 641                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
 
 643 //                                                              $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
 
 644         //                                                      $aGroupedSearches[$iGroup][] = $aReverseSearch;
 
 650                                 // Filter out duplicate searches
 
 651                                 $aSearchHash = array();
 
 652                                 foreach($aGroupedSearches as $iGroup => $aSearches)
 
 654                                         foreach($aSearches as $iSearch => $aSearch)
 
 656                                                 $sHash = serialize($aSearch);
 
 657                                                 if (isset($aSearchHash[$sHash]))
 
 659                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
 660                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
 664                                                         $aSearchHash[$sHash] = 1;
 
 669                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 673                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
 
 676                                         foreach($aSearches as $aSearch)
 
 680                                                 // Must have a location term
 
 681                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
 
 683                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
 
 685                                                                 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
 
 687                                                                         $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
 
 688                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 689                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
 
 690                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 695                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
 
 696                                                                 if (!$aSearch['sClass']) continue;
 
 697                                                                 if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 698                                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 700                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 701                                                                 if ($oDB->getOne($sSQL))
 
 703                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
 
 704                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 705                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
 
 706                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 707                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 708                                                                 $sSQL .= " limit $iLimit";
 
 709                                                                 if (CONST_Debug) var_dump($sSQL);
 
 710                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 712                                                                 if (!sizeof($aPlaceIDs))
 
 714                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
 
 715                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 716                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
 
 717                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 718                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 719                                                                         $sSQL .= " limit $iLimit";
 
 720                                                                         if (CONST_Debug) var_dump($sSQL);
 
 721                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 726                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 727                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
 
 728                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 729                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 730                                                                 $sSQL .= " limit $iLimit";
 
 731                                                                 if (CONST_Debug) var_dump($sSQL);
 
 732                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 738                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 739                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 740                                                         $aPlaceIDs = array();
 
 742                                                         // First we need a position, either aName or fLat or both
 
 745                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
 
 746                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
 
 747                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
 
 748                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
 
 749                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
 
 751                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
 
 752                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
 
 754                                                         if (sizeof($aExcludePlaceIDs))
 
 756                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 758                                                         if ($sCountryCodesSQL)
 
 760                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
 
 763                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
 
 764                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
 
 766                                                         $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
 
 768                                                         if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
 
 769                                                         if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
 
 770                                                         $aOrder[] = "$sImportanceSQL DESC";
 
 774                                                                 $sSQL = "select place_id";
 
 775                                                                 $sSQL .= " from search_name";
 
 776                                                                 $sSQL .= " where ".join(' and ',$aTerms);
 
 777                                                                 $sSQL .= " order by ".join(', ',$aOrder);
 
 778                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
 
 779                                                                         $sSQL .= " limit 50";
 
 780                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
 
 783                                                                         $sSQL .= " limit ".$iLimit;
 
 785                                                                 if (CONST_Debug) var_dump($sSQL);
 
 786                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
 
 787                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
 
 789                                                                         failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
 
 791 //var_dump($aViewBoxPlaceIDs);
 
 792                                                                 // Did we have an viewbox matches?
 
 793                                                                 $aPlaceIDs = array();
 
 794                                                                 $bViewBoxMatch = false;
 
 795                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
 
 797 //                                                                      if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
 
 798 //                                                                      if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
 
 799 //                                                                      if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
 
 800 //                                                                      else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
 
 801                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
 
 804 //var_Dump($aPlaceIDs);
 
 807                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
 
 809                                                                 $aRoadPlaceIDs = $aPlaceIDs;
 
 810                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 812                                                                 // Now they are indexed look for a house attached to a street we found
 
 813                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';                                         
 
 814                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
 
 815                                                                 if (sizeof($aExcludePlaceIDs))
 
 817                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 819                                                                 $sSQL .= " limit $iLimit";
 
 820                                                                 if (CONST_Debug) var_dump($sSQL);
 
 821                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 823                                                                 // If not try the aux fallback table
 
 824                                                                 if (!sizeof($aPlaceIDs))
 
 826                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 827                                                                         if (sizeof($aExcludePlaceIDs))
 
 829                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 831 //                                                                      $sSQL .= " limit $iLimit";
 
 832                                                                         if (CONST_Debug) var_dump($sSQL);
 
 833                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 836                                                                 if (!sizeof($aPlaceIDs))
 
 838                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 839                                                                         if (sizeof($aExcludePlaceIDs))
 
 841                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 843 //                                                                      $sSQL .= " limit $iLimit";
 
 844                                                                         if (CONST_Debug) var_dump($sSQL);
 
 845                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 848                                                                 // Fallback to the road
 
 849                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
 
 851                                                                         $aPlaceIDs = $aRoadPlaceIDs;
 
 856                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
 
 858                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 860                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
 
 862                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
 
 863                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 864                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 865                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
 
 866                                                                         if (CONST_Debug) var_dump($sSQL);
 
 867                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 870                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
 
 872                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 873                                                                         $bCacheTable = $oDB->getOne($sSQL);
 
 875                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
 
 877                                                                         if (CONST_Debug) var_dump($sSQL);
 
 878                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL));
 
 880                                                                         // For state / country level searches the normal radius search doesn't work very well
 
 882                                                                         if ($iMaxRank < 9 && $bCacheTable)
 
 884                                                                                 // Try and get a polygon to search in instead
 
 885         $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";
 
 886         if (CONST_Debug) var_dump($sSQL);
 
 887         $sPlaceGeom = $oDB->getOne($sSQL);
 
 897                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 898                                                                         if (CONST_Debug) var_dump($sSQL);
 
 899                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 900                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
 
 903                                                                         if ($sPlaceIDs || $sPlaceGeom)
 
 909                                                                                 // More efficient - can make the range bigger
 
 913                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
 
 914                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
 
 915                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
 917                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
 
 918                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
 
 921                                                                                         $sSQL .= ",placex as f where ";
 
 922                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
 
 927                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
 
 929                                                                                 if (sizeof($aExcludePlaceIDs))
 
 931                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 933                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
 
 934                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
 935                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
 936                                                                                 $sSQL .= " limit $iLimit";
 
 937                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 938                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 942                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
 
 945                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
 
 946                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
 
 948                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
 
 949                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
 
 950                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
 
 951                                                                                 if (sizeof($aExcludePlaceIDs))
 
 953                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 955                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";                                                           
 
 956                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
 957                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
 958                                                                                 $sSQL .= " limit $iLimit";
 
 959                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 960                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 968                                                 if (PEAR::IsError($aPlaceIDs))
 
 970                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
 
 973                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
 
 975                                                 foreach($aPlaceIDs as $iPlaceID)
 
 977                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
 
 979                                                 if ($iQueryLoop > 20) break;
 
 982                                         if (sizeof($aResultPlaceIDs)) break;
 
 983                                         if ($iGroupLoop > 4) break;
 
 984                                         if ($iQueryLoop > 30) break;
 
 987                                 // Did we find anything?        
 
 988                                 if (sizeof($aResultPlaceIDs))
 
 990 //var_Dump($aResultPlaceIDs);exit;
 
 991                                         // Get the details for display (is this a redundant extra step?)
 
 992                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
 993                                         $sOrderSQL = 'CASE ';
 
 994                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
 996                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
 998                                         $sOrderSQL .= ' ELSE 10000000 END';
 
 999                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
1000                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1001                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
1002                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
1003                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
1004 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1005                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
1006                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
1007                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
1008                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
1009                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1010                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1011                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1012                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1014                                         $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,";
 
1015                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1016                                         $sSQL .= "null as placename,";
 
1017                                         $sSQL .= "null as ref,";
 
1018                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1019 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1020                                         $sSQL .= "-0.15 as importance ";
 
1021                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1022                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1023                                         $sSQL .= "group by place_id";
 
1024                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1026                                         $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,";
 
1027                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1028                                         $sSQL .= "null as placename,";
 
1029                                         $sSQL .= "null as ref,";
 
1030                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1031 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1032                                         $sSQL .= "-0.10 as importance ";
 
1033                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1034                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1035                                         $sSQL .= "group by place_id";
 
1036                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1037                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1038                                         $sSQL .= "order by importance desc";
 
1039 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1040                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1041                                         $aSearchResults = $oDB->getAll($sSQL);
 
1042 //var_dump($sSQL,$aSearchResults);exit;
 
1044                                         if (PEAR::IsError($aSearchResults))
 
1046                                                 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
 
1049                         } // end if ($sQuery)
 
1052                                 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
 
1054                                         $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
 
1055                                         $aResultPlaceIDs = array($iPlaceID);
 
1057                                         // TODO: this needs refactoring!
 
1059                                         // Get the details for display (is this a redundant extra step?)
 
1060                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
1061                                         $sOrderSQL = 'CASE ';
 
1062                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
1064                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
1066                                         $sOrderSQL .= ' ELSE 10000000 END';
 
1067                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
1068                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1069                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
1070                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
1071                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
1072 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1073                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
1074                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
1075                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
1076                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
1077                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1078                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1079                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1080                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1082                                         $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,";
 
1083                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1084                                         $sSQL .= "null as placename,";
 
1085                                         $sSQL .= "null as ref,";
 
1086                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1087 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1088                                         $sSQL .= "-0.15 as importance ";
 
1089                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1090                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1091                                         $sSQL .= "group by place_id";
 
1092                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1094                                         $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,";
 
1095                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1096                                         $sSQL .= "null as placename,";
 
1097                                         $sSQL .= "null as ref,";
 
1098                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1099 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1100                                         $sSQL .= "-0.10 as importance ";
 
1101                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1102                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1103                                         $sSQL .= "group by place_id";
 
1104                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1105                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1106                                         $sSQL .= "order by importance desc";
 
1107 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1108                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1109                                         $aSearchResults = $oDB->getAll($sSQL);
 
1110 //var_dump($sSQL,$aSearchResults);exit;
 
1112                                         if (PEAR::IsError($aSearchResults))
 
1114                         failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
 
1120         $sSearchResult = '';
 
1121         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
 
1123                 $sSearchResult = 'No Results Found';
 
1125 //var_Dump($aSearchResults);
 
1127         $aClassType = getClassTypesWithImportance();
 
1128         foreach($aSearchResults as $iResNum => $aResult)
 
1130                 if (CONST_Search_AreaPolygons || true)
 
1132                         // Get the bounding box and outline polygon
 
1133                         $sSQL = "select place_id,numfeatures,area,outline,";
 
1134                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
 
1135                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
 
1136                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
 
1138                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
 
1139                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
 
1140                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
 
1141                         $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
 
1142                         $aPointPolygon = $oDB->getRow($sSQL);
 
1143                         if (PEAR::IsError($aPointPolygon))
 
1145                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
 
1147                         if ($aPointPolygon['place_id'])
 
1149                                 // Translate geometary string to point array
 
1150                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
 
1152                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
1154                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
 
1157                                         $iSteps = ($fRadius * 40000)^2;
 
1158                                         $fStepSize = (2*pi())/$iSteps;
 
1159                                         $aPolyPoints = array();
 
1160                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1162                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
 
1164                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
 
1165                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
 
1166                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
 
1167                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
 
1170                                 // Output data suitable for display (points and a bounding box)
 
1171                                 if ($bShowPolygons && isset($aPolyPoints))
 
1173                                         $aResult['aPolyPoints'] = array();
 
1174                                         foreach($aPolyPoints as $aPoint)
 
1176                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1179                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1183                 if (!isset($aResult['aBoundingBox']))
 
1186                         $fDiameter = 0.0001;
 
1188                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
 
1189                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
 
1191                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
 
1193                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
 
1194                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
 
1196                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
 
1198                         $fRadius = $fDiameter / 2;
 
1200                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
 
1201                         $fStepSize = (2*pi())/$iSteps;
 
1202                         $aPolyPoints = array();
 
1203                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1205                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
 
1207                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
 
1208                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
 
1209                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
 
1210                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
 
1212                         // Output data suitable for display (points and a bounding box)
 
1215                                 $aResult['aPolyPoints'] = array();
 
1216                                 foreach($aPolyPoints as $aPoint)
 
1218                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1221                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1224                 // Is there an icon set for this type of result?
 
1225                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
 
1226                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1228                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
1231                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) 
 
1232                         && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1234                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
1237                 if ($bShowAddressDetails)
 
1239                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
 
1240 //var_dump($aResult['address']);
 
1244 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
 
1246                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
 
1247                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
 
1249                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
 
1251                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
 
1252                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1254                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1258                         $aResult['importance'] = 1000000000000000;
 
1261                 $aResult['name'] = $aResult['langaddress'];
 
1262                 $aResult['foundorder'] = $iResNum;
 
1263                 $aSearchResults[$iResNum] = $aResult;
 
1266         uasort($aSearchResults, 'byImportance');
 
1268 //var_dump($aSearchResults);exit;
 
1270         $aOSMIDDone = array();
 
1271         $aClassTypeNameDone = array();
 
1272         $aToFilter = $aSearchResults;
 
1273         $aSearchResults = array();
 
1276         foreach($aToFilter as $iResNum => $aResult)
 
1278                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
 
1279                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1282                         $fLat = $aResult['lat'];
 
1283                         $fLon = $aResult['lon'];
 
1284                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1287                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1288                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
 
1290                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1291                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
 
1292                         $aSearchResults[] = $aResult;
 
1295                 // Absolute limit on number of results
 
1296                 if (sizeof($aSearchResults) >= $iLimit) break;
 
1299         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
 
1301         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
1303                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
 
1308                 logEnd($oDB, $hLog, sizeof($aToFilter));
 
1310         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
 
1311         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
 
1312         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
 
1313         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
 
1314         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
 
1315         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
 
1318                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
 
1320         $sMoreURL .= '&q='.urlencode($sQuery);
 
1322         if (CONST_Debug) exit;
 
1324         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');