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         $sSuggestion = $sSuggestionURL = false;
 
  17         $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
 
  18         $bReverseInPlan = false;
 
  19         $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
 
  20         $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
 
  22         if ($iLimit > 100) $iLimit = 100;
 
  25         if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' ||  $_GET['format'] == 'jsonv2'))
 
  27                 $sOutputFormat = $_GET['format'];
 
  30         // Show / use polygons
 
  31         $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
 
  33         // Show address breakdown
 
  34         $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
 
  37         $aLangPrefOrder = getPrefferedLangauges();
 
  38 //      if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
 
  39         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
 
  41         if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
 
  43                 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
 
  45                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
  46                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
  51         $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
 
  52         if (!$sQuery && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
 
  54                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
 
  56                 // reverse order of '/' seperated string
 
  57                 $aPhrases = explode('/', $sQuery);              
 
  58                 $aPhrases = array_reverse($aPhrases); 
 
  59                 $sQuery = join(', ',$aPhrases);
 
  64                 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
 
  66                 // Hack to make it handle "new york, ny" (and variants) correctly
 
  67                 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, new york', $sQuery);
 
  69                 // If we have a view box create the SQL
 
  70                 // Small is the actual view box, Large is double (on each axis) that 
 
  71                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
 
  72                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
 
  74                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
 
  75                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
 
  77                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
 
  79                         $aCoOrdinates = explode(',',$_GET['viewbox']);
 
  80                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
  81                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
 
  82                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
 
  83                         $aCoOrdinates[0] += $fHeight;
 
  84                         $aCoOrdinates[2] -= $fHeight;
 
  85                         $aCoOrdinates[1] += $fWidth;
 
  86                         $aCoOrdinates[3] -= $fWidth;
 
  87                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
 
  89                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
 
  91                         $aPoints = explode(',',$_GET['route']);
 
  92                         if (sizeof($aPoints) % 2 != 0)
 
  94                                 echo "Uneven number of points";
 
  97                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
 
  99                         foreach($aPoints as $i => $fPoint)
 
 103                                         if ($i != 1) $sViewboxCentreSQL .= ",";
 
 104                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
 
 108                                         $fPrevCoord = (float)$fPoint;
 
 111                         $sViewboxCentreSQL .= ")'::geometry,4326)";
 
 113                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
 
 114                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
 
 115                         if (PEAR::isError($sViewboxSmallSQL))
 
 117                                 var_dump($sViewboxSmallSQL);
 
 120                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
 
 122                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
 
 123                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
 
 124                         if (PEAR::isError($sViewboxLargeSQL))
 
 126                                 var_dump($sViewboxLargeSQL);
 
 129                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
 
 132                 // Do we have anything that looks like a lat/lon pair?
 
 133                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
 
 135                         $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
 
 136                         $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
 
 137                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 139                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
 
 141                         $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
 
 142                         $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
 
 143                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 145                 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b])/', $sQuery, $aData))
 
 147                         $_GET['nearlat'] = $aData[2];
 
 148                         $_GET['nearlon'] = $aData[3];
 
 149                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 155                         // Start with a blank search
 
 157                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 
 
 158                                         'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
 
 161                         $sNearPointSQL = false;
 
 162                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
 164                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
 
 165                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
 
 166                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
 
 167                                 $aSearches[0]['fRadius'] = 0.1;
 
 170                         $bSpecialTerms = false;
 
 171                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 172                         $aSpecialTerms = array();
 
 173                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 175                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 176                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
 
 179                         preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 180                         $aSpecialTerms = array();
 
 181                         foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 183                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 184                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
 
 185                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
 
 186                                 $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';
 
 187                                 $aSearchWords = $oDB->getAll($sSQL);
 
 188                                 $aNewSearches = array();
 
 189                                 foreach($aSearches as $aSearch)
 
 191                                         foreach($aSearchWords as $aSearchTerm)
 
 193                                                 $aNewSearch = $aSearch;                 
 
 194                                                 if ($aSearchTerm['country_code'])
 
 196                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 197                                                         $aNewSearches[] = $aNewSearch;
 
 198                                                         $bSpecialTerms = true;
 
 200                                                 if ($aSearchTerm['class'])
 
 202                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
 
 203                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
 
 204                                                         $aNewSearches[] = $aNewSearch;
 
 205                                                         $bSpecialTerms = true;
 
 209                                 $aSearches = $aNewSearches;
 
 212                         // Split query into phrases
 
 213                         // Commas are used to reduce the search space by indicating where phrases split
 
 214                         $aPhrases = explode(',',$sQuery);
 
 216                         // Convert each phrase to standard form
 
 217                         // Create a list of standard words
 
 218                         // Get all 'sets' of words
 
 219                         // Generate a complete list of all 
 
 221                         foreach($aPhrases as $iPhrase => $sPhrase)
 
 223                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
 
 224                                 if (PEAR::isError($aPhrase))
 
 229                                 if (trim($aPhrase['string']))
 
 231                                         $aPhrases[$iPhrase] = $aPhrase;
 
 232                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
 
 233                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
 
 234                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
 238                                         unset($aPhrases[$iPhrase]);
 
 242                         // reindex phrases - we make assumptions later on
 
 243                         $aPhrases = array_values($aPhrases);
 
 245                         if (sizeof($aTokens))
 
 248                         // Check which tokens we have, get the ID numbers                       
 
 249                         $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
 
 250                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
 
 251                         $sSQL .= ' and (class is null or class not in (\'highway\'))';
 
 252 //                      $sSQL .= ' group by word_token, word, class, type, location, country_code';
 
 254                         if (CONST_Debug) var_Dump($sSQL);
 
 256                         $aValidTokens = array();
 
 257                         if (sizeof($aTokens))
 
 258                                 $aDatabaseWords = $oDB->getAll($sSQL);
 
 260                                 $aDatabaseWords = array();
 
 261                         if (PEAR::IsError($aDatabaseWords))
 
 263                                 var_dump($sSQL, $aDatabaseWords);
 
 266                         foreach($aDatabaseWords as $aToken)
 
 268                                 if (isset($aValidTokens[$aToken['word_token']]))
 
 270                                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
 274                                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
 277                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
 279                         $aSuggestion = array();
 
 280                         $bSuggestion = false;
 
 281                         if (CONST_Suggestions_Enabled)
 
 283                                 foreach($aPhrases as $iPhrase => $aPhrase)
 
 285                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
 
 287                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
 
 288                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
 
 289                                                 $aRow = $aSuggestionWords[0];
 
 290                                                 if ($aRow && $aRow['word'])
 
 292                                                         $aSuggestion[] = $aRow['word'];
 
 297                                                         $aSuggestion[] = $aPhrase['string'];
 
 302                                                 $aSuggestion[] = $aPhrase['string'];
 
 306                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
 
 308                         // Try and calculate GB postcodes we might be missing
 
 309                         foreach($aTokens as $sToken)
 
 311                                 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))
 
 313                                         if (substr($aData[1],-2,1) != ' ')
 
 315                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
 
 316                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
 
 318                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
 
 319                                         if ($aGBPostcodeLocation)
 
 321                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
 
 326                         // Any words that have failed completely?
 
 329                         // Start the search process
 
 330                         $aResultPlaceIDs = array();
 
 333                                 Calculate all searches using aValidTokens i.e.
 
 335                                 'Wodsworth Road, Sheffield' =>
 
 339                                 0      1       (wodsworth)(road)
 
 342                                 Score how good the search is so they can be ordered
 
 345                                 foreach($aPhrases as $iPhrase => $sPhrase)
 
 347                                         $aNewPhraseSearches = array();
 
 349                                         foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
 
 351                                                 $aWordsetSearches = $aSearches;
 
 353                                                 // Add all words from this wordset
 
 354                                                 foreach($aWordset as $sToken)
 
 356 //echo "<br><b>$sToken</b>";
 
 357                                                         $aNewWordsetSearches = array();
 
 359                                                         foreach($aWordsetSearches as $aCurrentSearch)
 
 362 //var_dump($aCurrentSearch);
 
 365                                                                 // If the token is valid
 
 366                                                                 if (isset($aValidTokens[' '.$sToken]))
 
 368                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
 
 370                                                                                 $aSearch = $aCurrentSearch;
 
 371                                                                                 $aSearch['iSearchRank']++;
 
 372                                                                                 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
 
 374                                                                                         if ($aSearch['sCountryCode'] === false)
 
 376                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 377                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
 
 378                                                                                                 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
 
 379                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 382                                                                                 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
 
 384                                                                                         if ($aSearch['fLat'] === '')
 
 386                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
 
 387                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
 
 388                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
 
 389                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 392                                                                                 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
 
 394                                                                                         if ($aSearch['sHouseNumber'] === '')
 
 396                                                                                                 $aSearch['sHouseNumber'] = $sToken;
 
 397                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 399                                                                                                 // Fall back to not searching for this item (better than nothing)
 
 400                                                                                                 $aSearch = $aCurrentSearch;
 
 401                                                                                                 $aSearch['iSearchRank'] += 1;
 
 402                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 406                                                                                 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
 
 408                                                                                         if ($aSearch['sClass'] === '')
 
 410                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
 
 411                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
 
 412                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
 
 413                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
 
 414                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
 
 416                                                                                                 // Do we have a shortcut id?
 
 417                                                                                                 if ($aSearch['sOperator'] == 'name')
 
 419                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
 
 420                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
 
 422                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
 
 423                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
 
 424                                                                                                                 $aSearch['sClass'] = '';
 
 425                                                                                                                 $aSearch['sType'] = '';
 
 428                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 433                                                                                         if (sizeof($aSearch['aName']))
 
 435                                                                                                 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4)
 
 437                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 441                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
 
 446                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 447 //                                                                                              $aSearch['iNamePhrase'] = $iPhrase;
 
 449                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 453                                                                 if (isset($aValidTokens[$sToken]) && strlen($sToken) >= 4)
 
 455                                                                         // Allow searching for a word - but at extra cost
 
 456                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
 
 458 //var_Dump('<hr>',$aSearch['aName']);
 
 460                                                                                 if (sizeof($aCurrentSearch['aName']))
 
 462                                                                                 $aSearch = $aCurrentSearch;
 
 463                                                                                         $aSearch['iSearchRank'] += 1;
 
 464                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 465                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 468                                                                                 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
 
 470                                                                                 $aSearch = $aCurrentSearch;
 
 471                                                                                         $aSearch['iSearchRank'] += 4;
 
 472                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 473                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
 
 474                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 480                                                                         // Allow skipping a word - but at EXTREAM cost
 
 481                                                                         //$aSearch = $aCurrentSearch;
 
 482                                                                         //$aSearch['iSearchRank']+=100;
 
 483                                                                         //$aNewWordsetSearches[] = $aSearch;
 
 487                                                         usort($aNewWordsetSearches, 'bySearchRank');
 
 488                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 490 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 492                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 493                                                 usort($aNewPhraseSearches, 'bySearchRank');
 
 494                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 497                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 498                                         $aGroupedSearches = array();
 
 499                                         foreach($aNewPhraseSearches as $aSearch)
 
 501                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 503                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 504                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 507                                         ksort($aGroupedSearches);
 
 510                                         $aSearches = array();
 
 511                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
 
 513                                                 $iSearchCount += sizeof($aNewSearches);
 
 514                                                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 515                                                 if ($iSearchCount > 50) break;
 
 518 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 524                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 525                                         $aGroupedSearches = array();
 
 526                                         foreach($aSearches as $aSearch)
 
 528                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
 
 530                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 531                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 534                                         ksort($aGroupedSearches);
 
 537                                 if (CONST_Debug) var_Dump($aGroupedSearches);
 
 539                                 if ($bReverseInPlan && false)
 
 541                                         foreach($aGroupedSearches as $iGroup => $aSearches)
 
 543                                                 foreach($aSearches as $iSearch => $aSearch)
 
 545                                                         if (sizeof($aSearch['aAddress']))
 
 547                                                                 $aReverseSearch = $aSearch;
 
 548                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
 
 549                                                                 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
 
 550                                                                 $aGroupedSearches[$iGroup][] = $aReverseSearch;
 
 556                                 // Filter out duplicate searches
 
 557                                 $aSearchHash = array();
 
 558                                 foreach($aGroupedSearches as $iGroup => $aSearches)
 
 560                                         foreach($aSearches as $iSearch => $aSearch)
 
 562                                                 $sHash = serialize($aSearch);
 
 563                                                 if (isset($aSearchHash[$sHash]))
 
 565                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
 566                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
 570                                                         $aSearchHash[$sHash] = 1;
 
 575                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 579                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
 
 582                                         foreach($aSearches as $aSearch)
 
 586                                                 // Must have a location term
 
 587                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
 
 589                                                         if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
 
 590                                                         if (!$aSearch['sClass']) continue;
 
 591                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 592                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 594                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 595                                                         if ($oDB->getOne($sSQL))
 
 597                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
 
 598                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
 
 599                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 600                                                                 $sSQL .= " limit $iLimit";
 
 601                                                                 if (CONST_Debug) var_dump($sSQL);
 
 602                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 604                                                                 if (!sizeof($aPlaceIDs))
 
 606                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
 
 607                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
 
 608                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 609                                                                         $sSQL .= " limit $iLimit";
 
 610                                                                         if (CONST_Debug) var_dump($sSQL);
 
 611                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 616                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 617                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
 
 618                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
 619                                                                 $sSQL .= " limit $iLimit";
 
 620                                                                 if (CONST_Debug) var_dump($sSQL);
 
 621                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 626                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
 
 627                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
 
 628                                                         $aPlaceIDs = array();
 
 630                                                         // First we need a position, either aName or fLat or both
 
 633                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
 
 634                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
 
 635                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
 
 636                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
 
 637                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
 
 639                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
 
 640                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
 
 642                                                         if (sizeof($aExcludePlaceIDs))
 
 644                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 646                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
 
 647                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
 
 648                                                         if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
 
 649                                                         if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
 
 650                                                         $aOrder[] = "search_rank ASC";
 
 654                                                                 $sSQL = "select place_id";
 
 655                                                                 if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
 
 656                                                                 else $sSQL .= ",false as in_small";
 
 657                                                                 if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
 
 658                                                                 else $sSQL .= ",false as in_large";
 
 659                                                                 $sSQL .= " from search_name";
 
 660                                                                 $sSQL .= " where ".join(' and ',$aTerms);
 
 661                                                                 $sSQL .= " order by ".join(', ',$aOrder);
 
 662                                                                 if ($aSearch['sHouseNumber'])
 
 663                                                                         $sSQL .= " limit 50";
 
 664                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
 
 667                                                                         $sSQL .= " limit ".$iLimit;
 
 669                                                                 if (CONST_Debug) var_dump($sSQL);
 
 670                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
 
 671                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
 
 673                                                                         var_dump($sSQL, $aViewBoxPlaceIDs);                                     
 
 677                                                                 // Did we have an viewbox matches?
 
 678                                                                 $aPlaceIDs = array();
 
 679                                                                 $bViewBoxMatch = false;
 
 680                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
 
 682                                                                         if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
 
 683                                                                         if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
 
 684                                                                         if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
 
 685                                                                         else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
 
 686                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
 
 690                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
 
 692                                                                 $aRoadPlaceIDs = $aPlaceIDs;
 
 693                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 695                                                                 // Now they are indexed look for a house attached to a street we found
 
 696                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';                                         
 
 697                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
 
 698                                                                 if (sizeof($aExcludePlaceIDs))
 
 700                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 702                                                                 $sSQL .= " limit $iLimit";
 
 703                                                                 if (CONST_Debug) var_dump($sSQL);
 
 704                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 706                                                                 // If not try the aux fallback table
 
 707                                                                 if (!sizeof($aPlaceIDs))
 
 709                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 710                                                                         if (sizeof($aExcludePlaceIDs))
 
 712                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 714 //                                                                      $sSQL .= " limit $iLimit";
 
 715                                                                         if (CONST_Debug) var_dump($sSQL);
 
 716                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 719                                                                 if (!sizeof($aPlaceIDs))
 
 721                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
 722                                                                         if (sizeof($aExcludePlaceIDs))
 
 724                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 726 //                                                                      $sSQL .= " limit $iLimit";
 
 727                                                                         if (CONST_Debug) var_dump($sSQL);
 
 728                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 731                                                                 // Fallback to the road
 
 732                                                                 if (!sizeof($aPlaceIDs))
 
 734                                                                         $aPlaceIDs = $aRoadPlaceIDs;
 
 739                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
 
 741                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
 743                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
 
 745                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
 
 746                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
 747                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
 
 748                                                                         if (CONST_Debug) var_dump($sSQL);
 
 749                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 752                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
 
 754                                                                         $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
 
 755                                                                         if (CONST_Debug) var_dump($sSQL);
 
 756                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
 
 758                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 759                                                                         if (CONST_Debug) var_dump($sSQL);
 
 760                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
 
 761                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
 
 764                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
 765                                                                         if ($oDB->getOne($sSQL))
 
 767                                                                                 // More efficient - can make the range bigger
 
 769                                                                                 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
 
 770                                                                                 $sSQL .= ",placex as f where ";
 
 771                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
 
 772                                                                                 if (sizeof($aExcludePlaceIDs))
 
 774                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 776                                                                                 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.centroid) ASC";
 
 777                                                                                 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
 
 778                                                                                 $sSQL .= " limit $iLimit";
 
 779                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 780                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 784                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
 
 785                                                                                 $sSQL = "select l.place_id from placex as l,placex as f where ";
 
 786                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
 
 787                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
 
 788                                                                                 if (sizeof($aExcludePlaceIDs))
 
 790                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
 
 792                                                                                 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
 
 793                                                                                 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
 
 794                                                                                 $sSQL .= " limit $iLimit";
 
 795                                                                                 if (CONST_Debug) var_dump($sSQL);
 
 796                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 803                                                 if (PEAR::IsError($aPlaceIDs))
 
 805                                                         var_dump($sSQL, $aPlaceIDs);                                    
 
 809                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
 
 811                                                 foreach($aPlaceIDs as $iPlaceID)
 
 813                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
 
 815                                                 if ($iQueryLoop > 20) break;
 
 818                                         if (sizeof($aResultPlaceIDs)) break;
 
 819                                         if ($iGroupLoop > 4) break;
 
 820                                         if ($iQueryLoop > 30) break;
 
 823                                 // Did we find anything?        
 
 824                                 if (sizeof($aResultPlaceIDs))
 
 826 //var_Dump($aResultPlaceIDs);exit;
 
 827                                         // Get the details for display (is this a redundant extra step?)
 
 828                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
 
 829                                         $sOrderSQL = 'CASE ';
 
 830                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
 
 832                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
 
 834                                         $sOrderSQL .= ' ELSE 10000000 END';
 
 835                                         $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
 
 836                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
 837                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
 838                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
 839                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
 
 840                                         $sSQL .= $sOrderSQL." as porder ";
 
 841                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
 842                                         $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
 
 843                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
 844                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
 845                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
 
 846                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
 
 848                                         $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
 849                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
 850                                         $sSQL .= "null as placename,";
 
 851                                         $sSQL .= "null as ref,";
 
 852                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
 853                                         $sSQL .= $sOrderSQL." as porder ";
 
 854                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
 855                                         $sSQL .= "group by place_id";
 
 856                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
 858                                         $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
 
 859                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
 860                                         $sSQL .= "null as placename,";
 
 861                                         $sSQL .= "null as ref,";
 
 862                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
 863                                         $sSQL .= $sOrderSQL." as porder ";
 
 864                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
 865                                         $sSQL .= "group by place_id";
 
 866                                         if (!$bDeDupe) $sSQL .= ",place_id";
 
 867                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
 868                                         $sSQL .= "order by rank_search,rank_address,porder asc";
 
 869                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
 
 870                                         $aSearchResults = $oDB->getAll($sSQL);
 
 871 //var_dump($sSQL,$aSearchResults);exit;
 
 873                                         if (PEAR::IsError($aSearchResults))
 
 875                                                 var_dump($sSQL, $aSearchResults);                                       
 
 883         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
 
 885                 $sSearchResult = 'No Results Found';
 
 888         $aClassType = getClassTypesWithImportance();
 
 890         foreach($aSearchResults as $iResNum => $aResult)
 
 892                 if (CONST_Search_AreaPolygons || true)
 
 894                         // Get the bounding box and outline polygon
 
 895                         $sSQL = "select place_id,numfeatures,area,outline,";
 
 896                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
 
 897                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
 
 898                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
 
 900                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
 
 901                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
 
 902                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
 
 903                         $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
 
 904                         $aPointPolygon = $oDB->getRow($sSQL);
 
 905                         if (PEAR::IsError($aPointPolygon))
 
 907                                 var_dump($sSQL, $aPointPolygon);
 
 910                         if ($aPointPolygon['place_id'])
 
 912                                 // Translate geometary string to point array
 
 913                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
 
 915                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
 917                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
 
 920                                         $iSteps = ($fRadius * 40000)^2;
 
 921                                         $fStepSize = (2*pi())/$iSteps;
 
 922                                         $aPolyPoints = array();
 
 923                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
 925                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
 
 927                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
 
 928                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
 
 929                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
 
 930                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
 
 933                                 // Output data suitable for display (points and a bounding box)
 
 936                                         $aResult['aPolyPoints'] = array();
 
 937                                         foreach($aPolyPoints as $aPoint)
 
 939                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
 942                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
 946                 if (!isset($aResult['aBoundingBox']))
 
 951                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
 
 952                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
 
 954                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
 
 956                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
 
 957                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
 
 959                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
 
 961                         $fRadius = $fDiameter / 2;
 
 963                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
 
 964                         $fStepSize = (2*pi())/$iSteps;
 
 965                         $aPolyPoints = array();
 
 966                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
 968                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
 
 970                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
 
 971                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
 
 972                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
 
 973                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
 
 975                         // Output data suitable for display (points and a bounding box)
 
 978                                 $aResult['aPolyPoints'] = array();
 
 979                                 foreach($aPolyPoints as $aPoint)
 
 981                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
 984                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
 987                 // Is there an icon set for this type of result?
 
 988                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
 
 989                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
 991                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
 994                 if ($bShowAddressDetails)
 
 996                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
 
 997 //var_dump($aResult['address']);
 
1001                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
 
1002                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1004                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1008                         $aResult['importance'] = 1000000000000000;
 
1011                 $aResult['name'] = $aResult['langaddress'];
 
1012                 $aResult['foundorder'] = $iResNum;
 
1013                 $aSearchResults[$iResNum] = $aResult;
 
1016 //var_dump($aSearchResults);exit;
 
1018         uasort($aSearchResults, 'byImportance');
 
1020         $aOSMIDDone = array();
 
1021         $aClassTypeNameDone = array();
 
1022         $aToFilter = $aSearchResults;
 
1023         $aSearchResults = array();
 
1026         foreach($aToFilter as $iResNum => $aResult)
 
1028                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
 
1029                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1032                         $fLat = $aResult['lat'];
 
1033                         $fLon = $aResult['lon'];
 
1034                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1037                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1038                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
 
1040                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1041                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
 
1042                         $aSearchResults[] = $aResult;
 
1046         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
 
1048         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
 
1050                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
 
1055                 logEnd($oDB, $hLog, sizeof($aToFilter));
 
1057         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
 
1058         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
 
1059         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
 
1060         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
 
1061         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
 
1062         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
 
1065                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
 
1067         $sMoreURL .= '&q='.urlencode($sQuery);
 
1069         if (CONST_Debug) exit;
 
1071         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');