6                 protected $aLangPrefOrder = array();
 
   8                 protected $bIncludeAddressDetails = false;
 
  10                 protected $bIncludePolygonAsPoints = false;
 
  11                 protected $bIncludePolygonAsText = false;
 
  12                 protected $bIncludePolygonAsGeoJSON = false;
 
  13                 protected $bIncludePolygonAsKML = false;
 
  14                 protected $bIncludePolygonAsSVG = false;
 
  16                 protected $aExcludePlaceIDs = array();
 
  17                 protected $bDeDupe = true;
 
  18                 protected $bReverseInPlan = false;
 
  20                 protected $iLimit = 20;
 
  21                 protected $iFinalLimit = 10;
 
  22                 protected $iOffset = 0;
 
  23                 protected $bFallback = false;
 
  25                 protected $aCountryCodes = false;
 
  26                 protected $aNearPoint = false;
 
  28                 protected $bBoundedSearch = false;
 
  29                 protected $aViewBox = false;
 
  30                 protected $sViewboxSmallSQL = false;
 
  31                 protected $sViewboxLargeSQL = false;
 
  32                 protected $aRoutePoints = false;
 
  34                 protected $iMaxRank = 20;
 
  35                 protected $iMinAddressRank = 0;
 
  36                 protected $iMaxAddressRank = 30;
 
  37                 protected $aAddressRankList = array();
 
  38                 protected $exactMatchCache = array();
 
  40                 protected $sAllowedTypesSQLList = false;
 
  42                 protected $sQuery = false;
 
  43                 protected $aStructuredQuery = false;
 
  45                 function Geocode(&$oDB)
 
  50                 function setReverseInPlan($bReverse)
 
  52                         $this->bReverseInPlan = $bReverse;
 
  55                 function setLanguagePreference($aLangPref)
 
  57                         $this->aLangPrefOrder = $aLangPref;
 
  60                 function setIncludeAddressDetails($bAddressDetails = true)
 
  62                         $this->bIncludeAddressDetails = (bool)$bAddressDetails;
 
  65                 function getIncludeAddressDetails()
 
  67                         return $this->bIncludeAddressDetails;
 
  70                 function setIncludePolygonAsPoints($b = true)
 
  72                         $this->bIncludePolygonAsPoints = $b;
 
  75                 function getIncludePolygonAsPoints()
 
  77                         return $this->bIncludePolygonAsPoints;
 
  80                 function setIncludePolygonAsText($b = true)
 
  82                         $this->bIncludePolygonAsText = $b;
 
  85                 function getIncludePolygonAsText()
 
  87                         return $this->bIncludePolygonAsText;
 
  90                 function setIncludePolygonAsGeoJSON($b = true)
 
  92                         $this->bIncludePolygonAsGeoJSON = $b;
 
  95                 function setIncludePolygonAsKML($b = true)
 
  97                         $this->bIncludePolygonAsKML = $b;
 
 100                 function setIncludePolygonAsSVG($b = true)
 
 102                         $this->bIncludePolygonAsSVG = $b;
 
 105                 function setDeDupe($bDeDupe = true)
 
 107                         $this->bDeDupe = (bool)$bDeDupe;
 
 110                 function setLimit($iLimit = 10)
 
 112                         if ($iLimit > 50) $iLimit = 50;
 
 113                         if ($iLimit < 1) $iLimit = 1;
 
 115                         $this->iFinalLimit = $iLimit;
 
 116                         $this->iLimit = $this->iFinalLimit + min($this->iFinalLimit, 10);
 
 119                 function setOffset($iOffset = 0)
 
 121                         $this->iOffset = $iOffset;
 
 124                 function setFallback($bFallback = true)
 
 126                         $this->bFallback = (bool)$bFallback;
 
 129                 function setExcludedPlaceIDs($a)
 
 131                         // TODO: force to int
 
 132                         $this->aExcludePlaceIDs = $a;
 
 135                 function getExcludedPlaceIDs()
 
 137                         return $this->aExcludePlaceIDs;
 
 140                 function setBounded($bBoundedSearch = true)
 
 142                         $this->bBoundedSearch = (bool)$bBoundedSearch;
 
 145                 function setViewBox($fLeft, $fBottom, $fRight, $fTop)
 
 147                         $this->aViewBox = array($fLeft, $fBottom, $fRight, $fTop);
 
 150                 function getViewBoxString()
 
 152                         if (!$this->aViewBox) return null;
 
 153                         return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
 
 156                 function setRoute($aRoutePoints)
 
 158                         $this->aRoutePoints = $aRoutePoints;
 
 161                 function setFeatureType($sFeatureType)
 
 163                         switch($sFeatureType)
 
 166                                 $this->setRankRange(4, 4);
 
 169                                 $this->setRankRange(8, 8);
 
 172                                 $this->setRankRange(14, 16);
 
 175                                 $this->setRankRange(8, 20);
 
 180                 function setRankRange($iMin, $iMax)
 
 182                         $this->iMinAddressRank = (int)$iMin;
 
 183                         $this->iMaxAddressRank = (int)$iMax;
 
 186                 function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
 
 188                         $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
 
 191                 function setCountryCodesList($aCountryCodes)
 
 193                         $this->aCountryCodes = $aCountryCodes;
 
 196                 function setQuery($sQueryString)
 
 198                         $this->sQuery = $sQueryString;
 
 199                         $this->aStructuredQuery = false;
 
 202                 function getQueryString()
 
 204                         return $this->sQuery;
 
 208                 function loadParamArray($aParams)
 
 210                         if (isset($aParams['addressdetails'])) $this->bIncludeAddressDetails = (bool)$aParams['addressdetails'];
 
 211                         if (isset($aParams['bounded'])) $this->bBoundedSearch = (bool)$aParams['bounded'];
 
 212                         if (isset($aParams['dedupe'])) $this->bDeDupe = (bool)$aParams['dedupe'];
 
 214                         if (isset($aParams['limit'])) $this->setLimit((int)$aParams['limit']);
 
 215                         if (isset($aParams['offset'])) $this->iOffset = (int)$aParams['offset'];
 
 217                         if (isset($aParams['fallback'])) $this->bFallback = (bool)$aParams['fallback'];
 
 219                         // List of excluded Place IDs - used for more acurate pageing
 
 220                         if (isset($aParams['exclude_place_ids']) && $aParams['exclude_place_ids'])
 
 222                                 foreach(explode(',',$aParams['exclude_place_ids']) as $iExcludedPlaceID)
 
 224                                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
 225                                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
 227                                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
 
 230                         // Only certain ranks of feature
 
 231                         if (isset($aParams['featureType'])) $this->setFeatureType($aParams['featureType']);
 
 232                         if (isset($aParams['featuretype'])) $this->setFeatureType($aParams['featuretype']);
 
 235                         if (isset($aParams['countrycodes']))
 
 237                                 $aCountryCodes = array();
 
 238                                 foreach(explode(',',$aParams['countrycodes']) as $sCountryCode)
 
 240                                         if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
 
 242                                                 $aCountryCodes[] = strtolower($sCountryCode);
 
 245                                 $this->aCountryCodes = $aCountryCodes;
 
 248                         if (isset($aParams['viewboxlbrt']) && $aParams['viewboxlbrt'])
 
 250                                 $aCoOrdinatesLBRT = explode(',',$aParams['viewboxlbrt']);
 
 251                                 $this->setViewBox($aCoOrdinatesLBRT[0], $aCoOrdinatesLBRT[1], $aCoOrdinatesLBRT[2], $aCoOrdinatesLBRT[3]);
 
 253                         else if (isset($aParams['viewbox']) && $aParams['viewbox'])
 
 255                                 $aCoOrdinatesLTRB = explode(',',$aParams['viewbox']);
 
 256                                 $this->setViewBox($aCoOrdinatesLTRB[0], $aCoOrdinatesLTRB[3], $aCoOrdinatesLTRB[2], $aCoOrdinatesLTRB[1]);
 
 259                         if (isset($aParams['route']) && $aParams['route'] && isset($aParams['routewidth']) && $aParams['routewidth'])
 
 261                                 $aPoints = explode(',',$aParams['route']);
 
 262                                 if (sizeof($aPoints) % 2 != 0)
 
 264                                         userError("Uneven number of points");
 
 269                                 foreach($aPoints as $i => $fPoint)
 
 273                                                 $aRoute[] = array((float)$fPoint, $fPrevCoord);
 
 277                                                 $fPrevCoord = (float)$fPoint;
 
 280                                 $this->aRoutePoints = $aRoute;
 
 284                 function setQueryFromParams($aParams)
 
 287                         $sQuery = (isset($aParams['q'])?trim($aParams['q']):'');
 
 290                                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
 
 291                                 $this->setReverseInPlan(false);
 
 295                                 $this->setQuery($sQuery);
 
 299                 function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
 
 301                         $sValue = trim($sValue);
 
 302                         if (!$sValue) return false;
 
 303                         $this->aStructuredQuery[$sKey] = $sValue;
 
 304                         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30)
 
 306                                 $this->iMinAddressRank = $iNewMinAddressRank;
 
 307                                 $this->iMaxAddressRank = $iNewMaxAddressRank;
 
 309                         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
 
 313                 function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
 
 315                         $this->sQuery = false;
 
 318                         $this->iMinAddressRank = 0;
 
 319                         $this->iMaxAddressRank = 30;
 
 320                         $this->aAddressRankList = array();
 
 322                         $this->aStructuredQuery = array();
 
 323                         $this->sAllowedTypesSQLList = '';
 
 325                         $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
 
 326                         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
 
 327                         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
 
 328                         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
 
 329                         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
 
 330                         $this->loadStructuredAddressElement($sPostalCode, 'postalcode' , 5, 11, array(5, 11));
 
 331                         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
 
 333                         if (sizeof($this->aStructuredQuery) > 0) 
 
 335                                 $this->sQuery = join(', ', $this->aStructuredQuery);
 
 336                                 if ($this->iMaxAddressRank < 30)
 
 338                                         $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
 
 343                 function fallbackStructuredQuery()
 
 345                         if (!$this->aStructuredQuery) return false;
 
 347                         $aParams = $this->aStructuredQuery;
 
 349                         if (sizeof($aParams) == 1) return false;
 
 351                         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
 
 353                         foreach($aOrderToFallback as $sType)
 
 355                                 if (isset($aParams[$sType]))
 
 357                                         unset($aParams[$sType]);
 
 358                                         $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
 
 366                 function getDetails($aPlaceIDs)
 
 368                         if (sizeof($aPlaceIDs) == 0)  return array();
 
 370                         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
 
 372                         // Get the details for display (is this a redundant extra step?)
 
 373                         $sPlaceIDs = join(',',$aPlaceIDs);
 
 375                         $sImportanceSQL = '';
 
 376                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
 
 377                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
 
 379                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id, min(parent_place_id) as parent_place_id, calculated_country_code as country_code,";
 
 380                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
 381                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
 
 382                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
 
 383                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
 384                         $sSQL .= $sImportanceSQL."coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
 
 385                         $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
 
 386                         $sSQL .= "(extratags->'place') as extra_place ";
 
 387                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
 
 388                         $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 389                         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
 
 390                         if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
 
 392                         if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
 
 393                         $sSQL .= "and linked_place_id is null ";
 
 394                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
 
 395                         if (!$this->bDeDupe) $sSQL .= ",place_id";
 
 396                         $sSQL .= ",langaddress ";
 
 397                         $sSQL .= ",placename ";
 
 399                         $sSQL .= ",extratags->'place' ";
 
 401                         if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank)
 
 404                                 $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, min(parent_place_id) as parent_place_id,'us' as country_code,";
 
 405                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
 406                                 $sSQL .= "null as placename,";
 
 407                                 $sSQL .= "null as ref,";
 
 408                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
 409                                 $sSQL .= $sImportanceSQL."-1.15 as importance, ";
 
 410                                 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_tiger.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
 
 411                                 $sSQL .= "null as extra_place ";
 
 412                                 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
 
 413                                 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 414                                 $sSQL .= "group by place_id";
 
 415                                 if (!$this->bDeDupe) $sSQL .= ",place_id ";
 
 417                                 $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, min(parent_place_id) as parent_place_id,'us' as country_code,";
 
 418                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
 
 419                                 $sSQL .= "null as placename,";
 
 420                                 $sSQL .= "null as ref,";
 
 421                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
 
 422                                 $sSQL .= $sImportanceSQL."-1.10 as importance, ";
 
 423                                 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_aux.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
 
 424                                 $sSQL .= "null as extra_place ";
 
 425                                 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
 
 426                                 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 427                                 $sSQL .= "group by place_id";
 
 428                                 if (!$this->bDeDupe) $sSQL .= ",place_id";
 
 429                                 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 
 432                         $sSQL .= " order by importance desc";
 
 433                         if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
 
 434                         $aSearchResults = $this->oDB->getAll($sSQL);
 
 436                         if (PEAR::IsError($aSearchResults))
 
 438                                 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
 
 441                         return $aSearchResults;
 
 444                 /* Perform the actual query lookup.
 
 446                         Returns an ordered list of results, each with the following fields:
 
 447                           osm_type: type of corresponding OSM object
 
 451                                                         P - postcode (internally computed)
 
 452                           osm_id: id of corresponding OSM object
 
 453                           class: general object class (corresponds to tag key of primary OSM tag)
 
 454                           type: subclass of object (corresponds to tag value of primary OSM tag)
 
 455                           admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
 
 456                           rank_search: rank in search hierarchy
 
 457                                                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
 
 458                           rank_address: rank in address hierarchy (determines orer in address)
 
 459                           place_id: internal key (may differ between different instances)
 
 460                           country_code: ISO country code
 
 461                           langaddress: localized full address
 
 462                           placename: localized name of object
 
 463                           ref: content of ref tag (if available)
 
 466                           importance: importance of place based on Wikipedia link count
 
 467                           addressimportance: cumulated importance of address elements
 
 468                           extra_place: type of place (for admin boundaries, if there is a place tag)
 
 469                           aBoundingBox: bounding Box
 
 470                           label: short description of the object class/type (English only) 
 
 471                           name: full name (currently the same as langaddress)
 
 472                           foundorder: secondary ordering for places with same importance
 
 476                         if (!$this->sQuery && !$this->aStructuredQuery) return false;
 
 478                         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
 
 480                         $sCountryCodesSQL = false;
 
 481                         if ($this->aCountryCodes && sizeof($this->aCountryCodes))
 
 483                                 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
 
 486                         $sQuery = $this->sQuery;
 
 488                         // Conflicts between US state abreviations and various words for 'the' in different languages
 
 489                         if (isset($this->aLangPrefOrder['name:en']))
 
 491                                 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/','\1illinois\2', $sQuery);
 
 492                                 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/','\1alabama\2', $sQuery);
 
 493                                 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/','\1louisiana\2', $sQuery);
 
 497                         $sViewboxCentreSQL = false;
 
 498                         $bBoundingBoxSearch = false;
 
 501                                 $fHeight = $this->aViewBox[0]-$this->aViewBox[2];
 
 502                                 $fWidth = $this->aViewBox[1]-$this->aViewBox[3];
 
 503                                 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
 
 504                                 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
 
 505                                 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
 
 506                                 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
 
 508                                 $this->sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$this->aViewBox[0].",".(float)$this->aViewBox[1]."),ST_Point(".(float)$this->aViewBox[2].",".(float)$this->aViewBox[3].")),4326)";
 
 509                                 $this->sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aBigViewBox[0].",".(float)$aBigViewBox[1]."),ST_Point(".(float)$aBigViewBox[2].",".(float)$aBigViewBox[3].")),4326)";
 
 510                                 $bBoundingBoxSearch = $this->bBoundedSearch;
 
 514                         if ($this->aRoutePoints)
 
 516                                 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
 
 518                                 foreach($this->aRoutePoints as $aPoint)
 
 520                                         if (!$bFirst) $sViewboxCentreSQL .= ",";
 
 521                                         $sViewboxCentreSQL .= $aPoint[1].' '.$aPoint[0];
 
 524                                 $sViewboxCentreSQL .= ")'::geometry,4326)";
 
 526                                 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
 
 527                                 $this->sViewboxSmallSQL = $this->oDB->getOne($sSQL);
 
 528                                 if (PEAR::isError($this->sViewboxSmallSQL))
 
 530                                         failInternalError("Could not get small viewbox.", $sSQL, $this->sViewboxSmallSQL);
 
 532                                 $this->sViewboxSmallSQL = "'".$this->sViewboxSmallSQL."'::geometry";
 
 534                                 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
 
 535                                 $this->sViewboxLargeSQL = $this->oDB->getOne($sSQL);
 
 536                                 if (PEAR::isError($this->sViewboxLargeSQL))
 
 538                                         failInternalError("Could not get large viewbox.", $sSQL, $this->sViewboxLargeSQL);
 
 540                                 $this->sViewboxLargeSQL = "'".$this->sViewboxLargeSQL."'::geometry";
 
 541                                 $bBoundingBoxSearch = $this->bBoundedSearch;
 
 544                         // Do we have anything that looks like a lat/lon pair?
 
 545                         if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
 
 547                                 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
 
 548                                 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
 
 549                                 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 551                                         $this->setNearPoint(array($fQueryLat, $fQueryLon));
 
 552                                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 555                         elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
 
 557                                 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
 
 558                                 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
 
 559                                 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 561                                         $this->setNearPoint(array($fQueryLat, $fQueryLon));
 
 562                                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 565                         elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData))
 
 567                                 $fQueryLat = $aData[2];
 
 568                                 $fQueryLon = $aData[3];
 
 569                                 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
 
 571                                         $this->setNearPoint(array($fQueryLat, $fQueryLon));
 
 572                                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
 
 576                         $aSearchResults = array();
 
 577                         if ($sQuery || $this->aStructuredQuery)
 
 579                                 // Start with a blank search
 
 581                                         array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
 
 582                                               'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
 
 583                                               'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
 
 586                                 // Do we have a radius search?
 
 587                                 $sNearPointSQL = false;
 
 588                                 if ($this->aNearPoint)
 
 590                                         $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
 
 591                                         $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
 
 592                                         $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
 
 593                                         $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
 
 596                                 // Any 'special' terms in the search?
 
 597                                 $bSpecialTerms = false;
 
 598                                 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 599                                 $aSpecialTerms = array();
 
 600                                 foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 602                                         $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 603                                         $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
 
 606                                 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
 607                                 $aSpecialTerms = array();
 
 608                                 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
 
 610                                         $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
 
 611                                         unset($aStructuredQuery['amenity']);
 
 613                                 foreach($aSpecialTermsRaw as $aSpecialTerm)
 
 615                                         $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 616                                         $sToken = $this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
 
 617                                         $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
 
 618                                         $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null';
 
 619                                         if (CONST_Debug) var_Dump($sSQL);
 
 620                                         $aSearchWords = $this->oDB->getAll($sSQL);
 
 621                                         $aNewSearches = array();
 
 622                                         foreach($aSearches as $aSearch)
 
 624                                                 foreach($aSearchWords as $aSearchTerm)
 
 626                                                         $aNewSearch = $aSearch;
 
 627                                                         if ($aSearchTerm['country_code'])
 
 629                                                                 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 630                                                                 $aNewSearches[] = $aNewSearch;
 
 631                                                                 $bSpecialTerms = true;
 
 633                                                         if ($aSearchTerm['class'])
 
 635                                                                 $aNewSearch['sClass'] = $aSearchTerm['class'];
 
 636                                                                 $aNewSearch['sType'] = $aSearchTerm['type'];
 
 637                                                                 $aNewSearches[] = $aNewSearch;
 
 638                                                                 $bSpecialTerms = true;
 
 642                                         $aSearches = $aNewSearches;
 
 645                                 // Split query into phrases
 
 646                                 // Commas are used to reduce the search space by indicating where phrases split
 
 647                                 if ($this->aStructuredQuery)
 
 649                                         $aPhrases = $this->aStructuredQuery;
 
 650                                         $bStructuredPhrases = true;
 
 654                                         $aPhrases = explode(',',$sQuery);
 
 655                                         $bStructuredPhrases = false;
 
 658                                 // Convert each phrase to standard form
 
 659                                 // Create a list of standard words
 
 660                                 // Get all 'sets' of words
 
 661                                 // Generate a complete list of all
 
 663                                 foreach($aPhrases as $iPhrase => $sPhrase)
 
 665                                         $aPhrase = $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
 
 666                                         if (PEAR::isError($aPhrase))
 
 668                                                 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
 
 669                                                 if (CONST_Debug) var_dump($aPhrase);
 
 672                                         if (trim($aPhrase['string']))
 
 674                                                 $aPhrases[$iPhrase] = $aPhrase;
 
 675                                                 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
 
 676                                                 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
 
 677                                                 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
 681                                                 unset($aPhrases[$iPhrase]);
 
 685                                 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
 
 686                                 $aPhraseTypes = array_keys($aPhrases);
 
 687                                 $aPhrases = array_values($aPhrases);
 
 689                                 if (sizeof($aTokens))
 
 691                                         // Check which tokens we have, get the ID numbers
 
 692                                         $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
 
 693                                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
 
 695                                         if (CONST_Debug) var_Dump($sSQL);
 
 697                                         $aValidTokens = array();
 
 698                                         if (sizeof($aTokens)) $aDatabaseWords = $this->oDB->getAll($sSQL);
 
 699                                         else $aDatabaseWords = array();
 
 700                                         if (PEAR::IsError($aDatabaseWords))
 
 702                                                 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
 
 704                                         $aPossibleMainWordIDs = array();
 
 705                                         $aWordFrequencyScores = array();
 
 706                                         foreach($aDatabaseWords as $aToken)
 
 708                                                 // Very special case - require 2 letter country param to match the country code found
 
 709                                                 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
 
 710                                                                 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
 
 715                                                 if (isset($aValidTokens[$aToken['word_token']]))
 
 717                                                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
 721                                                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
 723                                                 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
 
 724                                                 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
 
 726                                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
 728                                         // Try and calculate GB postcodes we might be missing
 
 729                                         foreach($aTokens as $sToken)
 
 731                                                 // Source of gb postcodes is now definitive - always use
 
 732                                                 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
 
 734                                                         if (substr($aData[1],-2,1) != ' ')
 
 736                                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
 
 737                                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
 
 739                                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
 
 740                                                         if ($aGBPostcodeLocation)
 
 742                                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
 
 745                                                 // US ZIP+4 codes - if there is no token,
 
 746                                                 //      merge in the 5-digit ZIP code
 
 747                                                 else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
 
 749                                                         if (isset($aValidTokens[$aData[1]]))
 
 751                                                                 foreach($aValidTokens[$aData[1]] as $aToken)
 
 753                                                                         if (!$aToken['class'])
 
 755                                                                                 if (isset($aValidTokens[$sToken]))
 
 757                                                                                         $aValidTokens[$sToken][] = $aToken;
 
 761                                                                                         $aValidTokens[$sToken] = array($aToken);
 
 769                                         foreach($aTokens as $sToken)
 
 771                                                 // Unknown single word token with a number - assume it is a house number
 
 772                                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
 
 774                                                         $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
 
 778                                         // Any words that have failed completely?
 
 781                                         // Start the search process
 
 782                                         $aResultPlaceIDs = array();
 
 785                                            Calculate all searches using aValidTokens i.e.
 
 786                                            'Wodsworth Road, Sheffield' =>
 
 790                                            0      1       (wodsworth)(road)
 
 793                                            Score how good the search is so they can be ordered
 
 795                                         foreach($aPhrases as $iPhrase => $sPhrase)
 
 797                                                 $aNewPhraseSearches = array();
 
 798                                                 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
 
 799                                                 else $sPhraseType = '';
 
 801                                                 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
 
 803                                                         // Too many permutations - too expensive
 
 804                                                         if ($iWordSet > 120) break;
 
 806                                                         $aWordsetSearches = $aSearches;
 
 808                                                         // Add all words from this wordset
 
 809                                                         foreach($aWordset as $iToken => $sToken)
 
 811                                                                 //echo "<br><b>$sToken</b>";
 
 812                                                                 $aNewWordsetSearches = array();
 
 814                                                                 foreach($aWordsetSearches as $aCurrentSearch)
 
 817                                                                         //var_dump($aCurrentSearch);
 
 820                                                                         // If the token is valid
 
 821                                                                         if (isset($aValidTokens[' '.$sToken]))
 
 823                                                                                 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
 
 825                                                                                         $aSearch = $aCurrentSearch;
 
 826                                                                                         $aSearch['iSearchRank']++;
 
 827                                                                                         if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
 
 829                                                                                                 if ($aSearch['sCountryCode'] === false)
 
 831                                                                                                         $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 832                                                                                                         // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
 
 833                                                                                                         // If reverse order is enabled, it may appear at the beginning as well.
 
 834                                                                                                         if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
 
 835                                                                                                                         (!$this->bReverseInPlan || $iToken > 0 || $iPhrase > 0))
 
 837                                                                                                                 $aSearch['iSearchRank'] += 5;
 
 839                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 842                                                                                         elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
 
 844                                                                                                 if ($aSearch['fLat'] === '')
 
 846                                                                                                         $aSearch['fLat'] = $aSearchTerm['lat'];
 
 847                                                                                                         $aSearch['fLon'] = $aSearchTerm['lon'];
 
 848                                                                                                         $aSearch['fRadius'] = $aSearchTerm['radius'];
 
 849                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 852                                                                                         elseif ($sPhraseType == 'postalcode')
 
 854                                                                                                 // We need to try the case where the postal code is the primary element (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode) so try both
 
 855                                                                                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
 
 857                                                                                                         // If we already have a name try putting the postcode first
 
 858                                                                                                         if (sizeof($aSearch['aName']))
 
 860                                                                                                                 $aNewSearch = $aSearch;
 
 861                                                                                                                 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
 
 862                                                                                                                 $aNewSearch['aName'] = array();
 
 863                                                                                                                 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 864                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
 
 867                                                                                                         if (sizeof($aSearch['aName']))
 
 869                                                                                                                 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
 
 871                                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 875                                                                                                                         $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 876                                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
 
 881                                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 882                                                                                                                 //$aSearch['iNamePhrase'] = $iPhrase;
 
 884                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 888                                                                                         elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
 
 890                                                                                                 if ($aSearch['sHouseNumber'] === '')
 
 892                                                                                                         $aSearch['sHouseNumber'] = $sToken;
 
 893                                                                                                         // sanity check: if the housenumber is not mainly made
 
 894                                                                                                         // up of numbers, add a penalty
 
 895                                                                                                         if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
 
 896                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 898                                                                                                         // Fall back to not searching for this item (better than nothing)
 
 899                                                                                                         $aSearch = $aCurrentSearch;
 
 900                                                                                                         $aSearch['iSearchRank'] += 1;
 
 901                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 905                                                                                         elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
 
 907                                                                                                 if ($aSearch['sClass'] === '')
 
 909                                                                                                         $aSearch['sOperator'] = $aSearchTerm['operator'];
 
 910                                                                                                         $aSearch['sClass'] = $aSearchTerm['class'];
 
 911                                                                                                         $aSearch['sType'] = $aSearchTerm['type'];
 
 912                                                                                                         if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
 
 913                                                                                                         else $aSearch['sOperator'] = 'near'; // near = in for the moment
 
 914                                                                                                         if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
 
 916                                                                                                         // Do we have a shortcut id?
 
 917                                                                                                         if ($aSearch['sOperator'] == 'name')
 
 919                                                                                                                 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
 
 920                                                                                                                 if ($iAmenityID = $this->oDB->getOne($sSQL))
 
 922                                                                                                                         $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
 
 923                                                                                                                         $aSearch['aName'][$iAmenityID] = $iAmenityID;
 
 924                                                                                                                         $aSearch['sClass'] = '';
 
 925                                                                                                                         $aSearch['sType'] = '';
 
 928                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 931                                                                                         elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
 
 933                                                                                                 if (sizeof($aSearch['aName']))
 
 935                                                                                                         if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
 
 937                                                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 941                                                                                                                 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 942                                                                                                                 $aSearch['iSearchRank'] += 1000; // skip;
 
 947                                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 948                                                                                                         //$aSearch['iNamePhrase'] = $iPhrase;
 
 950                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 954                                                                         if (isset($aValidTokens[$sToken]))
 
 956                                                                                 // Allow searching for a word - but at extra cost
 
 957                                                                                 foreach($aValidTokens[$sToken] as $aSearchTerm)
 
 959                                                                                         if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
 
 961                                                                                                 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
 
 963                                                                                                         $aSearch = $aCurrentSearch;
 
 964                                                                                                         $aSearch['iSearchRank'] += 1;
 
 965                                                                                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
 
 967                                                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 968                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 970                                                                                                         elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
 
 972                                                                                                                 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
 
 974                                                                                                                         if (empty($aSearchTermToken['country_code'])
 
 975                                                                                                                                         && empty($aSearchTermToken['lat'])
 
 976                                                                                                                                         && empty($aSearchTermToken['class']))
 
 978                                                                                                                                 $aSearch = $aCurrentSearch;
 
 979                                                                                                                                 $aSearch['iSearchRank'] += 1;
 
 980                                                                                                                                 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
 
 981                                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 987                                                                                                                 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 988                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 992                                                                                                 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
 
 994                                                                                                         $aSearch = $aCurrentSearch;
 
 995                                                                                                         $aSearch['iSearchRank'] += 2;
 
 996                                                                                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
 
 997                                                                                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
 
 998                                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
1000                                                                                                                 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
1001                                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
 
1002                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
1009                                                                                 // Allow skipping a word - but at EXTREAM cost
 
1010                                                                                 //$aSearch = $aCurrentSearch;
 
1011                                                                                 //$aSearch['iSearchRank']+=100;
 
1012                                                                                 //$aNewWordsetSearches[] = $aSearch;
 
1016                                                                 usort($aNewWordsetSearches, 'bySearchRank');
 
1017                                                                 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
1019                                                         //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
1021                                                         $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
1022                                                         usort($aNewPhraseSearches, 'bySearchRank');
 
1024                                                         $aSearchHash = array();
 
1025                                                         foreach($aNewPhraseSearches as $iSearch => $aSearch)
 
1027                                                                 $sHash = serialize($aSearch);
 
1028                                                                 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
 
1029                                                                 else $aSearchHash[$sHash] = 1;
 
1032                                                         $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
1035                                                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
1036                                                 $aGroupedSearches = array();
 
1037                                                 foreach($aNewPhraseSearches as $aSearch)
 
1039                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank)
 
1041                                                                 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
1042                                                                 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
1045                                                 ksort($aGroupedSearches);
 
1048                                                 $aSearches = array();
 
1049                                                 foreach($aGroupedSearches as $iScore => $aNewSearches)
 
1051                                                         $iSearchCount += sizeof($aNewSearches);
 
1052                                                         $aSearches = array_merge($aSearches, $aNewSearches);
 
1053                                                         if ($iSearchCount > 50) break;
 
1056                                                 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
1063                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
1064                                         $aGroupedSearches = array();
 
1065                                         foreach($aSearches as $aSearch)
 
1067                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank)
 
1069                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
1070                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
1073                                         ksort($aGroupedSearches);
 
1076                                 if (CONST_Debug) var_Dump($aGroupedSearches);
 
1078                                 if ($this->bReverseInPlan)
 
1080                                         $aCopyGroupedSearches = $aGroupedSearches;
 
1081                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
 
1083                                                 foreach($aSearches as $iSearch => $aSearch)
 
1085                                                         if (sizeof($aSearch['aAddress']))
 
1087                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
 
1088                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
 
1090                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
 
1091                                                                         $aSearch['aName'] = array($iReverseItem);
 
1092                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
 
1094                                                                 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
 
1095                                                                 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
 
1101                                 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
 
1103                                         $aCopyGroupedSearches = $aGroupedSearches;
 
1104                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
 
1106                                                 foreach($aSearches as $iSearch => $aSearch)
 
1108                                                         $aReductionsList = array($aSearch['aAddress']);
 
1109                                                         $iSearchRank = $aSearch['iSearchRank'];
 
1110                                                         while(sizeof($aReductionsList) > 0)
 
1113                                                                 if ($iSearchRank > iMaxRank) break 3;
 
1114                                                                 $aNewReductionsList = array();
 
1115                                                                 foreach($aReductionsList as $aReductionsWordList)
 
1117                                                                         for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
 
1119                                                                                 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
 
1120                                                                                 $aReverseSearch = $aSearch;
 
1121                                                                                 $aSearch['aAddress'] = $aReductionsWordListResult;
 
1122                                                                                 $aSearch['iSearchRank'] = $iSearchRank;
 
1123                                                                                 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
 
1124                                                                                 if (sizeof($aReductionsWordListResult) > 0)
 
1126                                                                                         $aNewReductionsList[] = $aReductionsWordListResult;
 
1130                                                                 $aReductionsList = $aNewReductionsList;
 
1134                                         ksort($aGroupedSearches);
 
1137                                 // Filter out duplicate searches
 
1138                                 $aSearchHash = array();
 
1139                                 foreach($aGroupedSearches as $iGroup => $aSearches)
 
1141                                         foreach($aSearches as $iSearch => $aSearch)
 
1143                                                 $sHash = serialize($aSearch);
 
1144                                                 if (isset($aSearchHash[$sHash]))
 
1146                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
1147                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
1151                                                         $aSearchHash[$sHash] = 1;
 
1156                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
1160                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
 
1163                                         foreach($aSearches as $aSearch)
 
1167                                                 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
 
1168                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
 
1170                                                 // No location term?
 
1171                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
 
1173                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
 
1175                                                                 // Just looking for a country by code - look it up
 
1176                                                                 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
 
1178                                                                         $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
 
1179                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
 
1180                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
 
1181                                                                         if (CONST_Debug) var_dump($sSQL);
 
1182                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1186                                                                         $aPlaceIDs = array();
 
1191                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
 
1192                                                                 if (!$aSearch['sClass']) continue;
 
1193                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
1194                                                                 if ($this->oDB->getOne($sSQL))
 
1196                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
1197                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
1198                                                                         $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
 
1199                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
 
1200                                                                         if (sizeof($this->aExcludePlaceIDs))
 
1202                                                                                 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
 
1204                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
 
1205                                                                         $sSQL .= " limit $this->iLimit";
 
1206                                                                         if (CONST_Debug) var_dump($sSQL);
 
1207                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1209                                                                         // If excluded place IDs are given, it is fair to assume that
 
1210                                                                         // there have been results in the small box, so no further
 
1211                                                                         // expansion in that case.
 
1212                                                                         // Also don't expand if bounded results were requested.
 
1213                                                                         if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch)
 
1215                                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
1216                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
1217                                                                                 $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
 
1218                                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
 
1219                                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
 
1220                                                                                 $sSQL .= " limit $this->iLimit";
 
1221                                                                                 if (CONST_Debug) var_dump($sSQL);
 
1222                                                                                 $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1227                                                                         $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
1228                                                                         $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
 
1229                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
 
1230                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
 
1231                                                                         $sSQL .= " limit $this->iLimit";
 
1232                                                                         if (CONST_Debug) var_dump($sSQL);
 
1233                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1239                                                         $aPlaceIDs = array();
 
1241                                                         // First we need a position, either aName or fLat or both
 
1245                                                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
 
1246                                                         // they might be right - but they are just too darned expensive to run
 
1247                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
 
1248                                                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
 
1249                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
 
1251                                                                 // For infrequent name terms disable index usage for address
 
1252                                                                 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
 
1253                                                                                 sizeof($aSearch['aName']) == 1 &&
 
1254                                                                                 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
 
1256                                                                         $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
 
1260                                                                         $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
 
1261                                                                         if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
 
1264                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
 
1265                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
 
1266                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
 
1268                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
 
1269                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
 
1271                                                         if (sizeof($this->aExcludePlaceIDs))
 
1273                                                                 $aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
 
1275                                                         if ($sCountryCodesSQL)
 
1277                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
 
1280                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
 
1281                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
 
1283                                                         if ($aSearch['sHouseNumber'])
 
1285                                                                 $sImportanceSQL = '- abs(26 - address_rank) + 3';
 
1289                                                                 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
 
1291                                                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
 
1292                                                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
 
1294                                                         $aOrder[] = "$sImportanceSQL DESC";
 
1295                                                         if (sizeof($aSearch['aFullNameAddress']))
 
1297                                                                 $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
 
1298                                                                 $aOrder[] = 'exactmatch DESC';
 
1300                                                                 $sExactMatchSQL = '0::int as exactmatch';
 
1303                                                         if (sizeof($aTerms))
 
1305                                                                 $sSQL = "select place_id, ";
 
1306                                                                 $sSQL .= $sExactMatchSQL;
 
1307                                                                 $sSQL .= " from search_name";
 
1308                                                                 $sSQL .= " where ".join(' and ',$aTerms);
 
1309                                                                 $sSQL .= " order by ".join(', ',$aOrder);
 
1310                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
 
1311                                                                         $sSQL .= " limit 50";
 
1312                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
 
1313                                                                         $sSQL .= " limit 1";
 
1315                                                                         $sSQL .= " limit ".$this->iLimit;
 
1317                                                                 if (CONST_Debug) { var_dump($sSQL); }
 
1318                                                                 $aViewBoxPlaceIDs = $this->oDB->getAll($sSQL);
 
1319                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
 
1321                                                                         failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
 
1323                                                                 //var_dump($aViewBoxPlaceIDs);
 
1324                                                                 // Did we have an viewbox matches?
 
1325                                                                 $aPlaceIDs = array();
 
1326                                                                 $bViewBoxMatch = false;
 
1327                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
 
1329                                                                         //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
 
1330                                                                         //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
 
1331                                                                         //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
 
1332                                                                         //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
 
1333                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
 
1334                                                                         $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
 
1337                                                         //var_Dump($aPlaceIDs);
 
1340                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
 
1342                                                                 $aRoadPlaceIDs = $aPlaceIDs;
 
1343                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
1345                                                                 // Now they are indexed look for a house attached to a street we found
 
1346                                                                 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
 
1347                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
1348                                                                 if (sizeof($this->aExcludePlaceIDs))
 
1350                                                                         $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
 
1352                                                                 $sSQL .= " limit $this->iLimit";
 
1353                                                                 if (CONST_Debug) var_dump($sSQL);
 
1354                                                                 $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1356                                                                 // If not try the aux fallback table
 
1357                                                                 if (!sizeof($aPlaceIDs))
 
1359                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
1360                                                                         if (sizeof($this->aExcludePlaceIDs))
 
1362                                                                                 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
 
1364                                                                         //$sSQL .= " limit $this->iLimit";
 
1365                                                                         if (CONST_Debug) var_dump($sSQL);
 
1366                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1369                                                                 if (!sizeof($aPlaceIDs))
 
1371                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
1372                                                                         if (sizeof($this->aExcludePlaceIDs))
 
1374                                                                                 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
 
1376                                                                         //$sSQL .= " limit $this->iLimit";
 
1377                                                                         if (CONST_Debug) var_dump($sSQL);
 
1378                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1381                                                                 // Fallback to the road
 
1382                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
 
1384                                                                         $aPlaceIDs = $aRoadPlaceIDs;
 
1389                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
 
1391                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
1392                                                                 $aClassPlaceIDs = array();
 
1394                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
 
1396                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
 
1397                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
 
1398                                                                         $sSQL .= " and linked_place_id is null";
 
1399                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
 
1400                                                                         $sSQL .= " order by rank_search asc limit $this->iLimit";
 
1401                                                                         if (CONST_Debug) var_dump($sSQL);
 
1402                                                                         $aClassPlaceIDs = $this->oDB->getCol($sSQL);
 
1405                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
 
1407                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
1408                                                                         $bCacheTable = $this->oDB->getOne($sSQL);
 
1410                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
 
1412                                                                         if (CONST_Debug) var_dump($sSQL);
 
1413                                                                         $this->iMaxRank = ((int)$this->oDB->getOne($sSQL));
 
1415                                                                         // For state / country level searches the normal radius search doesn't work very well
 
1416                                                                         $sPlaceGeom = false;
 
1417                                                                         if ($this->iMaxRank < 9 && $bCacheTable)
 
1419                                                                                 // Try and get a polygon to search in instead
 
1420                                                                                 $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
 
1421                                                                                 if (CONST_Debug) var_dump($sSQL);
 
1422                                                                                 $sPlaceGeom = $this->oDB->getOne($sSQL);
 
1431                                                                                 $this->iMaxRank += 5;
 
1432                                                                                 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
 
1433                                                                                 if (CONST_Debug) var_dump($sSQL);
 
1434                                                                                 $aPlaceIDs = $this->oDB->getCol($sSQL);
 
1435                                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
 
1438                                                                         if ($sPlaceIDs || $sPlaceGeom)
 
1444                                                                                         // More efficient - can make the range bigger
 
1448                                                                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
 
1449                                                                                         else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
 
1450                                                                                         else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
1452                                                                                         $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
 
1453                                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
 
1456                                                                                                 $sSQL .= ",placex as f where ";
 
1457                                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
 
1462                                                                                                 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
 
1464                                                                                         if (sizeof($this->aExcludePlaceIDs))
 
1466                                                                                                 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
 
1468                                                                                         if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
 
1469                                                                                         if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
 
1470                                                                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
 
1471                                                                                         $sSQL .= " limit $this->iLimit";
 
1472                                                                                         if (CONST_Debug) var_dump($sSQL);
 
1473                                                                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
 
1477                                                                                         if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
 
1480                                                                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
 
1481                                                                                         else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
 
1483                                                                                         $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
 
1484                                                                                         $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
 
1485                                                                                         $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
 
1486                                                                                         if (sizeof($this->aExcludePlaceIDs))
 
1488                                                                                                 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
 
1490                                                                                         if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
 
1491                                                                                         if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
 
1492                                                                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
 
1493                                                                                         $sSQL .= " limit $this->iLimit";
 
1494                                                                                         if (CONST_Debug) var_dump($sSQL);
 
1495                                                                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
 
1500                                                                 $aPlaceIDs = $aClassPlaceIDs;
 
1506                                                 if (PEAR::IsError($aPlaceIDs))
 
1508                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
 
1511                                                 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
 
1513                                                 foreach($aPlaceIDs as $iPlaceID)
 
1515                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
 
1517                                                 if ($iQueryLoop > 20) break;
 
1520                                         if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
 
1522                                                 // Need to verify passes rank limits before dropping out of the loop (yuk!)
 
1523                                                 $sSQL = "select place_id from placex where place_id in (".join(',',$aResultPlaceIDs).") ";
 
1524                                                 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
1525                                                 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
 
1526                                                 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
 
1527                                                 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',$aResultPlaceIDs).") ";
 
1528                                                 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
1529                                                 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
 
1531                                                 if (CONST_Debug) var_dump($sSQL);
 
1532                                                 $aResultPlaceIDs = $this->oDB->getCol($sSQL);
 
1536                                         if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
 
1537                                         if ($iGroupLoop > 4) break;
 
1538                                         if ($iQueryLoop > 30) break;
 
1541                                 // Did we find anything?
 
1542                                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
 
1544                                         $aSearchResults = $this->getDetails($aResultPlaceIDs);
 
1550                                 // Just interpret as a reverse geocode
 
1551                                 $iPlaceID = geocodeReverse((float)$this->aNearPoint[0], (float)$this->aNearPoint[1]);
 
1553                                         $aSearchResults = $this->getDetails(array($iPlaceID));
 
1555                                         $aSearchResults = array();
 
1559                         if (!sizeof($aSearchResults))
 
1561                                 if ($this->bFallback)
 
1563                                         if ($this->fallbackStructuredQuery())
 
1565                                                 return $this->lookup();
 
1572                         $aClassType = getClassTypesWithImportance();
 
1573                         $aRecheckWords = preg_split('/\b[\s,\\-]*/u',$sQuery);
 
1574                         foreach($aRecheckWords as $i => $sWord)
 
1576                                 if (!$sWord) unset($aRecheckWords[$i]);
 
1579                         foreach($aSearchResults as $iResNum => $aResult)
 
1581                                 if (CONST_Search_AreaPolygons)
 
1583                                         // Get the bounding box and outline polygon
 
1584                                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
 
1585                                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
 
1586                                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
 
1587                                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
 
1588                                         if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
 
1589                                         if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
 
1590                                         if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
 
1591                                         if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
 
1592                                         $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
 
1593                                         $aPointPolygon = $this->oDB->getRow($sSQL);
 
1594                                         if (PEAR::IsError($aPointPolygon))
 
1596                                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
 
1599                                         if ($aPointPolygon['place_id'])
 
1601                                                 if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
 
1602                                                 if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
 
1603                                                 if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
 
1604                                                 if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
 
1606                                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
 
1608                                                         $aResult['lat'] = $aPointPolygon['centrelat'];
 
1609                                                         $aResult['lon'] = $aPointPolygon['centrelon'];
 
1612                                                 if ($this->bIncludePolygonAsPoints)
 
1614                                                         // Translate geometary string to point array
 
1615                                                         if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
 
1617                                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
1619                                                         elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
 
1621                                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
 
1623                                                         elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
 
1626                                                                 $iSteps = ($fRadius * 40000)^2;
 
1627                                                                 $fStepSize = (2*pi())/$iSteps;
 
1628                                                                 $aPolyPoints = array();
 
1629                                                                 for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1631                                                                         $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
 
1633                                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
 
1634                                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
 
1635                                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
 
1636                                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
 
1640                                                 // Output data suitable for display (points and a bounding box)
 
1641                                                 if ($this->bIncludePolygonAsPoints && isset($aPolyPoints))
 
1643                                                         $aResult['aPolyPoints'] = array();
 
1644                                                         foreach($aPolyPoints as $aPoint)
 
1646                                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1649                                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
 
1653                                 if ($aResult['extra_place'] == 'city')
 
1655                                         $aResult['class'] = 'place';
 
1656                                         $aResult['type'] = 'city';
 
1657                                         $aResult['rank_search'] = 16;
 
1660                                 if (!isset($aResult['aBoundingBox']))
 
1663                                         $fDiameter = 0.0001;
 
1665                                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
 
1666                                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
 
1668                                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
 
1670                                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
 
1671                                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
 
1673                                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
 
1675                                         $fRadius = $fDiameter / 2;
 
1677                                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
 
1678                                         $fStepSize = (2*pi())/$iSteps;
 
1679                                         $aPolyPoints = array();
 
1680                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
 
1682                                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
 
1684                                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
 
1685                                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
 
1686                                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
 
1687                                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
 
1689                                         // Output data suitable for display (points and a bounding box)
 
1690                                         if ($this->bIncludePolygonAsPoints)
 
1692                                                 $aResult['aPolyPoints'] = array();
 
1693                                                 foreach($aPolyPoints as $aPoint)
 
1695                                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
 
1698                                         $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
 
1701                                 // Is there an icon set for this type of result?
 
1702                                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1703                                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1705                                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
1708                                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
 
1709                                                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
 
1711                                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
 
1713                                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1714                                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1716                                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
1719                                 if ($this->bIncludeAddressDetails)
 
1721                                         $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
 
1722                                         if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
 
1724                                                 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
 
1728                                 // Adjust importance for the number of exact string matches in the result
 
1729                                 $aResult['importance'] = max(0.001,$aResult['importance']);
 
1731                                 $sAddress = $aResult['langaddress'];
 
1732                                 foreach($aRecheckWords as $i => $sWord)
 
1734                                         if (stripos($sAddress, $sWord)!==false)
 
1737                                                 if (preg_match("/(^|,)\s*$sWord\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
 
1741                                 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1); // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
 
1743                                 $aResult['name'] = $aResult['langaddress'];
 
1744                                 // secondary ordering (for results with same importance (the smaller the better):
 
1745                                 //   - approximate importance of address parts
 
1746                                 $aResult['foundorder'] = -$aResult['addressimportance']/10;
 
1747                                 //   - number of exact matches from the query
 
1748                                 if (isset($this->exactMatchCache[$aResult['place_id']]))
 
1749                                         $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
 
1750                                 else if (isset($this->exactMatchCache[$aResult['parent_place_id']]))
 
1751                                         $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
 
1752                                 //  - importance of the class/type
 
1753                                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1754                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1756                                         $aResult['foundorder'] = $aResult['foundorder'] + 0.000001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1760                                         $aResult['foundorder'] = $aResult['foundorder'] + 0.001;
 
1762                                 $aSearchResults[$iResNum] = $aResult;
 
1764                         uasort($aSearchResults, 'byImportance');
 
1766                         $aOSMIDDone = array();
 
1767                         $aClassTypeNameDone = array();
 
1768                         $aToFilter = $aSearchResults;
 
1769                         $aSearchResults = array();
 
1772                         foreach($aToFilter as $iResNum => $aResult)
 
1774                                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
 
1775                                 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1778                                         $fLat = $aResult['lat'];
 
1779                                         $fLon = $aResult['lon'];
 
1780                                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1783                                 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1784                                                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
 
1786                                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1787                                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
 
1788                                         $aSearchResults[] = $aResult;
 
1791                                 // Absolute limit on number of results
 
1792                                 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
 
1795                         return $aSearchResults;