5 require_once(CONST_BasePath.'/lib/NearPoint.php');
 
   6 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
 
   7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
 
  13     protected $aLangPrefOrder = array();
 
  15     protected $bIncludeAddressDetails = false;
 
  16     protected $bIncludeExtraTags = false;
 
  17     protected $bIncludeNameDetails = false;
 
  19     protected $bIncludePolygonAsPoints = false;
 
  20     protected $bIncludePolygonAsText = false;
 
  21     protected $bIncludePolygonAsGeoJSON = false;
 
  22     protected $bIncludePolygonAsKML = false;
 
  23     protected $bIncludePolygonAsSVG = false;
 
  24     protected $fPolygonSimplificationThreshold = 0.0;
 
  26     protected $aExcludePlaceIDs = array();
 
  27     protected $bDeDupe = true;
 
  28     protected $bReverseInPlan = false;
 
  30     protected $iLimit = 20;
 
  31     protected $iFinalLimit = 10;
 
  32     protected $iOffset = 0;
 
  33     protected $bFallback = false;
 
  35     protected $aCountryCodes = false;
 
  37     protected $bBoundedSearch = false;
 
  38     protected $aViewBox = false;
 
  39     protected $sViewboxCentreSQL = false;
 
  40     protected $sViewboxSmallSQL = false;
 
  41     protected $sViewboxLargeSQL = false;
 
  43     protected $iMaxRank = 20;
 
  44     protected $iMinAddressRank = 0;
 
  45     protected $iMaxAddressRank = 30;
 
  46     protected $aAddressRankList = array();
 
  47     protected $exactMatchCache = array();
 
  49     protected $sAllowedTypesSQLList = false;
 
  51     protected $sQuery = false;
 
  52     protected $aStructuredQuery = false;
 
  55     public function __construct(&$oDB)
 
  60     public function setReverseInPlan($bReverse)
 
  62         $this->bReverseInPlan = $bReverse;
 
  65     public function setLanguagePreference($aLangPref)
 
  67         $this->aLangPrefOrder = $aLangPref;
 
  70     public function getMoreUrlParams()
 
  72         if ($this->aStructuredQuery) {
 
  73             $aParams = $this->aStructuredQuery;
 
  75             $aParams = array('q' => $this->sQuery);
 
  78         if ($this->aExcludePlaceIDs) {
 
  79             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
 
  82         if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
 
  83         if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
 
  84         if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
 
  86         if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
 
  87         if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
 
  88         if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
 
  89         if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
 
  90         if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
 
  92         if ($this->fPolygonSimplificationThreshold > 0.0) {
 
  93             $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
 
  96         if ($this->bBoundedSearch) $aParams['bounded'] = '1';
 
  97         if (!$this->bDeDupe) $aParams['dedupe'] = '0';
 
  99         if ($this->aCountryCodes) {
 
 100             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
 
 103         if ($this->aViewBox) {
 
 104             $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
 
 105                                   .','.$this->aViewBox[2].','.$this->aViewBox[1];
 
 111     public function setIncludePolygonAsPoints($b = true)
 
 113         $this->bIncludePolygonAsPoints = $b;
 
 116     public function setIncludePolygonAsText($b = true)
 
 118         $this->bIncludePolygonAsText = $b;
 
 121     public function setIncludePolygonAsGeoJSON($b = true)
 
 123         $this->bIncludePolygonAsGeoJSON = $b;
 
 126     public function setIncludePolygonAsKML($b = true)
 
 128         $this->bIncludePolygonAsKML = $b;
 
 131     public function setIncludePolygonAsSVG($b = true)
 
 133         $this->bIncludePolygonAsSVG = $b;
 
 136     public function setPolygonSimplificationThreshold($f)
 
 138         $this->fPolygonSimplificationThreshold = $f;
 
 141     public function setLimit($iLimit = 10)
 
 143         if ($iLimit > 50) $iLimit = 50;
 
 144         if ($iLimit < 1) $iLimit = 1;
 
 146         $this->iFinalLimit = $iLimit;
 
 147         $this->iLimit = $iLimit + min($iLimit, 10);
 
 150     public function setFeatureType($sFeatureType)
 
 152         switch ($sFeatureType) {
 
 154                 $this->setRankRange(4, 4);
 
 157                 $this->setRankRange(8, 8);
 
 160                 $this->setRankRange(14, 16);
 
 163                 $this->setRankRange(8, 20);
 
 168     public function setRankRange($iMin, $iMax)
 
 170         $this->iMinAddressRank = $iMin;
 
 171         $this->iMaxAddressRank = $iMax;
 
 174     public function setRoute($aRoutePoints, $fRouteWidth)
 
 176         $this->aViewBox = false;
 
 178         $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
 
 180         foreach ($aRoutePoints as $aPoint) {
 
 181             $fPoint = (float)$aPoint;
 
 182             $this->sViewboxCentreSQL .= $sSep.$fPoint;
 
 183             $sSep = ($sSep == ' ') ? ',' : ' ';
 
 185         $this->sViewboxCentreSQL .= ")'::geometry,4326)";
 
 187         $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
 
 188         $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
 
 190         $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
 
 191         $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
 
 194     public function setViewbox($aViewbox)
 
 196         $this->aViewBox = array_map('floatval', $aViewbox);
 
 198         $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
 
 199         $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
 
 200         $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
 
 201         $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
 
 203         if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
 
 204             || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
 
 206             userError("Bad parameter 'viewbox'. Not a box.");
 
 209         $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
 
 210         $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
 
 211         $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
 
 212         $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
 
 213         $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
 
 214         $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
 
 216         $this->sViewboxCentreSQL = false;
 
 217         $this->sViewboxSmallSQL = sprintf(
 
 218             'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
 
 224         $this->sViewboxLargeSQL = sprintf(
 
 225             'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
 
 233     public function setQuery($sQueryString)
 
 235         $this->sQuery = $sQueryString;
 
 236         $this->aStructuredQuery = false;
 
 239     public function getQueryString()
 
 241         return $this->sQuery;
 
 245     public function loadParamArray($oParams)
 
 247         $this->bIncludeAddressDetails
 
 248          = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
 
 249         $this->bIncludeExtraTags
 
 250          = $oParams->getBool('extratags', $this->bIncludeExtraTags);
 
 251         $this->bIncludeNameDetails
 
 252          = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
 
 254         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
 
 255         $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
 
 257         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
 
 258         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
 
 260         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
 
 262         // List of excluded Place IDs - used for more acurate pageing
 
 263         $sExcluded = $oParams->getStringList('exclude_place_ids');
 
 265             foreach ($sExcluded as $iExcludedPlaceID) {
 
 266                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
 267                 if ($iExcludedPlaceID)
 
 268                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
 271             if (isset($aExcludePlaceIDs))
 
 272                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
 
 275         // Only certain ranks of feature
 
 276         $sFeatureType = $oParams->getString('featureType');
 
 277         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
 
 278         if ($sFeatureType) $this->setFeatureType($sFeatureType);
 
 281         $sCountries = $oParams->getStringList('countrycodes');
 
 283             foreach ($sCountries as $sCountryCode) {
 
 284                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
 
 285                     $aCountries[] = strtolower($sCountryCode);
 
 288             if (isset($aCountries))
 
 289                 $this->aCountryCodes = $aCountries;
 
 292         $aViewbox = $oParams->getStringList('viewboxlbrt');
 
 294             if (count($aViewbox) != 4) {
 
 295                 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
 
 297             $this->setViewbox($aViewbox);
 
 299             $aViewbox = $oParams->getStringList('viewbox');
 
 301                 if (count($aViewbox) != 4) {
 
 302                     userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
 
 304                 $this->setViewBox(array(
 
 311                 $aRoute = $oParams->getStringList('route');
 
 312                 $fRouteWidth = $oParams->getFloat('routewidth');
 
 313                 if ($aRoute && $fRouteWidth) {
 
 314                     $this->setRoute($aRoute, $fRouteWidth);
 
 320     public function setQueryFromParams($oParams)
 
 323         $sQuery = $oParams->getString('q');
 
 325             $this->setStructuredQuery(
 
 326                 $oParams->getString('amenity'),
 
 327                 $oParams->getString('street'),
 
 328                 $oParams->getString('city'),
 
 329                 $oParams->getString('county'),
 
 330                 $oParams->getString('state'),
 
 331                 $oParams->getString('country'),
 
 332                 $oParams->getString('postalcode')
 
 334             $this->setReverseInPlan(false);
 
 336             $this->setQuery($sQuery);
 
 340     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
 
 342         $sValue = trim($sValue);
 
 343         if (!$sValue) return false;
 
 344         $this->aStructuredQuery[$sKey] = $sValue;
 
 345         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
 
 346             $this->iMinAddressRank = $iNewMinAddressRank;
 
 347             $this->iMaxAddressRank = $iNewMaxAddressRank;
 
 349         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
 
 353     public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
 
 355         $this->sQuery = false;
 
 358         $this->iMinAddressRank = 0;
 
 359         $this->iMaxAddressRank = 30;
 
 360         $this->aAddressRankList = array();
 
 362         $this->aStructuredQuery = array();
 
 363         $this->sAllowedTypesSQLList = '';
 
 365         $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
 
 366         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
 
 367         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
 
 368         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
 
 369         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
 
 370         $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
 
 371         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
 
 373         if (sizeof($this->aStructuredQuery) > 0) {
 
 374             $this->sQuery = join(', ', $this->aStructuredQuery);
 
 375             if ($this->iMaxAddressRank < 30) {
 
 376                 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
 
 381     public function fallbackStructuredQuery()
 
 383         if (!$this->aStructuredQuery) return false;
 
 385         $aParams = $this->aStructuredQuery;
 
 387         if (sizeof($aParams) == 1) return false;
 
 389         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
 
 391         foreach ($aOrderToFallback as $sType) {
 
 392             if (isset($aParams[$sType])) {
 
 393                 unset($aParams[$sType]);
 
 394                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
 
 402     public function getDetails($aPlaceIDs)
 
 404         //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
 
 405         if (sizeof($aPlaceIDs) == 0) return array();
 
 407         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
 
 409         // Get the details for display (is this a redundant extra step?)
 
 410         $sPlaceIDs = join(',', array_keys($aPlaceIDs));
 
 412         $sImportanceSQL = '';
 
 413         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
 
 414         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
 
 417         $sSQL .= "    osm_type,";
 
 421         $sSQL .= "    admin_level,";
 
 422         $sSQL .= "    rank_search,";
 
 423         $sSQL .= "    rank_address,";
 
 424         $sSQL .= "    min(place_id) AS place_id, ";
 
 425         $sSQL .= "    min(parent_place_id) AS parent_place_id, ";
 
 426         $sSQL .= "    country_code, ";
 
 427         $sSQL .= "    get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
 
 428         $sSQL .= "    get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
 
 429         $sSQL .= "    get_name_by_language(name, ARRAY['ref']) AS ref,";
 
 430         if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
 
 431         if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
 
 432         $sSQL .= "    avg(ST_X(centroid)) AS lon, ";
 
 433         $sSQL .= "    avg(ST_Y(centroid)) AS lat, ";
 
 434         $sSQL .= "    ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
 
 436         $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
 
 438         $sSQL .= "         place_addressline s, ";
 
 439         $sSQL .= "         placex p";
 
 440         $sSQL .= "       WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
 
 441         $sSQL .= "         AND p.place_id = s.address_place_id ";
 
 442         $sSQL .= "         AND s.isaddress ";
 
 443         $sSQL .= "         AND p.importance is not null ";
 
 444         $sSQL .= "    ) AS addressimportance, ";
 
 445         $sSQL .= "    (extratags->'place') AS extra_place ";
 
 446         $sSQL .= " FROM placex";
 
 447         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
 
 449         $sSQL .= "            placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 450         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
 
 451             $sSQL .= "        OR (extratags->'place') = 'city'";
 
 453         if ($this->aAddressRankList) {
 
 454             $sSQL .= "        OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
 
 457         if ($this->sAllowedTypesSQLList) {
 
 458             $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
 
 460         $sSQL .= "    AND linked_place_id is null ";
 
 461         $sSQL .= " GROUP BY ";
 
 462         $sSQL .= "     osm_type, ";
 
 463         $sSQL .= "     osm_id, ";
 
 466         $sSQL .= "     admin_level, ";
 
 467         $sSQL .= "     rank_search, ";
 
 468         $sSQL .= "     rank_address, ";
 
 469         $sSQL .= "     country_code, ";
 
 470         $sSQL .= "     importance, ";
 
 471         if (!$this->bDeDupe) $sSQL .= "place_id,";
 
 472         $sSQL .= "     langaddress, ";
 
 473         $sSQL .= "     placename, ";
 
 475         if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
 
 476         if ($this->bIncludeNameDetails) $sSQL .= "name, ";
 
 477         $sSQL .= "     extratags->'place' ";
 
 482         $sSQL .= "  'P' as osm_type,";
 
 483         $sSQL .= "  (SELECT osm_id from placex p WHERE p.place_id = parent_place_id) as osm_id,";
 
 484         $sSQL .= "  'place' as class, 'postcode' as type,";
 
 485         $sSQL .= "  null as admin_level, rank_search, rank_address,";
 
 486         $sSQL .= "  place_id, parent_place_id, country_code,";
 
 487         $sSQL .= "  get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
 
 488         $sSQL .= "  postcode as placename,";
 
 489         $sSQL .= "  postcode as ref,";
 
 490         if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
 
 491         if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
 
 492         $sSQL .= "  ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
 
 493         $sSQL .=    $sImportanceSQL."(0.75-(rank_search::float/40)) AS importance, ";
 
 495         $sSQL .= "     SELECT max(p.importance*(p.rank_address+2))";
 
 497         $sSQL .= "       place_addressline s, ";
 
 498         $sSQL .= "       placex p";
 
 499         $sSQL .= "     WHERE s.place_id = parent_place_id";
 
 500         $sSQL .= "       AND p.place_id = s.address_place_id ";
 
 501         $sSQL .= "       AND s.isaddress";
 
 502         $sSQL .= "       AND p.importance is not null";
 
 503         $sSQL .= "  ) AS addressimportance, ";
 
 504         $sSQL .= "  null AS extra_place ";
 
 505         $sSQL .= "FROM location_postcode";
 
 506         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
 
 508         if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
 
 509             // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
 
 510             // with start- and endnumber, the common osm housenumbers are usually saved as points
 
 513             $length = count($aPlaceIDs);
 
 514             foreach ($aPlaceIDs as $placeID => $housenumber) {
 
 516                 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
 
 517                 if ($i<$length) $sHousenumbers .= ", ";
 
 520             if (CONST_Use_US_Tiger_Data) {
 
 521                 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
 
 524                 $sSQL .= "     'T' AS osm_type, ";
 
 525                 $sSQL .= "     (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
 
 526                 $sSQL .= "     'place' AS class, ";
 
 527                 $sSQL .= "     'house' AS type, ";
 
 528                 $sSQL .= "     null AS admin_level, ";
 
 529                 $sSQL .= "     30 AS rank_search, ";
 
 530                 $sSQL .= "     30 AS rank_address, ";
 
 531                 $sSQL .= "     min(place_id) AS place_id, ";
 
 532                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
 
 533                 $sSQL .= "     'us' AS country_code, ";
 
 534                 $sSQL .= "     get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
 
 535                 $sSQL .= "     null AS placename, ";
 
 536                 $sSQL .= "     null AS ref, ";
 
 537                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
 
 538                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
 
 539                 $sSQL .= "     avg(st_x(centroid)) AS lon, ";
 
 540                 $sSQL .= "     avg(st_y(centroid)) AS lat,";
 
 541                 $sSQL .= "     ".$sImportanceSQL."-1.15 AS importance, ";
 
 543                 $sSQL .= "        SELECT max(p.importance*(p.rank_address+2))";
 
 545                 $sSQL .= "          place_addressline s, ";
 
 546                 $sSQL .= "          placex p";
 
 547                 $sSQL .= "        WHERE s.place_id = min(blub.parent_place_id)";
 
 548                 $sSQL .= "          AND p.place_id = s.address_place_id ";
 
 549                 $sSQL .= "          AND s.isaddress";
 
 550                 $sSQL .= "          AND p.importance is not null";
 
 551                 $sSQL .= "     ) AS addressimportance, ";
 
 552                 $sSQL .= "     null AS extra_place ";
 
 554                 $sSQL .= "     SELECT place_id, ";    // interpolate the Tiger housenumbers here
 
 555                 $sSQL .= "         ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
 
 556                 $sSQL .= "         parent_place_id, ";
 
 557                 $sSQL .= "         housenumber_for_place";
 
 559                 $sSQL .= "            location_property_tiger ";
 
 560                 $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
 
 562                 $sSQL .= "         housenumber_for_place>=0";
 
 563                 $sSQL .= "         AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
 
 564                 $sSQL .= " ) AS blub"; //postgres wants an alias here
 
 565                 $sSQL .= " GROUP BY";
 
 566                 $sSQL .= "      place_id, ";
 
 567                 $sSQL .= "      housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
 
 568                 if (!$this->bDeDupe) $sSQL .= ", place_id ";
 
 571             // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
 
 574             $sSQL .= "  'W' AS osm_type, ";
 
 575             $sSQL .= "  osm_id, ";
 
 576             $sSQL .= "  'place' AS class, ";
 
 577             $sSQL .= "  'house' AS type, ";
 
 578             $sSQL .= "  null AS admin_level, ";
 
 579             $sSQL .= "  30 AS rank_search, ";
 
 580             $sSQL .= "  30 AS rank_address, ";
 
 581             $sSQL .= "  min(place_id) as place_id, ";
 
 582             $sSQL .= "  min(parent_place_id) AS parent_place_id, ";
 
 583             $sSQL .= "  country_code, ";
 
 584             $sSQL .= "  get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
 
 585             $sSQL .= "  null AS placename, ";
 
 586             $sSQL .= "  null AS ref, ";
 
 587             if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
 
 588             if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
 
 589             $sSQL .= "  AVG(st_x(centroid)) AS lon, ";
 
 590             $sSQL .= "  AVG(st_y(centroid)) AS lat, ";
 
 591             $sSQL .= "  ".$sImportanceSQL."-0.1 AS importance, ";  // slightly smaller than the importance for normal houses with rank 30, which is 0
 
 594             $sSQL .= "       MAX(p.importance*(p.rank_address+2)) ";
 
 596             $sSQL .= "       place_addressline s, ";
 
 597             $sSQL .= "       placex p";
 
 598             $sSQL .= "     WHERE s.place_id = min(blub.parent_place_id) ";
 
 599             $sSQL .= "       AND p.place_id = s.address_place_id ";
 
 600             $sSQL .= "       AND s.isaddress ";
 
 601             $sSQL .= "       AND p.importance is not null";
 
 602             $sSQL .= "  ) AS addressimportance,";
 
 603             $sSQL .= "  null AS extra_place ";
 
 606             $sSQL .= "         osm_id, ";
 
 607             $sSQL .= "         place_id, ";
 
 608             $sSQL .= "         country_code, ";
 
 609             $sSQL .= "         CASE ";             // interpolate the housenumbers here
 
 610             $sSQL .= "           WHEN startnumber != endnumber ";
 
 611             $sSQL .= "           THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
 
 612             $sSQL .= "           ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
 
 613             $sSQL .= "         END as centroid, ";
 
 614             $sSQL .= "         parent_place_id, ";
 
 615             $sSQL .= "         housenumber_for_place ";
 
 617             $sSQL .= "            location_property_osmline ";
 
 618             $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
 
 620             $sSQL .= "     WHERE housenumber_for_place>=0 ";
 
 621             $sSQL .= "       AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
 
 622             $sSQL .= "  ) as blub"; //postgres wants an alias here
 
 623             $sSQL .= "  GROUP BY ";
 
 624             $sSQL .= "    osm_id, ";
 
 625             $sSQL .= "    place_id, ";
 
 626             $sSQL .= "    housenumber_for_place, ";
 
 627             $sSQL .= "    country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
 
 628             if (!$this->bDeDupe) $sSQL .= ", place_id ";
 
 630             if (CONST_Use_Aux_Location_data) {
 
 633                 $sSQL .= "     'L' AS osm_type, ";
 
 634                 $sSQL .= "     place_id AS osm_id, ";
 
 635                 $sSQL .= "     'place' AS class,";
 
 636                 $sSQL .= "     'house' AS type, ";
 
 637                 $sSQL .= "     null AS admin_level, ";
 
 638                 $sSQL .= "     0 AS rank_search,";
 
 639                 $sSQL .= "     0 AS rank_address, ";
 
 640                 $sSQL .= "     min(place_id) AS place_id,";
 
 641                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
 
 642                 $sSQL .= "     'us' AS country_code, ";
 
 643                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
 
 644                 $sSQL .= "     null AS placename, ";
 
 645                 $sSQL .= "     null AS ref, ";
 
 646                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
 
 647                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
 
 648                 $sSQL .= "     avg(ST_X(centroid)) AS lon, ";
 
 649                 $sSQL .= "     avg(ST_Y(centroid)) AS lat, ";
 
 650                 $sSQL .= "     ".$sImportanceSQL."-1.10 AS importance, ";
 
 652                 $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
 
 654                 $sSQL .= "          place_addressline s, ";
 
 655                 $sSQL .= "          placex p";
 
 656                 $sSQL .= "       WHERE s.place_id = min(location_property_aux.parent_place_id)";
 
 657                 $sSQL .= "         AND p.place_id = s.address_place_id ";
 
 658                 $sSQL .= "         AND s.isaddress";
 
 659                 $sSQL .= "         AND p.importance is not null";
 
 660                 $sSQL .= "     ) AS addressimportance, ";
 
 661                 $sSQL .= "     null AS extra_place ";
 
 662                 $sSQL .= "  FROM location_property_aux ";
 
 663                 $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
 
 664                 $sSQL .= "    AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 665                 $sSQL .= "  GROUP BY ";
 
 666                 $sSQL .= "     place_id, ";
 
 667                 if (!$this->bDeDupe) $sSQL .= "place_id, ";
 
 668                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
 
 672         $sSQL .= " order by importance desc";
 
 677         $aSearchResults = chksql(
 
 678             $this->oDB->getAll($sSQL),
 
 679             "Could not get details for place."
 
 682         return $aSearchResults;
 
 685     public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
 
 688              Calculate all searches using aValidTokens i.e.
 
 689              'Wodsworth Road, Sheffield' =>
 
 693              0      1       (wodsworth)(road)
 
 696              Score how good the search is so they can be ordered
 
 698         foreach ($aPhrases as $iPhrase => $aPhrase) {
 
 699             $aNewPhraseSearches = array();
 
 700             if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
 
 701             else $sPhraseType = '';
 
 703             foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
 
 704                 // Too many permutations - too expensive
 
 705                 if ($iWordSet > 120) break;
 
 707                 $aWordsetSearches = $aSearches;
 
 709                 // Add all words from this wordset
 
 710                 foreach ($aWordset as $iToken => $sToken) {
 
 711                     //echo "<br><b>$sToken</b>";
 
 712                     $aNewWordsetSearches = array();
 
 714                     foreach ($aWordsetSearches as $aCurrentSearch) {
 
 716                         //var_dump($aCurrentSearch);
 
 719                         // If the token is valid
 
 720                         if (isset($aValidTokens[' '.$sToken])) {
 
 721                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
 
 722                                 $aSearch = $aCurrentSearch;
 
 723                                 $aSearch['iSearchRank']++;
 
 724                                 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
 
 725                                     if ($aSearch['sCountryCode'] === false) {
 
 726                                         $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
 727                                         // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
 
 728                                         if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
 
 729                                             $aSearch['iSearchRank'] += 5;
 
 731                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 733                                 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
 
 734                                     if ($aSearch['oNear'] === false) {
 
 735                                         $aSearch['oNear'] = new NearPoint(
 
 738                                             $aSearchTerm['radius']
 
 740                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 742                                 } elseif ($sPhraseType == 'postalcode' || ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode')) {
 
 743                                     // 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
 
 744                                     if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
 
 745                                         // If we have structured search or this is the first term,
 
 746                                         // make the postcode the primary search element.
 
 747                                         if ($aSearchTerm['operator'] == '' && ($sPhraseType == 'postalcode' || sizeof($aSearch['aName']) == 0)) {
 
 748                                             $aNewSearch = $aSearch;
 
 749                                             $aNewSearch['sOperator'] = 'postcode';
 
 750                                             $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
 
 751                                             $aNewSearch['aName'][$aSearchTerm['word_id']] = substr($aSearchTerm['word_token'], 1);
 
 752                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
 
 755                                         // If we have a structured search or this is not the first term,
 
 756                                         // add the postcode as an addendum.
 
 757                                         if ($sPhraseType == 'postalcode' || sizeof($aSearch['aName'])) {
 
 758                                             $aSearch['sPostcode'] = substr($aSearchTerm['word_token'], 1);
 
 759                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 762                                 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
 
 763                                     if ($aSearch['sHouseNumber'] === '') {
 
 764                                         $aSearch['sHouseNumber'] = $sToken;
 
 765                                         // sanity check: if the housenumber is not mainly made
 
 766                                         // up of numbers, add a penalty
 
 767                                         if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
 
 768                                         // also housenumbers should appear in the first or second phrase
 
 769                                         if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
 
 770                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 772                                         // Fall back to not searching for this item (better than nothing)
 
 773                                         $aSearch = $aCurrentSearch;
 
 774                                         $aSearch['iSearchRank'] += 1;
 
 775                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 778                                 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
 
 779                                     // require a normalized exact match of the term
 
 780                                     // if we have the normalizer version of the query
 
 782                                     if ($aSearch['sClass'] === ''
 
 783                                         && ($sNormQuery === null || !($aSearchTerm['word'] && strpos($sNormQuery, $aSearchTerm['word']) === false))) {
 
 784                                         $aSearch['sClass'] = $aSearchTerm['class'];
 
 785                                         $aSearch['sType'] = $aSearchTerm['type'];
 
 786                                         if ($aSearchTerm['operator'] == '') {
 
 787                                             $aSearch['sOperator'] = sizeof($aSearch['aName']) ? 'name' :  'near';
 
 788                                             $aSearch['iSearchRank'] += 2;
 
 790                                             $aSearch['sOperator'] = 'near'; // near = in for the moment
 
 793                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 795                                 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
 
 796                                     if (sizeof($aSearch['aName'])) {
 
 797                                         if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
 
 798                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 800                                             $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 801                                             $aSearch['iSearchRank'] += 1000; // skip;
 
 804                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 805                                         //$aSearch['iNamePhrase'] = $iPhrase;
 
 807                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 811                         // Look for partial matches.
 
 812                         // Note that there is no point in adding country terms here
 
 813                         // because country are omitted in the address.
 
 814                         if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
 
 815                             // Allow searching for a word - but at extra cost
 
 816                             foreach ($aValidTokens[$sToken] as $aSearchTerm) {
 
 817                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
 
 818                                     if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
 
 819                                         $aSearch = $aCurrentSearch;
 
 820                                         $aSearch['iSearchRank'] += 1;
 
 821                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
 
 822                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 823                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 824                                         } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
 
 825                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 826                                             $aSearch['iSearchRank'] += 1;
 
 827                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 828                                             foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
 
 829                                                 if (empty($aSearchTermToken['country_code'])
 
 830                                                     && empty($aSearchTermToken['lat'])
 
 831                                                     && empty($aSearchTermToken['class'])
 
 833                                                     $aSearch = $aCurrentSearch;
 
 834                                                     $aSearch['iSearchRank'] += 1;
 
 835                                                     $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
 
 836                                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 840                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 841                                             if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
 
 842                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 846                                     if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
 
 847                                         $aSearch = $aCurrentSearch;
 
 848                                         $aSearch['iSearchRank'] += 1;
 
 849                                         if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
 
 850                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
 
 851                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
 
 852                                             $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 854                                             $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
 
 856                                         $aSearch['iNamePhrase'] = $iPhrase;
 
 857                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
 
 862                             // Allow skipping a word - but at EXTREAM cost
 
 863                             //$aSearch = $aCurrentSearch;
 
 864                             //$aSearch['iSearchRank']+=100;
 
 865                             //$aNewWordsetSearches[] = $aSearch;
 
 869                     usort($aNewWordsetSearches, 'bySearchRank');
 
 870                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 872                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 874                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 875                 usort($aNewPhraseSearches, 'bySearchRank');
 
 877                 $aSearchHash = array();
 
 878                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
 
 879                     $sHash = serialize($aSearch);
 
 880                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
 
 881                     else $aSearchHash[$sHash] = 1;
 
 884                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 887             // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 888             $aGroupedSearches = array();
 
 889             foreach ($aNewPhraseSearches as $aSearch) {
 
 890                 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
 
 891                     if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
 892                     $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
 895             ksort($aGroupedSearches);
 
 898             $aSearches = array();
 
 899             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
 
 900                 $iSearchCount += sizeof($aNewSearches);
 
 901                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 902                 if ($iSearchCount > 50) break;
 
 905             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 907         return $aGroupedSearches;
 
 910     /* Perform the actual query lookup.
 
 912         Returns an ordered list of results, each with the following fields:
 
 913             osm_type: type of corresponding OSM object
 
 917                         P - postcode (internally computed)
 
 918             osm_id: id of corresponding OSM object
 
 919             class: general object class (corresponds to tag key of primary OSM tag)
 
 920             type: subclass of object (corresponds to tag value of primary OSM tag)
 
 921             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
 
 922             rank_search: rank in search hierarchy
 
 923                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
 
 924             rank_address: rank in address hierarchy (determines orer in address)
 
 925             place_id: internal key (may differ between different instances)
 
 926             country_code: ISO country code
 
 927             langaddress: localized full address
 
 928             placename: localized name of object
 
 929             ref: content of ref tag (if available)
 
 932             importance: importance of place based on Wikipedia link count
 
 933             addressimportance: cumulated importance of address elements
 
 934             extra_place: type of place (for admin boundaries, if there is a place tag)
 
 935             aBoundingBox: bounding Box
 
 936             label: short description of the object class/type (English only)
 
 937             name: full name (currently the same as langaddress)
 
 938             foundorder: secondary ordering for places with same importance
 
 942     public function lookup()
 
 944         if (!$this->sQuery && !$this->aStructuredQuery) return array();
 
 946         $oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
 
 947         if ($oNormalizer !== null) {
 
 948             $sNormQuery = $oNormalizer->transliterate($this->sQuery);
 
 953         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
 
 954         $sCountryCodesSQL = false;
 
 955         if ($this->aCountryCodes) {
 
 956             $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
 
 959         $sQuery = $this->sQuery;
 
 960         if (!preg_match('//u', $sQuery)) {
 
 961             userError("Query string is not UTF-8 encoded.");
 
 964         // Conflicts between US state abreviations and various words for 'the' in different languages
 
 965         if (isset($this->aLangPrefOrder['name:en'])) {
 
 966             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
 
 967             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
 
 968             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
 
 971         $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
 
 972         if ($this->sViewboxCentreSQL) {
 
 973             // For complex viewboxes (routes) precompute the bounding geometry
 
 975                 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
 
 976                 "Could not get small viewbox"
 
 978             $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
 
 981                 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
 
 982                 "Could not get large viewbox"
 
 984             $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
 
 987         // Do we have anything that looks like a lat/lon pair?
 
 989         if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
 
 990             $oNearPoint = $aLooksLike['pt'];
 
 991             $sQuery = $aLooksLike['query'];
 
 994         $aSearchResults = array();
 
 995         if ($sQuery || $this->aStructuredQuery) {
 
 996             // Start with a blank search
 
1000                            'iNamePhrase' => -1,
 
1001                            'sCountryCode' => false,
 
1003                            'aAddress' => array(),
 
1004                            'aFullNameAddress' => array(),
 
1005                            'aNameNonSearch' => array(),
 
1006                            'aAddressNonSearch' => array(),
 
1008                            'aFeatureName' => array(),
 
1011                            'sHouseNumber' => '',
 
1013                            'oNear' => $oNearPoint
 
1017             // Any 'special' terms in the search?
 
1018             $bSpecialTerms = false;
 
1019             preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
1020             $aSpecialTerms = array();
 
1021             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
 
1022                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
1023                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
 
1026             preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
 
1027             $aSpecialTerms = array();
 
1028             if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
 
1029                 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
 
1030                 unset($this->aStructuredQuery['amenity']);
 
1033             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
 
1034                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
1035                 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
 
1036                 $sSQL = 'SELECT * ';
 
1038                 $sSQL .= '   SELECT word_id, word_token, word, class, type, country_code, operator';
 
1039                 $sSQL .= '   FROM word ';
 
1040                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
 
1042                 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
 
1043                 $sSQL .= ' OR country_code is not null';
 
1044                 if (CONST_Debug) var_Dump($sSQL);
 
1045                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
 
1046                 $aNewSearches = array();
 
1047                 foreach ($aSearches as $aSearch) {
 
1048                     foreach ($aSearchWords as $aSearchTerm) {
 
1049                         $aNewSearch = $aSearch;
 
1050                         if ($aSearchTerm['country_code']) {
 
1051                             $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
 
1052                             $aNewSearches[] = $aNewSearch;
 
1053                             $bSpecialTerms = true;
 
1055                         if ($aSearchTerm['class']) {
 
1056                             $aNewSearch['sClass'] = $aSearchTerm['class'];
 
1057                             $aNewSearch['sType'] = $aSearchTerm['type'];
 
1058                             $aNewSearches[] = $aNewSearch;
 
1059                             $bSpecialTerms = true;
 
1063                 $aSearches = $aNewSearches;
 
1066             // Split query into phrases
 
1067             // Commas are used to reduce the search space by indicating where phrases split
 
1068             if ($this->aStructuredQuery) {
 
1069                 $aPhrases = $this->aStructuredQuery;
 
1070                 $bStructuredPhrases = true;
 
1072                 $aPhrases = explode(',', $sQuery);
 
1073                 $bStructuredPhrases = false;
 
1076             // Convert each phrase to standard form
 
1077             // Create a list of standard words
 
1078             // Get all 'sets' of words
 
1079             // Generate a complete list of all
 
1081             foreach ($aPhrases as $iPhrase => $sPhrase) {
 
1083                     $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
 
1084                     "Cannot normalize query string (is it a UTF-8 string?)"
 
1086                 if (trim($aPhrase['string'])) {
 
1087                     $aPhrases[$iPhrase] = $aPhrase;
 
1088                     $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
 
1089                     $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
 
1090                     $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
1092                     unset($aPhrases[$iPhrase]);
 
1096             // Reindex phrases - we make assumptions later on that they are numerically keyed in order
 
1097             $aPhraseTypes = array_keys($aPhrases);
 
1098             $aPhrases = array_values($aPhrases);
 
1100             if (sizeof($aTokens)) {
 
1101                 // Check which tokens we have, get the ID numbers
 
1102                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
 
1103                 $sSQL .= ' FROM word ';
 
1104                 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
 
1106                 if (CONST_Debug) var_Dump($sSQL);
 
1108                 $aValidTokens = array();
 
1109                 if (sizeof($aTokens)) {
 
1110                     $aDatabaseWords = chksql(
 
1111                         $this->oDB->getAll($sSQL),
 
1112                         "Could not get word tokens."
 
1115                     $aDatabaseWords = array();
 
1117                 $aPossibleMainWordIDs = array();
 
1118                 $aWordFrequencyScores = array();
 
1119                 foreach ($aDatabaseWords as $aToken) {
 
1120                     // Very special case - require 2 letter country param to match the country code found
 
1121                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
 
1122                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
 
1127                     if (isset($aValidTokens[$aToken['word_token']])) {
 
1128                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
1130                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
1132                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
 
1133                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
 
1135                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
1137                 // Try and calculate GB postcodes we might be missing
 
1138                 foreach ($aTokens as $sToken) {
 
1139                     // Source of gb postcodes is now definitive - always use
 
1140                     if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
 
1141                         if (substr($aData[1], -2, 1) != ' ') {
 
1142                             $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
 
1143                             $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
 
1145                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
 
1146                         if ($aGBPostcodeLocation) {
 
1147                             $aValidTokens[$sToken] = $aGBPostcodeLocation;
 
1149                     } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
 
1150                         // US ZIP+4 codes - if there is no token,
 
1151                         // merge in the 5-digit ZIP code
 
1152                         if (isset($aValidTokens[$aData[1]])) {
 
1153                             foreach ($aValidTokens[$aData[1]] as $aToken) {
 
1154                                 if (!$aToken['class']) {
 
1155                                     if (isset($aValidTokens[$sToken])) {
 
1156                                         $aValidTokens[$sToken][] = $aToken;
 
1158                                         $aValidTokens[$sToken] = array($aToken);
 
1166                 foreach ($aTokens as $sToken) {
 
1167                     // Unknown single word token with a number - assume it is a house number
 
1168                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
 
1169                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
 
1173                 // Any words that have failed completely?
 
1174                 // TODO: suggestions
 
1176                 // Start the search process
 
1177                 // array with: placeid => -1 | tiger-housenumber
 
1178                 $aResultPlaceIDs = array();
 
1180                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
 
1182                 if ($this->bReverseInPlan) {
 
1183                     // Reverse phrase array and also reverse the order of the wordsets in
 
1184                     // the first and final phrase. Don't bother about phrases in the middle
 
1185                     // because order in the address doesn't matter.
 
1186                     $aPhrases = array_reverse($aPhrases);
 
1187                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
 
1188                     if (sizeof($aPhrases) > 1) {
 
1189                         $aFinalPhrase = end($aPhrases);
 
1190                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
 
1192                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
 
1194                     foreach ($aGroupedSearches as $aSearches) {
 
1195                         foreach ($aSearches as $aSearch) {
 
1196                             if ($aSearch['iSearchRank'] < $this->iMaxRank) {
 
1197                                 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
 
1198                                 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
1203                     $aGroupedSearches = $aReverseGroupedSearches;
 
1204                     ksort($aGroupedSearches);
 
1207                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
1208                 $aGroupedSearches = array();
 
1209                 foreach ($aSearches as $aSearch) {
 
1210                     if ($aSearch['iSearchRank'] < $this->iMaxRank) {
 
1211                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
 
1212                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
 
1215                 ksort($aGroupedSearches);
 
1218             if (CONST_Debug) var_Dump($aGroupedSearches);
 
1219             if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
 
1220                 $aCopyGroupedSearches = $aGroupedSearches;
 
1221                 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
 
1222                     foreach ($aSearches as $iSearch => $aSearch) {
 
1223                         $aReductionsList = array($aSearch['aAddress']);
 
1224                         $iSearchRank = $aSearch['iSearchRank'];
 
1225                         while (sizeof($aReductionsList) > 0) {
 
1227                             if ($iSearchRank > iMaxRank) break 3;
 
1228                             $aNewReductionsList = array();
 
1229                             foreach ($aReductionsList as $aReductionsWordList) {
 
1230                                 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
 
1231                                     $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
 
1232                                     $aReverseSearch = $aSearch;
 
1233                                     $aSearch['aAddress'] = $aReductionsWordListResult;
 
1234                                     $aSearch['iSearchRank'] = $iSearchRank;
 
1235                                     $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
 
1236                                     if (sizeof($aReductionsWordListResult) > 0) {
 
1237                                         $aNewReductionsList[] = $aReductionsWordListResult;
 
1241                             $aReductionsList = $aNewReductionsList;
 
1245                 ksort($aGroupedSearches);
 
1248             // Filter out duplicate searches
 
1249             $aSearchHash = array();
 
1250             foreach ($aGroupedSearches as $iGroup => $aSearches) {
 
1251                 foreach ($aSearches as $iSearch => $aSearch) {
 
1252                     $sHash = serialize($aSearch);
 
1253                     if (isset($aSearchHash[$sHash])) {
 
1254                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
1255                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
1257                         $aSearchHash[$sHash] = 1;
 
1262             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
1266             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
 
1268                 foreach ($aSearches as $aSearch) {
 
1270                     $searchedHousenumber = -1;
 
1272                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
 
1273                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
 
1275                     if ($sCountryCodesSQL && $aSearch['sCountryCode'] && !in_array($aSearch['sCountryCode'], $this->aCountryCodes)) {
 
1279                     // No location term?
 
1280                     if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['oNear']) {
 
1281                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
 
1282                             // Just looking for a country by code - look it up
 
1283                             if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
 
1284                                 $sSQL = "SELECT place_id FROM placex WHERE country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
 
1285                                 if ($bBoundingBoxSearch)
 
1286                                     $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
 
1287                                 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
 
1288                                 if (CONST_Debug) var_dump($sSQL);
 
1289                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1291                                 $aPlaceIDs = array();
 
1294                             if (!$bBoundingBoxSearch && !$aSearch['oNear']) continue;
 
1295                             if (!$aSearch['sClass']) continue;
 
1297                             $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
 
1298                             if (chksql($this->oDB->getOne($sSQL))) {
 
1299                                 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
1300                                 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
 
1301                                 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
 
1302                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
 
1303                                 if (sizeof($this->aExcludePlaceIDs)) {
 
1304                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1306                                 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
 
1307                                 $sSQL .= " limit $this->iLimit";
 
1308                                 if (CONST_Debug) var_dump($sSQL);
 
1309                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1311                                 // If excluded place IDs are given, it is fair to assume that
 
1312                                 // there have been results in the small box, so no further
 
1313                                 // expansion in that case.
 
1314                                 // Also don't expand if bounded results were requested.
 
1315                                 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
 
1316                                     $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
 
1317                                     if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
 
1318                                     $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
 
1319                                     if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
 
1320                                     if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
 
1321                                     $sSQL .= " LIMIT $this->iLimit";
 
1322                                     if (CONST_Debug) var_dump($sSQL);
 
1323                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1326                                 $sSQL = "SELECT place_id ";
 
1327                                 $sSQL .= "FROM placex ";
 
1328                                 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
 
1329                                 $sSQL .= "  AND type='".$aSearch['sType']."'";
 
1330                                 $sSQL .= "  AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
 
1331                                 $sSQL .= "  AND linked_place_id is null";
 
1332                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
 
1333                                 if ($this->sViewboxCentreSQL)   $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
 
1334                                 $sSQL .= " LIMIT $this->iLimit";
 
1335                                 if (CONST_Debug) var_dump($sSQL);
 
1336                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1339                     } elseif ($aSearch['oNear'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
 
1340                         // If a coordinate is given, the search must either
 
1341                         // be for a name or a special search. Ignore everythin else.
 
1342                         $aPlaceIDs = array();
 
1343                     } elseif ($aSearch['sOperator'] == 'postcode') {
 
1344                         $sSQL  = "SELECT p.place_id FROM location_postcode p ";
 
1345                         if (sizeof($aSearch['aAddress'])) {
 
1346                             $sSQL .= ", search_name s ";
 
1347                             $sSQL .= "WHERE s.place_id = p.parent_place_id ";
 
1348                             $sSQL .= "AND array_cat(s.nameaddress_vector, s.name_vector) @> ARRAY[".join($aSearch['aAddress'], ",")."] AND ";
 
1352                         $sSQL .= "p.postcode = '".pg_escape_string(reset($aSearch['aName']))."'";
 
1353                         if ($aSearch['sCountryCode']) {
 
1354                             $sSQL .= " AND p.country_code = '".$aSearch['sCountryCode']."'";
 
1355                         } elseif ($sCountryCodesSQL) {
 
1356                             $sSQL .= " AND p.country_code in ($sCountryCodesSQL)";
 
1358                         $sSQL .= " LIMIT $this->iLimit";
 
1359                         if (CONST_Debug) var_dump($sSQL);
 
1360                         $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1362                         $aPlaceIDs = array();
 
1364                         // First we need a position, either aName or fLat or both
 
1368                         if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
 
1369                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
 
1372                             $aOrder[0] .= "   EXISTS(";
 
1373                             $aOrder[0] .= "     SELECT place_id ";
 
1374                             $aOrder[0] .= "     FROM placex ";
 
1375                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
 
1376                             $aOrder[0] .= "       AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
 
1377                             $aOrder[0] .= "     LIMIT 1";
 
1378                             $aOrder[0] .= "   ) ";
 
1379                             // also housenumbers from interpolation lines table are needed
 
1380                             $aOrder[0] .= "   OR EXISTS(";
 
1381                             $aOrder[0] .= "     SELECT place_id ";
 
1382                             $aOrder[0] .= "     FROM location_property_osmline ";
 
1383                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
 
1384                             $aOrder[0] .= "       AND startnumber is not NULL";
 
1385                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
 
1386                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
 
1387                             $aOrder[0] .= "     LIMIT 1";
 
1390                             $aOrder[0] .= " DESC";
 
1393                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
 
1394                         // they might be right - but they are just too darned expensive to run
 
1395                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
 
1396                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
 
1397                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
 
1398                             // For infrequent name terms disable index usage for address
 
1399                             if (CONST_Search_NameOnlySearchFrequencyThreshold
 
1400                                 && sizeof($aSearch['aName']) == 1
 
1401                                 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
 
1403                                 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
 
1405                                 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
 
1406                                 if (sizeof($aSearch['aAddressNonSearch'])) {
 
1407                                     $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
 
1411                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
 
1412                         if ($aSearch['sHouseNumber']) {
 
1413                             $aTerms[] = "address_rank between 16 and 27";
 
1415                             if ($this->iMinAddressRank > 0) {
 
1416                                 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
 
1418                             if ($this->iMaxAddressRank < 30) {
 
1419                                 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
 
1422                         if ($aSearch['oNear']) {
 
1423                             $aTerms[] = $aSearch['oNear']->withinSQL('centroid');
 
1425                             $aOrder[] = $aSearch['oNear']->distanceSQL('centroid');
 
1426                         } elseif ($aSearch['sPostcode']) {
 
1427                             $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$aSearch['sPostcode']."')";
 
1429                         if (sizeof($this->aExcludePlaceIDs)) {
 
1430                             $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1432                         if ($sCountryCodesSQL) {
 
1433                             $aTerms[] = "country_code in ($sCountryCodesSQL)";
 
1436                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
 
1438                             $aOrder[] = $oNearPoint->distanceSQL('centroid');
 
1441                         if ($aSearch['sHouseNumber']) {
 
1442                             $sImportanceSQL = '- abs(26 - address_rank) + 3';
 
1444                             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
 
1446                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
 
1447                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
 
1449                         $aOrder[] = "$sImportanceSQL DESC";
 
1450                         if (sizeof($aSearch['aFullNameAddress'])) {
 
1451                             $sExactMatchSQL = ' ( ';
 
1452                             $sExactMatchSQL .= '   SELECT count(*) FROM ( ';
 
1453                             $sExactMatchSQL .= '      SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
 
1454                             $sExactMatchSQL .= '      INTERSECT ';
 
1455                             $sExactMatchSQL .= '      SELECT unnest(nameaddress_vector)';
 
1456                             $sExactMatchSQL .= '   ) s';
 
1457                             $sExactMatchSQL .= ') as exactmatch';
 
1458                             $aOrder[] = 'exactmatch DESC';
 
1460                             $sExactMatchSQL = '0::int as exactmatch';
 
1463                         if (sizeof($aTerms)) {
 
1464                             $sSQL = "SELECT place_id, ";
 
1465                             $sSQL .= $sExactMatchSQL;
 
1466                             $sSQL .= " FROM search_name";
 
1467                             $sSQL .= " WHERE ".join(' and ', $aTerms);
 
1468                             $sSQL .= " ORDER BY ".join(', ', $aOrder);
 
1469                             if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
 
1470                                 $sSQL .= " LIMIT 20";
 
1471                             } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
 
1472                                 $sSQL .= " LIMIT 1";
 
1474                                 $sSQL .= " LIMIT ".$this->iLimit;
 
1477                             if (CONST_Debug) var_dump($sSQL);
 
1478                             $aViewBoxPlaceIDs = chksql(
 
1479                                 $this->oDB->getAll($sSQL),
 
1480                                 "Could not get places for search terms."
 
1482                             //var_dump($aViewBoxPlaceIDs);
 
1483                             // Did we have an viewbox matches?
 
1484                             $aPlaceIDs = array();
 
1485                             $bViewBoxMatch = false;
 
1486                             foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
 
1487                                 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
 
1488                                 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
 
1489                                 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
 
1490                                 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
 
1491                                 $aPlaceIDs[] = $aViewBoxRow['place_id'];
 
1492                                 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
 
1495                         //var_Dump($aPlaceIDs);
 
1498                         //now search for housenumber, if housenumber provided
 
1499                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
 
1500                             $searchedHousenumber = intval($aSearch['sHouseNumber']);
 
1501                             $aRoadPlaceIDs = $aPlaceIDs;
 
1502                             $sPlaceIDs = join(',', $aPlaceIDs);
 
1504                             // Now they are indexed, look for a house attached to a street we found
 
1505                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
 
1506                             $sSQL = "SELECT place_id FROM placex ";
 
1507                             $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
1508                             if (sizeof($this->aExcludePlaceIDs)) {
 
1509                                 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1511                             $sSQL .= " LIMIT $this->iLimit";
 
1512                             if (CONST_Debug) var_dump($sSQL);
 
1513                             $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1515                             // if nothing found, search in the interpolation line table
 
1516                             if (!sizeof($aPlaceIDs)) {
 
1517                                 // do we need to use transliteration and the regex for housenumbers???
 
1518                                 //new query for lines, not housenumbers anymore
 
1519                                 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
 
1520                                 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
 
1521                                 if ($searchedHousenumber%2 == 0) {
 
1522                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
 
1523                                     $sSQL .= "interpolationtype='even'";
 
1525                                     //look for housenumber in streets with interpolationtype odd or all
 
1526                                     $sSQL .= "interpolationtype='odd'";
 
1528                                 $sSQL .= " or interpolationtype='all') and ";
 
1529                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
 
1530                                 $sSQL .= $searchedHousenumber."<=endnumber";
 
1532                                 if (sizeof($this->aExcludePlaceIDs)) {
 
1533                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1535                                 //$sSQL .= " limit $this->iLimit";
 
1536                                 if (CONST_Debug) var_dump($sSQL);
 
1538                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
 
1541                             // If nothing found try the aux fallback table
 
1542                             if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
 
1543                                 $sSQL = "SELECT place_id FROM location_property_aux ";
 
1544                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
 
1545                                 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
 
1546                                 if (sizeof($this->aExcludePlaceIDs)) {
 
1547                                     $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1549                                 //$sSQL .= " limit $this->iLimit";
 
1550                                 if (CONST_Debug) var_dump($sSQL);
 
1551                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1554                             //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
 
1555                             if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
 
1556                                 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
 
1557                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
 
1558                                 if ($searchedHousenumber%2 == 0) {
 
1559                                     $sSQL .= "interpolationtype='even'";
 
1561                                     $sSQL .= "interpolationtype='odd'";
 
1563                                 $sSQL .= " or interpolationtype='all') and ";
 
1564                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
 
1565                                 $sSQL .= $searchedHousenumber."<=endnumber";
 
1567                                 if (sizeof($this->aExcludePlaceIDs)) {
 
1568                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1570                                 //$sSQL .= " limit $this->iLimit";
 
1571                                 if (CONST_Debug) var_dump($sSQL);
 
1573                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
 
1576                             // Fallback to the road (if no housenumber was found)
 
1577                             if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
 
1578                                 $aPlaceIDs = $aRoadPlaceIDs;
 
1579                                 //set to -1, if no housenumbers were found
 
1580                                 $searchedHousenumber = -1;
 
1582                             //else: housenumber was found, remains saved in searchedHousenumber
 
1586                         if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
 
1587                             $sPlaceIDs = join(',', $aPlaceIDs);
 
1588                             $aClassPlaceIDs = array();
 
1590                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
 
1591                                 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
 
1592                                 $sSQL = "SELECT place_id ";
 
1593                                 $sSQL .= " FROM placex ";
 
1594                                 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
 
1595                                 $sSQL .= "   AND class='".$aSearch['sClass']."' ";
 
1596                                 $sSQL .= "   AND type='".$aSearch['sType']."'";
 
1597                                 $sSQL .= "   AND linked_place_id is null";
 
1598                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
 
1599                                 $sSQL .= " ORDER BY rank_search ASC ";
 
1600                                 $sSQL .= " LIMIT $this->iLimit";
 
1601                                 if (CONST_Debug) var_dump($sSQL);
 
1602                                 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1605                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
 
1606                                 $sClassTable = 'place_classtype_'.$aSearch['sClass'].'_'.$aSearch['sType'];
 
1607                                 $sSQL = "SELECT count(*) FROM pg_tables ";
 
1608                                 $sSQL .= "WHERE tablename = '$sClassTable'";
 
1609                                 $bCacheTable = chksql($this->oDB->getOne($sSQL));
 
1611                                 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
 
1613                                 if (CONST_Debug) var_dump($sSQL);
 
1614                                 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
 
1616                                 // For state / country level searches the normal radius search doesn't work very well
 
1617                                 $sPlaceGeom = false;
 
1618                                 if ($this->iMaxRank < 9 && $bCacheTable) {
 
1619                                     // Try and get a polygon to search in instead
 
1620                                     $sSQL = "SELECT geometry ";
 
1621                                     $sSQL .= " FROM placex";
 
1622                                     $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
1623                                     $sSQL .= "   AND rank_search < $this->iMaxRank + 5";
 
1624                                     $sSQL .= "   AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
 
1625                                     $sSQL .= " ORDER BY rank_search ASC ";
 
1626                                     $sSQL .= " LIMIT 1";
 
1627                                     if (CONST_Debug) var_dump($sSQL);
 
1628                                     $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
 
1634                                     $this->iMaxRank += 5;
 
1635                                     $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
 
1636                                     if (CONST_Debug) var_dump($sSQL);
 
1637                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1638                                     $sPlaceIDs = join(',', $aPlaceIDs);
 
1641                                 if ($sPlaceIDs || $sPlaceGeom) {
 
1644                                         // More efficient - can make the range bigger
 
1649                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
 
1650                                         } elseif ($sPlaceIDs) {
 
1651                                             $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
 
1652                                         } elseif ($sPlaceGeom) {
 
1653                                             $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
1656                                         $sSQL = "select distinct i.place_id".($sOrderBySQL?', i.order_term':'')." from (";
 
1657                                         $sSQL .= "select l.place_id".($sOrderBySQL?','.$sOrderBySQL.' as order_term':'')." from ".$sClassTable." as l";
 
1658                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
 
1660                                             $sSQL .= ",placex as f where ";
 
1661                                             $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
 
1665                                             $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
 
1667                                         if (sizeof($this->aExcludePlaceIDs)) {
 
1668                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1670                                         if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
 
1671                                         $sSQL .= 'limit 300) i ';
 
1672                                         if ($sOrderBySQL) $sSQL .= "order by order_term asc";
 
1673                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
 
1674                                         $sSQL .= " limit $this->iLimit";
 
1675                                         if (CONST_Debug) var_dump($sSQL);
 
1676                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
 
1678                                         if ($aSearch['oNear']) {
 
1679                                             $fRange = $aSearch['oNear']->radius();
 
1684                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
 
1686                                             $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
 
1689                                         $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
 
1690                                         $sSQL .= " FROM placex as l, placex as f ";
 
1691                                         $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
 
1692                                         $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
 
1693                                         $sSQL .= "  AND l.class='".$aSearch['sClass']."' ";
 
1694                                         $sSQL .= "  AND l.type='".$aSearch['sType']."' ";
 
1695                                         if (sizeof($this->aExcludePlaceIDs)) {
 
1696                                             $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
 
1698                                         if ($sCountryCodesSQL) $sSQL .= " AND l.country_code in ($sCountryCodesSQL)";
 
1699                                         if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
 
1700                                         if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
 
1701                                         $sSQL .= " limit $this->iLimit";
 
1702                                         if (CONST_Debug) var_dump($sSQL);
 
1703                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
 
1707                             $aPlaceIDs = $aClassPlaceIDs;
 
1712                         echo "<br><b>Place IDs:</b> ";
 
1713                         var_Dump($aPlaceIDs);
 
1716                     if ($aSearch['sPostcode']) {
 
1717                         $sSQL = 'SELECT place_id FROM placex';
 
1718                         $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
 
1719                         $sSQL .= " AND postcode = '".pg_escape_string($aSearch['sPostcode'])."'";
 
1720                         if (CONST_Debug) var_dump($sSQL);
 
1721                         $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1722                         if ($aFilteredPlaceIDs) {
 
1723                             $aPlaceIDs = $aFilteredPlaceIDs;
 
1725                                 echo "<br><b>Place IDs after postcode filtering:</b> ";
 
1726                                 var_Dump($aPlaceIDs);
 
1731                     foreach ($aPlaceIDs as $iPlaceID) {
 
1732                         // array for placeID => -1 | Tiger housenumber
 
1733                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
 
1735                     if ($iQueryLoop > 20) break;
 
1738                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
 
1739                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
 
1740                     // reduces the number of place ids, like a filter
 
1741                     // rank_address is 30 for interpolated housenumbers
 
1742                     $sSQL = "SELECT place_id ";
 
1743                     $sSQL .= "FROM placex ";
 
1744                     $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
 
1746                     $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
1747                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
 
1748                         $sSQL .= "     OR (extratags->'place') = 'city'";
 
1750                     if ($this->aAddressRankList) {
 
1751                         $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
 
1753                     if (CONST_Use_US_Tiger_Data) {
 
1756                         $sSQL .= "  SELECT place_id ";
 
1757                         $sSQL .= "  FROM location_property_tiger ";
 
1758                         $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
 
1759                         $sSQL .= "    AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
1760                         if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
 
1762                     $sSQL .= ") UNION ";
 
1763                     $sSQL .= "  SELECT place_id ";
 
1764                     $sSQL .= "  FROM location_property_osmline ";
 
1765                     $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
 
1766                     $sSQL .= "    AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
 
1767                     if (CONST_Debug) var_dump($sSQL);
 
1768                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1770                     foreach ($aFilteredPlaceIDs as $placeID) {
 
1771                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
 
1773                     $aResultPlaceIDs = $tempIDs;
 
1777                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
 
1778                 if ($iGroupLoop > 4) break;
 
1779                 if ($iQueryLoop > 30) break;
 
1782             // Did we find anything?
 
1783             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
 
1784                 $aSearchResults = $this->getDetails($aResultPlaceIDs);
 
1787             // Just interpret as a reverse geocode
 
1788             $oReverse = new ReverseGeocode($this->oDB);
 
1789             $oReverse->setZoom(18);
 
1791             $aLookup = $oReverse->lookup(
 
1797             if (CONST_Debug) var_dump("Reverse search", $aLookup);
 
1799             if ($aLookup['place_id']) {
 
1800                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
 
1801                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
 
1803                 $aSearchResults = array();
 
1808         if (!sizeof($aSearchResults)) {
 
1809             if ($this->bFallback) {
 
1810                 if ($this->fallbackStructuredQuery()) {
 
1811                     return $this->lookup();
 
1818         $aClassType = getClassTypesWithImportance();
 
1819         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
 
1820         foreach ($aRecheckWords as $i => $sWord) {
 
1821             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
 
1825             echo '<i>Recheck words:<\i>';
 
1826             var_dump($aRecheckWords);
 
1829         $oPlaceLookup = new PlaceLookup($this->oDB);
 
1830         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
 
1831         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
 
1832         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
 
1833         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
 
1834         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
 
1835         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
 
1837         foreach ($aSearchResults as $iResNum => $aResult) {
 
1839             $fDiameter = getResultDiameter($aResult);
 
1841             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
 
1842             if ($aOutlineResult) {
 
1843                 $aResult = array_merge($aResult, $aOutlineResult);
 
1846             if ($aResult['extra_place'] == 'city') {
 
1847                 $aResult['class'] = 'place';
 
1848                 $aResult['type'] = 'city';
 
1849                 $aResult['rank_search'] = 16;
 
1852             // Is there an icon set for this type of result?
 
1853             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1854                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
 
1856                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
1859             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
 
1860                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
 
1862                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
 
1863             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1864                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
 
1866                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
1868             // if tag '&addressdetails=1' is set in query
 
1869             if ($this->bIncludeAddressDetails) {
 
1870                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
 
1871                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
 
1872                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
 
1873                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
 
1877             if ($this->bIncludeExtraTags) {
 
1878                 if ($aResult['extra']) {
 
1879                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
 
1881                     $aResult['sExtraTags'] = (object) array();
 
1885             if ($this->bIncludeNameDetails) {
 
1886                 if ($aResult['names']) {
 
1887                     $aResult['sNameDetails'] = json_decode($aResult['names']);
 
1889                     $aResult['sNameDetails'] = (object) array();
 
1893             // Adjust importance for the number of exact string matches in the result
 
1894             $aResult['importance'] = max(0.001, $aResult['importance']);
 
1896             $sAddress = $aResult['langaddress'];
 
1897             foreach ($aRecheckWords as $i => $sWord) {
 
1898                 if (stripos($sAddress, $sWord)!==false) {
 
1900                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
 
1904             $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
 
1906             $aResult['name'] = $aResult['langaddress'];
 
1907             // secondary ordering (for results with same importance (the smaller the better):
 
1908             // - approximate importance of address parts
 
1909             $aResult['foundorder'] = -$aResult['addressimportance']/10;
 
1910             // - number of exact matches from the query
 
1911             if (isset($this->exactMatchCache[$aResult['place_id']])) {
 
1912                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
 
1913             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
 
1914                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
 
1916             // - importance of the class/type
 
1917             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1918                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
 
1920                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1922                 $aResult['foundorder'] += 0.01;
 
1924             if (CONST_Debug) var_dump($aResult);
 
1925             $aSearchResults[$iResNum] = $aResult;
 
1927         uasort($aSearchResults, 'byImportance');
 
1929         $aOSMIDDone = array();
 
1930         $aClassTypeNameDone = array();
 
1931         $aToFilter = $aSearchResults;
 
1932         $aSearchResults = array();
 
1935         foreach ($aToFilter as $iResNum => $aResult) {
 
1936             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1938                 $fLat = $aResult['lat'];
 
1939                 $fLon = $aResult['lon'];
 
1940                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1943             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1944                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
 
1946                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1947                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
 
1948                 $aSearchResults[] = $aResult;
 
1951             // Absolute limit on number of results
 
1952             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
 
1955         return $aSearchResults;