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                                 var_dump($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                                 var_dump($sViewboxLargeSQL);
 
 178                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
 
 181                 // Do we have anything that looks like a lat/lon pair?
 
 182                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
 
 184                         $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
 
 185                         $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
 
 186                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 188                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
 
 190                         $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
 
 191                         $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
 
 192                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 194                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
 
 196                         $_GET['nearlat'] = $aData[2];
 
 197                         $_GET['nearlon'] = $aData[3];
 
 198                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 203                         // Start with a blank search
 
 205                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 
 
 206                                         'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
 
 209                         $sNearPointSQL = false;
 
 210                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
 212                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
 
 213                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
 
 214                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
 
 215                                 $aSearches[0]['fRadius'] = 0.1;
 
 218                         $bSpecialTerms = false;
 
 219                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 220                         $aSpecialTerms = array();
 
 221                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 223                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 224                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
 
 227                         preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 228                         $aSpecialTerms = array();
 
 229                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 231                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 232                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
 
 233                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
 
 234                                 $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';
 
 235                                 $aSearchWords = $oDB->getAll($sSQL);
 
 236                                 $aNewSearches = array();
 
 237                                 foreach($aSearches as $aSearch)
 
 239                                         foreach($aSearchWords as $aSearchTerm)
 
 241                                                 $aNewSearch = $aSearch;                 
 
 242                                                 if ($aSearchTerm['country_code'])
 
 244                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 245                                                         $aNewSearches[] = $aNewSearch;
 
 246                                                         $bSpecialTerms = true;
 
 248                                                 if ($aSearchTerm['class'])
 
 250                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
 
 251                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
 
 252                                                         $aNewSearches[] = $aNewSearch;
 
 253                                                         $bSpecialTerms = true;
 
 257                                 $aSearches = $aNewSearches;
 
 260                         // Split query into phrases
 
 261                         // Commas are used to reduce the search space by indicating where phrases split
 
 262                         $aPhrases = explode(',',$sQuery);
 
 264                         // Convert each phrase to standard form
 
 265                         // Create a list of standard words
 
 266                         // Get all 'sets' of words
 
 267                         // Generate a complete list of all 
 
 269                         foreach($aPhrases as $iPhrase => $sPhrase)
 
 271                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
 
 272                                 if (PEAR::isError($aPhrase))
 
 277                                 if (trim($aPhrase['string']))
 
 279                                         $aPhrases[$iPhrase] = $aPhrase;
 
 280                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
 
 281                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
 
 282                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
 286                                         unset($aPhrases[$iPhrase]);
 
 290                         // reindex phrases - we make assumptions later on
 
 291                         $aPhrases = array_values($aPhrases);
 
 293                         if (sizeof($aTokens))
 
 296                         // Check which tokens we have, get the ID numbers                       
 
 297                         $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
 
 298                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
 
 299                         $sSQL .= ' and (class is null or class not in (\'highway\'))';
 
 300 //                      $sSQL .= ' group by word_token, word, class, type, location, country_code';
 
 302                         if (CONST_Debug) var_Dump($sSQL);
 
 304                         $aValidTokens = array();
 
 305                         if (sizeof($aTokens))
 
 306                                 $aDatabaseWords = $oDB->getAll($sSQL);
 
 308                                 $aDatabaseWords = array();
 
 309                         if (PEAR::IsError($aDatabaseWords))
 
 311                                 var_dump($sSQL, $aDatabaseWords);
 
 314                         $aPossibleMainWordIDs = array();
 
 315                         foreach($aDatabaseWords as $aToken)
 
 317                                 if (isset($aValidTokens[$aToken['word_token']]))
 
 319                                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
 323                                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
 325                                 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
 
 327                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
 329                         $aSuggestion = array();
 
 330                         $bSuggestion = false;
 
 331                         if (CONST_Suggestions_Enabled)
 
 333                                 foreach($aPhrases as $iPhrase => $aPhrase)
 
 335                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
 
 337                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
 
 338                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
 
 339                                                 $aRow = $aSuggestionWords[0];
 
 340                                                 if ($aRow && $aRow['word'])
 
 342                                                         $aSuggestion[] = $aRow['word'];
 
 347                                                         $aSuggestion[] = $aPhrase['string'];
 
 352                                                 $aSuggestion[] = $aPhrase['string'];
 
 356                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
 
 358                         // Try and calculate GB postcodes we might be missing
 
 359                         foreach($aTokens as $sToken)
 
 361                                 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))
 
 363                                         if (substr($aData[1],-2,1) != ' ')
 
 365                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
 
 366                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
 
 368                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
 
 369                                         if ($aGBPostcodeLocation)
 
 371                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
 
 376                         foreach($aTokens as $sToken)
 
 378                                 // Unknown single word token with a number - assume it is a house number
 
 379                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
 
 381                                         $aValidTokens[' '.$sToken] = array('class'=>'place','type'=>'house');
 
 385                         // Any words that have failed completely?
 
 388                         // Start the search process
 
 389                         $aResultPlaceIDs = array();
 
 392                                 Calculate all searches using aValidTokens i.e.
 
 394                                 'Wodsworth Road, Sheffield' =>
 
 398                                 0      1       (wodsworth)(road)
 
 401                                 Score how good the search is so they can be ordered
 
 404                                 foreach($aPhrases as $iPhrase => $sPhrase)
 
 406                                         $aNewPhraseSearches = array();
 
 408                                         foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
 
 410                                                 $aWordsetSearches = $aSearches;
 
 412                                                 // Add all words from this wordset
 
 413                                                 foreach($aWordset as $sToken)
 
 415 //echo "<br><b>$sToken</b>";
 
 416                                                         $aNewWordsetSearches = array();
 
 418                                                         foreach($aWordsetSearches as $aCurrentSearch)
 
 421 //var_dump($aCurrentSearch);
 
 424                                                                 // If the token is valid
 
 425                                                                 if (isset($aValidTokens[' '.$sToken]))
 
 427                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
 
 429                                                                                 $aSearch = $aCurrentSearch;
 
 430                                                                                 $aSearch['iSearchRank']++;
 
 431                                                                                 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
 
 433                                                                                         if ($aSearch['sCountryCode'] === false)
 
 435                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 436                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
 
 437                                                                                                 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
 
 438                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 441                                                                                 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
 
 443                                                                                         if ($aSearch['fLat'] === '')
 
 445                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
 
 446                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
 
 447                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
 
 448                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 451                                                                                 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
 
 453                                                                                         if ($aSearch['sHouseNumber'] === '')
 
 455                                                                                                 $aSearch['sHouseNumber'] = $sToken;
 
 456                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 458                                                                                                 // Fall back to not searching for this item (better than nothing)
 
 459                                                                                                 $aSearch = $aCurrentSearch;
 
 460                                                                                                 $aSearch['iSearchRank'] += 1;
 
 461                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 465                                                                                 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
 
 467                                                                                         if ($aSearch['sClass'] === '')
 
 469                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
 
 470                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
 
 471                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
 
 472                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
 
 473                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
 
 475                                                                                                 // Do we have a shortcut id?
 
 476                                                                                                 if ($aSearch['sOperator'] == 'name')
 
 478                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
 
 479                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
 
 481                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
 
 482                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
 
 483                                                                                                                 $aSearch['sClass'] = '';
 
 484                                                                                                                 $aSearch['sType'] = '';
 
 487                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 492                                                                                         if (sizeof($aSearch['aName']))
 
 494                                                                                                 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
 
 496                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 500                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
 
 505                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 506 //                                                                                              $aSearch['iNamePhrase'] = $iPhrase;
 
 508                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 512                                                                 if (isset($aValidTokens[$sToken]))
 
 514                                                                         // Allow searching for a word - but at extra cost
 
 515                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
 
 517 //var_Dump('<hr>',$aSearch['aName']);
 
 519                                                                                 if (sizeof($aCurrentSearch['aName'])  && strlen($sToken) >= 4)
 
 521                                                                                 $aSearch = $aCurrentSearch;
 
 522                                                                                         $aSearch['iSearchRank'] += 1;
 
 523                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 524                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 527                                                                                 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
 
 529                                                                                 $aSearch = $aCurrentSearch;
 
 530                                                                                         $aSearch['iSearchRank'] += 2;
 
 531                                                                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
 
 532                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 533                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
 
 534                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 540                                                                         // Allow skipping a word - but at EXTREAM cost
 
 541                                                                         //$aSearch = $aCurrentSearch;
 
 542                                                                         //$aSearch['iSearchRank']+=100;
 
 543                                                                         //$aNewWordsetSearches[] = $aSearch;
 
 547                                                         usort($aNewWordsetSearches, 'bySearchRank');
 
 548                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 550 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 552                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 553                                                 usort($aNewPhraseSearches, 'bySearchRank');
 
 555           $aSearchHash = array();
 
 556           foreach($aNewPhraseSearches as $iSearch => $aSearch)
 
 558             $sHash = serialize($aSearch);
 
 559             if (isset($aSearchHash[$sHash]))
 
 561               unset($aNewPhraseSearches[$iSearch]);
 
 565               $aSearchHash[$sHash] = 1;
 
 569                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 572                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 573                                         $aGroupedSearches = array();
 
 574                                         foreach($aNewPhraseSearches as $aSearch)
 
 576                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 578                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 579                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 582                                         ksort($aGroupedSearches);
 
 585                                         $aSearches = array();
 
 586                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
 
 588                                                 $iSearchCount += sizeof($aNewSearches);
 
 589                                                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 590                                                 if ($iSearchCount > 50) break;
 
 593 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 599                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 600                                         $aGroupedSearches = array();
 
 601                                         foreach($aSearches as $aSearch)
 
 603                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 605                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 606                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 609                                         ksort($aGroupedSearches);
 
 612                                 if (CONST_Debug) var_Dump($aGroupedSearches);
 
 616                                         $aCopyGroupedSearches = $aGroupedSearches;
 
 617                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
 
 619                                                 foreach($aSearches as $iSearch => $aSearch)
 
 621                                                         if (sizeof($aSearch['aAddress']))
 
 623                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
 
 624                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
 
 626                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
 
 627                                                                         $aSearch['aName'] = array($iReverseItem);
 
 628                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
 
 630 //                                                              $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
 
 631         //                                                      $aGroupedSearches[$iGroup][] = $aReverseSearch;
 
 637                                 // Filter out duplicate searches
 
 638                                 $aSearchHash = array();
 
 639                                 foreach($aGroupedSearches as $iGroup => $aSearches)
 
 641                                         foreach($aSearches as $iSearch => $aSearch)
 
 643                                                 $sHash = serialize($aSearch);
 
 644                                                 if (isset($aSearchHash[$sHash]))
 
 646                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
 647                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
 651                                                         $aSearchHash[$sHash] = 1;
 
 656                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 660                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
 
 663                                         foreach($aSearches as $aSearch)
 
 667                                                 // Must have a location term
 
 668                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
 
 670                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
 
 672                                                                 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
 
 674                                                                         $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
 
 675                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 676                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
 
 677                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 682                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
 
 683                                                                 if (!$aSearch['sClass']) continue;
 
 684                                                                 if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 685                                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 687                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 688                                                                 if ($oDB->getOne($sSQL))
 
 690                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
 
 691                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 692                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
 
 693                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 694                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 695                                                                 $sSQL .= " limit $iLimit";
 
 696                                                                 if (CONST_Debug) var_dump($sSQL);
 
 697                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 699                                                                 if (!sizeof($aPlaceIDs))
 
 701                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
 
 702                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
 703                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
 
 704                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 705                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 706                                                                         $sSQL .= " limit $iLimit";
 
 707                                                                         if (CONST_Debug) var_dump($sSQL);
 
 708                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 713                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 714                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
 
 715                                                                 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 716                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 717                                                                 $sSQL .= " limit $iLimit";
 
 718                                                                 if (CONST_Debug) var_dump($sSQL);
 
 719                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 725                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 726                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 727                                                         $aPlaceIDs = array();
 
 729                                                         // First we need a position, either aName or fLat or both
 
 732                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
 
 733                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
 
 734                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
 
 735                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
 
 736                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
 
 738                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
 
 739                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
 
 741                                                         if (sizeof($aExcludePlaceIDs))
 
 743                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 745                                                         if ($sCountryCodesSQL)
 
 747                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
 
 750                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
 
 751                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
 
 753                                                         $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
 
 755                                                         if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
 
 756                                                         if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
 
 757                                                         $aOrder[] = "$sImportanceSQL DESC";
 
 761                                                                 $sSQL = "select place_id";
 
 762                                                                 $sSQL .= " from search_name";
 
 763                                                                 $sSQL .= " where ".join(' and ',$aTerms);
 
 764                                                                 $sSQL .= " order by ".join(', ',$aOrder);
 
 765                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
 
 766                                                                         $sSQL .= " limit 50";
 
 767                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
 
 770                                                                         $sSQL .= " limit ".$iLimit;
 
 772                                                                 if (CONST_Debug) var_dump($sSQL);
 
 773                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
 
 774                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
 
 776                                                                         var_dump($sSQL, $aViewBoxPlaceIDs);                                     
 
 779 //var_dump($aViewBoxPlaceIDs);
 
 780                                                                 // Did we have an viewbox matches?
 
 781                                                                 $aPlaceIDs = array();
 
 782                                                                 $bViewBoxMatch = false;
 
 783                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
 
 785 //                                                                      if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
 
 786 //                                                                      if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
 
 787 //                                                                      if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
 
 788 //                                                                      else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
 
 789                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
 
 792 //var_Dump($aPlaceIDs);
 
 795                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
 
 797                                                                 $aRoadPlaceIDs = $aPlaceIDs;
 
 798                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 800                                                                 // Now they are indexed look for a house attached to a street we found
 
 801                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';                                         
 
 802                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
 
 803                                                                 if (sizeof($aExcludePlaceIDs))
 
 805                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 807                                                                 $sSQL .= " limit $iLimit";
 
 808                                                                 if (CONST_Debug) var_dump($sSQL);
 
 809                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 811                                                                 // If not try the aux fallback table
 
 812                                                                 if (!sizeof($aPlaceIDs))
 
 814                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 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);
 
 824                                                                 if (!sizeof($aPlaceIDs))
 
 826                                                                         $sSQL = "select place_id from location_property_tiger 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                                                                 // Fallback to the road
 
 837                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
 
 839                                                                         $aPlaceIDs = $aRoadPlaceIDs;
 
 844                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
 
 846                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 848                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
 
 850                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
 
 851                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 852                                                                         if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";                                                             
 
 853                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
 
 854                                                                         if (CONST_Debug) var_dump($sSQL);
 
 855                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 858                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
 
 860                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 861                                                                         $bCacheTable = $oDB->getOne($sSQL);
 
 863                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
 
 865                                                                         if (CONST_Debug) var_dump($sSQL);
 
 866                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL));
 
 868                                                                         // For state / country level searches the normal radius search doesn't work very well
 
 870                                                                         if ($iMaxRank < 9 && $bCacheTable)
 
 872                                                                                 // Try and get a polygon to search in instead
 
 873         $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";
 
 874         if (CONST_Debug) var_dump($sSQL);
 
 875         $sPlaceGeom = $oDB->getOne($sSQL);
 
 885                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 886                                                                         if (CONST_Debug) var_dump($sSQL);
 
 887                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 888                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
 
 891                                                                         if ($sPlaceIDs || $sPlaceGeom)
 
 897                                                                                 // More efficient - can make the range bigger
 
 901                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
 
 902                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
 
 903                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
 905                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
 
 906                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
 
 909                                                                                         $sSQL .= ",placex as f where ";
 
 910                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
 
 915                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
 
 917                                                                                 if (sizeof($aExcludePlaceIDs))
 
 919                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 921                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
 
 922                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
 923                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
 924                                                                                 $sSQL .= " limit $iLimit";
 
 925                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 926                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 930                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
 
 933                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
 
 934                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
 
 936                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
 
 937                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
 
 938                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
 
 939                                                                                 if (sizeof($aExcludePlaceIDs))
 
 941                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 943                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";                                                           
 
 944                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
 945                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
 
 946                                                                                 $sSQL .= " limit $iLimit";
 
 947                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 948                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 956                                                 if (PEAR::IsError($aPlaceIDs))
 
 958                                                         var_dump($sSQL, $aPlaceIDs);                                    
 
 962                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
 
 964                                                 foreach($aPlaceIDs as $iPlaceID)
 
 966                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
 
 968                                                 if ($iQueryLoop > 20) break;
 
 971                                         if (sizeof($aResultPlaceIDs)) break;
 
 972                                         if ($iGroupLoop > 4) break;
 
 973                                         if ($iQueryLoop > 30) break;
 
 976                                 // Did we find anything?        
 
 977                                 if (sizeof($aResultPlaceIDs))
 
 979 //var_Dump($aResultPlaceIDs);exit;
 
 980                                         // Get the details for display (is this a redundant extra step?)
 
 981                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
 982                                         $sOrderSQL = 'CASE ';
 
 983                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
 985                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
 987                                         $sOrderSQL .= ' ELSE 10000000 END';
 
 988                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
 989                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
 990                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
 991                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
 992                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
 993 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
 994                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
 995                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
 996                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
 997                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
 998                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
 999                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1000                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1001                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1003                                         $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,";
 
1004                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1005                                         $sSQL .= "null as placename,";
 
1006                                         $sSQL .= "null as ref,";
 
1007                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1008 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1009                                         $sSQL .= "-0.15 as importance ";
 
1010                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1011                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1012                                         $sSQL .= "group by place_id";
 
1013                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1015                                         $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,";
 
1016                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1017                                         $sSQL .= "null as placename,";
 
1018                                         $sSQL .= "null as ref,";
 
1019                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1020 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1021                                         $sSQL .= "-0.10 as importance ";
 
1022                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1023                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1024                                         $sSQL .= "group by place_id";
 
1025                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1026                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1027                                         $sSQL .= "order by importance desc";
 
1028 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1029                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1030                                         $aSearchResults = $oDB->getAll($sSQL);
 
1031 //var_dump($sSQL,$aSearchResults);exit;
 
1033                                         if (PEAR::IsError($aSearchResults))
 
1035                                                 var_dump($sSQL, $aSearchResults);                                       
 
1039                         } // end if ($sQuery)
 
1042                                 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
 
1044                                         $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
 
1045                                         $aResultPlaceIDs = array($iPlaceID);
 
1047                                         // TODO: this needs refactoring!
 
1049                                         // Get the details for display (is this a redundant extra step?)
 
1050                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
1051                                         $sOrderSQL = 'CASE ';
 
1052                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
1054                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
1056                                         $sOrderSQL .= ' ELSE 10000000 END';
 
1057                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
1058                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1059                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
1060                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
1061                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
1062 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1063                                         $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
 
1064                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
1065                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
 
1066                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
 
1067                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1068                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1069                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
1070                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
1072                                         $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
1073                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1074                                         $sSQL .= "null as placename,";
 
1075                                         $sSQL .= "null as ref,";
 
1076                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1077 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1078                                         $sSQL .= "-0.15 as importance ";
 
1079                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
1080                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1081                                         $sSQL .= "group by place_id";
 
1082                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1084                                         $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
1085                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
1086                                         $sSQL .= "null as placename,";
 
1087                                         $sSQL .= "null as ref,";
 
1088                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
1089 //                                      $sSQL .= $sOrderSQL." as porder, ";
 
1090                                         $sSQL .= "-0.10 as importance ";
 
1091                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
1092                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
 
1093                                         $sSQL .= "group by place_id";
 
1094                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
1095                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
1096                                         $sSQL .= "order by importance desc";
 
1097 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
 
1098                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
1099                                         $aSearchResults = $oDB->getAll($sSQL);
 
1100 //var_dump($sSQL,$aSearchResults);exit;
 
1102                                         if (PEAR::IsError($aSearchResults))
 
1104                                                 var_dump($sSQL, $aSearchResults);                                       
 
1111         $sSearchResult = '';
 
1112         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
 
1114                 $sSearchResult = 'No Results Found';
 
1116 //var_Dump($aSearchResults);
 
1118         $aClassType = getClassTypesWithImportance();
 
1119         foreach($aSearchResults as $iResNum => $aResult)
 
1121                 if (CONST_Search_AreaPolygons || true)
 
1123                         // Get the bounding box and outline polygon
 
1124                         $sSQL = "select place_id,numfeatures,area,outline,";
 
1125                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
 
1126                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
 
1127                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
 
1129                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
 
1130                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
 
1131                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
 
1132                         $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
 
1133                         $aPointPolygon = $oDB->getRow($sSQL);
 
1134                         if (PEAR::IsError($aPointPolygon))
 
1136                                 var_dump($sSQL, $aPointPolygon);
 
1139                         if ($aPointPolygon['place_id'])
 
1141                                 // Translate geometary string to point array
 
1142                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
 
1144                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
1146                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
 
1149                                         $iSteps = ($fRadius * 40000)^2;
 
1150                                         $fStepSize = (2*pi())/$iSteps;
 
1151                                         $aPolyPoints = array();
 
1152                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1154                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
 
1156                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
 
1157                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
 
1158                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
 
1159                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
 
1162                                 // Output data suitable for display (points and a bounding box)
 
1163                                 if ($bShowPolygons && isset($aPolyPoints))
 
1165                                         $aResult['aPolyPoints'] = array();
 
1166                                         foreach($aPolyPoints as $aPoint)
 
1168                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1171                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1175                 if (!isset($aResult['aBoundingBox']))
 
1178                         $fDiameter = 0.0001;
 
1180                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
 
1181                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
 
1183                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
 
1185                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
 
1186                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
 
1188                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
 
1190                         $fRadius = $fDiameter / 2;
 
1192                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
 
1193                         $fStepSize = (2*pi())/$iSteps;
 
1194                         $aPolyPoints = array();
 
1195                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1197                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
 
1199                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
 
1200                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
 
1201                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
 
1202                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
 
1204                         // Output data suitable for display (points and a bounding box)
 
1207                                 $aResult['aPolyPoints'] = array();
 
1208                                 foreach($aPolyPoints as $aPoint)
 
1210                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1213                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1216                 // Is there an icon set for this type of result?
 
1217                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
 
1218                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1220                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
1223                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) 
 
1224                         && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1226                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
1229                 if ($bShowAddressDetails)
 
1231                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
 
1232 //var_dump($aResult['address']);
 
1236 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
 
1238                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
 
1239                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
 
1241                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
 
1243                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
 
1244                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1246                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1250                         $aResult['importance'] = 1000000000000000;
 
1253                 $aResult['name'] = $aResult['langaddress'];
 
1254                 $aResult['foundorder'] = $iResNum;
 
1255                 $aSearchResults[$iResNum] = $aResult;
 
1258         uasort($aSearchResults, 'byImportance');
 
1260 //var_dump($aSearchResults);exit;
 
1262         $aOSMIDDone = array();
 
1263         $aClassTypeNameDone = array();
 
1264         $aToFilter = $aSearchResults;
 
1265         $aSearchResults = array();
 
1268         foreach($aToFilter as $iResNum => $aResult)
 
1270                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
 
1271                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1274                         $fLat = $aResult['lat'];
 
1275                         $fLon = $aResult['lon'];
 
1276                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1279                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1280                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
 
1282                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1283                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
 
1284                         $aSearchResults[] = $aResult;
 
1287                 // Absolute limit on number of results
 
1288                 if (sizeof($aSearchResults) >= $iLimit) break;
 
1291         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
 
1293         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
1295                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
 
1300                 logEnd($oDB, $hLog, sizeof($aToFilter));
 
1302         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
 
1303         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
 
1304         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
 
1305         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
 
1306         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
 
1307         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
 
1310                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
 
1312         $sMoreURL .= '&q='.urlencode($sQuery);
 
1314         if (CONST_Debug) exit;
 
1316         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');