5 require_once(CONST_BasePath.'/lib/NearPoint.php');
 
   6 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
 
   7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
 
   8 require_once(CONST_BasePath.'/lib/SearchDescription.php');
 
  14     protected $aLangPrefOrder = array();
 
  16     protected $bIncludeAddressDetails = false;
 
  17     protected $bIncludeExtraTags = false;
 
  18     protected $bIncludeNameDetails = false;
 
  20     protected $bIncludePolygonAsPoints = false;
 
  21     protected $bIncludePolygonAsText = false;
 
  22     protected $bIncludePolygonAsGeoJSON = false;
 
  23     protected $bIncludePolygonAsKML = false;
 
  24     protected $bIncludePolygonAsSVG = false;
 
  25     protected $fPolygonSimplificationThreshold = 0.0;
 
  27     protected $aExcludePlaceIDs = array();
 
  28     protected $bDeDupe = true;
 
  29     protected $bReverseInPlan = false;
 
  31     protected $iLimit = 20;
 
  32     protected $iFinalLimit = 10;
 
  33     protected $iOffset = 0;
 
  34     protected $bFallback = false;
 
  36     protected $aCountryCodes = false;
 
  38     protected $bBoundedSearch = false;
 
  39     protected $aViewBox = false;
 
  40     protected $sViewboxCentreSQL = false;
 
  41     protected $sViewboxSmallSQL = false;
 
  42     protected $sViewboxLargeSQL = false;
 
  44     protected $iMaxRank = 20;
 
  45     protected $iMinAddressRank = 0;
 
  46     protected $iMaxAddressRank = 30;
 
  47     protected $aAddressRankList = array();
 
  48     protected $exactMatchCache = array();
 
  50     protected $sAllowedTypesSQLList = false;
 
  52     protected $sQuery = false;
 
  53     protected $aStructuredQuery = false;
 
  55     protected $oNormalizer = null;
 
  58     public function __construct(&$oDB)
 
  61         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
 
  64     private function normTerm($sTerm)
 
  66         if ($this->oNormalizer === null) {
 
  70         return $this->oNormalizer->transliterate($sTerm);
 
  73     public function setReverseInPlan($bReverse)
 
  75         $this->bReverseInPlan = $bReverse;
 
  78     public function setLanguagePreference($aLangPref)
 
  80         $this->aLangPrefOrder = $aLangPref;
 
  83     public function getMoreUrlParams()
 
  85         if ($this->aStructuredQuery) {
 
  86             $aParams = $this->aStructuredQuery;
 
  88             $aParams = array('q' => $this->sQuery);
 
  91         if ($this->aExcludePlaceIDs) {
 
  92             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
 
  95         if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
 
  96         if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
 
  97         if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
 
  99         if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
 
 100         if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
 
 101         if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
 
 102         if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
 
 103         if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
 
 105         if ($this->fPolygonSimplificationThreshold > 0.0) {
 
 106             $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
 
 109         if ($this->bBoundedSearch) $aParams['bounded'] = '1';
 
 110         if (!$this->bDeDupe) $aParams['dedupe'] = '0';
 
 112         if ($this->aCountryCodes) {
 
 113             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
 
 116         if ($this->aViewBox) {
 
 117             $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
 
 118                                   .','.$this->aViewBox[2].','.$this->aViewBox[1];
 
 124     public function setIncludePolygonAsPoints($b = true)
 
 126         $this->bIncludePolygonAsPoints = $b;
 
 129     public function setIncludePolygonAsText($b = true)
 
 131         $this->bIncludePolygonAsText = $b;
 
 134     public function setIncludePolygonAsGeoJSON($b = true)
 
 136         $this->bIncludePolygonAsGeoJSON = $b;
 
 139     public function setIncludePolygonAsKML($b = true)
 
 141         $this->bIncludePolygonAsKML = $b;
 
 144     public function setIncludePolygonAsSVG($b = true)
 
 146         $this->bIncludePolygonAsSVG = $b;
 
 149     public function setPolygonSimplificationThreshold($f)
 
 151         $this->fPolygonSimplificationThreshold = $f;
 
 154     public function setLimit($iLimit = 10)
 
 156         if ($iLimit > 50) $iLimit = 50;
 
 157         if ($iLimit < 1) $iLimit = 1;
 
 159         $this->iFinalLimit = $iLimit;
 
 160         $this->iLimit = $iLimit + min($iLimit, 10);
 
 163     public function setFeatureType($sFeatureType)
 
 165         switch ($sFeatureType) {
 
 167                 $this->setRankRange(4, 4);
 
 170                 $this->setRankRange(8, 8);
 
 173                 $this->setRankRange(14, 16);
 
 176                 $this->setRankRange(8, 20);
 
 181     public function setRankRange($iMin, $iMax)
 
 183         $this->iMinAddressRank = $iMin;
 
 184         $this->iMaxAddressRank = $iMax;
 
 187     public function setRoute($aRoutePoints, $fRouteWidth)
 
 189         $this->aViewBox = false;
 
 191         $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
 
 193         foreach ($aRoutePoints as $aPoint) {
 
 194             $fPoint = (float)$aPoint;
 
 195             $this->sViewboxCentreSQL .= $sSep.$fPoint;
 
 196             $sSep = ($sSep == ' ') ? ',' : ' ';
 
 198         $this->sViewboxCentreSQL .= ")'::geometry,4326)";
 
 200         $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
 
 201         $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
 
 203         $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
 
 204         $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
 
 207     public function setViewbox($aViewbox)
 
 209         $this->aViewBox = array_map('floatval', $aViewbox);
 
 211         $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
 
 212         $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
 
 213         $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
 
 214         $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
 
 216         if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
 
 217             || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
 
 219             userError("Bad parameter 'viewbox'. Not a box.");
 
 222         $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
 
 223         $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
 
 224         $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
 
 225         $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
 
 226         $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
 
 227         $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
 
 229         $this->sViewboxCentreSQL = false;
 
 230         $this->sViewboxSmallSQL = sprintf(
 
 231             'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
 
 237         $this->sViewboxLargeSQL = sprintf(
 
 238             'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
 
 246     public function setQuery($sQueryString)
 
 248         $this->sQuery = $sQueryString;
 
 249         $this->aStructuredQuery = false;
 
 252     public function getQueryString()
 
 254         return $this->sQuery;
 
 258     public function loadParamArray($oParams)
 
 260         $this->bIncludeAddressDetails
 
 261          = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
 
 262         $this->bIncludeExtraTags
 
 263          = $oParams->getBool('extratags', $this->bIncludeExtraTags);
 
 264         $this->bIncludeNameDetails
 
 265          = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
 
 267         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
 
 268         $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
 
 270         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
 
 271         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
 
 273         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
 
 275         // List of excluded Place IDs - used for more acurate pageing
 
 276         $sExcluded = $oParams->getStringList('exclude_place_ids');
 
 278             foreach ($sExcluded as $iExcludedPlaceID) {
 
 279                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
 280                 if ($iExcludedPlaceID)
 
 281                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
 284             if (isset($aExcludePlaceIDs))
 
 285                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
 
 288         // Only certain ranks of feature
 
 289         $sFeatureType = $oParams->getString('featureType');
 
 290         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
 
 291         if ($sFeatureType) $this->setFeatureType($sFeatureType);
 
 294         $sCountries = $oParams->getStringList('countrycodes');
 
 296             foreach ($sCountries as $sCountryCode) {
 
 297                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
 
 298                     $aCountries[] = strtolower($sCountryCode);
 
 301             if (isset($aCountries))
 
 302                 $this->aCountryCodes = $aCountries;
 
 305         $aViewbox = $oParams->getStringList('viewboxlbrt');
 
 307             if (count($aViewbox) != 4) {
 
 308                 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
 
 310             $this->setViewbox($aViewbox);
 
 312             $aViewbox = $oParams->getStringList('viewbox');
 
 314                 if (count($aViewbox) != 4) {
 
 315                     userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
 
 317                 $this->setViewBox($aViewbox);
 
 319                 $aRoute = $oParams->getStringList('route');
 
 320                 $fRouteWidth = $oParams->getFloat('routewidth');
 
 321                 if ($aRoute && $fRouteWidth) {
 
 322                     $this->setRoute($aRoute, $fRouteWidth);
 
 328     public function setQueryFromParams($oParams)
 
 331         $sQuery = $oParams->getString('q');
 
 333             $this->setStructuredQuery(
 
 334                 $oParams->getString('amenity'),
 
 335                 $oParams->getString('street'),
 
 336                 $oParams->getString('city'),
 
 337                 $oParams->getString('county'),
 
 338                 $oParams->getString('state'),
 
 339                 $oParams->getString('country'),
 
 340                 $oParams->getString('postalcode')
 
 342             $this->setReverseInPlan(false);
 
 344             $this->setQuery($sQuery);
 
 348     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
 
 350         $sValue = trim($sValue);
 
 351         if (!$sValue) return false;
 
 352         $this->aStructuredQuery[$sKey] = $sValue;
 
 353         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
 
 354             $this->iMinAddressRank = $iNewMinAddressRank;
 
 355             $this->iMaxAddressRank = $iNewMaxAddressRank;
 
 357         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
 
 361     public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
 
 363         $this->sQuery = false;
 
 366         $this->iMinAddressRank = 0;
 
 367         $this->iMaxAddressRank = 30;
 
 368         $this->aAddressRankList = array();
 
 370         $this->aStructuredQuery = array();
 
 371         $this->sAllowedTypesSQLList = False;
 
 373         $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
 
 374         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
 
 375         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
 
 376         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
 
 377         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
 
 378         $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
 
 379         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
 
 381         if (sizeof($this->aStructuredQuery) > 0) {
 
 382             $this->sQuery = join(', ', $this->aStructuredQuery);
 
 383             if ($this->iMaxAddressRank < 30) {
 
 384                 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
 
 389     public function fallbackStructuredQuery()
 
 391         if (!$this->aStructuredQuery) return false;
 
 393         $aParams = $this->aStructuredQuery;
 
 395         if (sizeof($aParams) == 1) return false;
 
 397         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
 
 399         foreach ($aOrderToFallback as $sType) {
 
 400             if (isset($aParams[$sType])) {
 
 401                 unset($aParams[$sType]);
 
 402                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
 
 410     public function getDetails($aPlaceIDs)
 
 412         //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
 
 413         if (sizeof($aPlaceIDs) == 0) return array();
 
 415         $sLanguagePrefArraySQL = getArraySQL(
 
 416             array_map("getDBQuoted",
 
 417             $this->aLangPrefOrder)
 
 420         // Get the details for display (is this a redundant extra step?)
 
 421         $sPlaceIDs = join(',', array_keys($aPlaceIDs));
 
 423         $sImportanceSQL = '';
 
 424         $sImportanceSQLGeom = '';
 
 425         if ($this->sViewboxSmallSQL) {
 
 426             $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
 
 427             $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, geometry) THEN 1 ELSE 0.75 END * ";
 
 429         if ($this->sViewboxLargeSQL) {
 
 430             $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
 
 431             $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, geometry) THEN 1 ELSE 0.75 END * ";
 
 435         $sSQL .= "    osm_type,";
 
 439         $sSQL .= "    admin_level,";
 
 440         $sSQL .= "    rank_search,";
 
 441         $sSQL .= "    rank_address,";
 
 442         $sSQL .= "    min(place_id) AS place_id, ";
 
 443         $sSQL .= "    min(parent_place_id) AS parent_place_id, ";
 
 444         $sSQL .= "    country_code, ";
 
 445         $sSQL .= "    get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
 
 446         $sSQL .= "    get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
 
 447         $sSQL .= "    get_name_by_language(name, ARRAY['ref']) AS ref,";
 
 448         if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
 
 449         if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
 
 450         $sSQL .= "    avg(ST_X(centroid)) AS lon, ";
 
 451         $sSQL .= "    avg(ST_Y(centroid)) AS lat, ";
 
 452         $sSQL .= "    ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
 
 454         $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
 
 456         $sSQL .= "         place_addressline s, ";
 
 457         $sSQL .= "         placex p";
 
 458         $sSQL .= "       WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
 
 459         $sSQL .= "         AND p.place_id = s.address_place_id ";
 
 460         $sSQL .= "         AND s.isaddress ";
 
 461         $sSQL .= "         AND p.importance is not null ";
 
 462         $sSQL .= "    ) AS addressimportance, ";
 
 463         $sSQL .= "    (extratags->'place') AS extra_place ";
 
 464         $sSQL .= " FROM placex";
 
 465         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
 
 467         $sSQL .= "            placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 468         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
 
 469             $sSQL .= "        OR (extratags->'place') = 'city'";
 
 471         if ($this->aAddressRankList) {
 
 472             $sSQL .= "        OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
 
 475         if ($this->sAllowedTypesSQLList) {
 
 476             $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
 
 478         $sSQL .= "    AND linked_place_id is null ";
 
 479         $sSQL .= " GROUP BY ";
 
 480         $sSQL .= "     osm_type, ";
 
 481         $sSQL .= "     osm_id, ";
 
 484         $sSQL .= "     admin_level, ";
 
 485         $sSQL .= "     rank_search, ";
 
 486         $sSQL .= "     rank_address, ";
 
 487         $sSQL .= "     country_code, ";
 
 488         $sSQL .= "     importance, ";
 
 489         if (!$this->bDeDupe) $sSQL .= "place_id,";
 
 490         $sSQL .= "     langaddress, ";
 
 491         $sSQL .= "     placename, ";
 
 493         if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
 
 494         if ($this->bIncludeNameDetails) $sSQL .= "name, ";
 
 495         $sSQL .= "     extratags->'place' ";
 
 500         $sSQL .= "  'P' as osm_type,";
 
 501         $sSQL .= "  (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
 
 502         $sSQL .= "  'place' as class, 'postcode' as type,";
 
 503         $sSQL .= "  null as admin_level, rank_search, rank_address,";
 
 504         $sSQL .= "  place_id, parent_place_id, country_code,";
 
 505         $sSQL .= "  get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
 
 506         $sSQL .= "  postcode as placename,";
 
 507         $sSQL .= "  postcode as ref,";
 
 508         if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
 
 509         if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
 
 510         $sSQL .= "  ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
 
 511         $sSQL .=    $sImportanceSQLGeom."(0.75-(rank_search::float/40)) AS importance, ";
 
 513         $sSQL .= "     SELECT max(p.importance*(p.rank_address+2))";
 
 515         $sSQL .= "       place_addressline s, ";
 
 516         $sSQL .= "       placex p";
 
 517         $sSQL .= "     WHERE s.place_id = lp.parent_place_id";
 
 518         $sSQL .= "       AND p.place_id = s.address_place_id ";
 
 519         $sSQL .= "       AND s.isaddress";
 
 520         $sSQL .= "       AND p.importance is not null";
 
 521         $sSQL .= "  ) AS addressimportance, ";
 
 522         $sSQL .= "  null AS extra_place ";
 
 523         $sSQL .= "FROM location_postcode lp";
 
 524         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
 
 526         if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
 
 527             // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
 
 528             // with start- and endnumber, the common osm housenumbers are usually saved as points
 
 531             $length = count($aPlaceIDs);
 
 532             foreach ($aPlaceIDs as $placeID => $housenumber) {
 
 534                 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
 
 535                 if ($i<$length) $sHousenumbers .= ", ";
 
 538             if (CONST_Use_US_Tiger_Data) {
 
 539                 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
 
 542                 $sSQL .= "     'T' AS osm_type, ";
 
 543                 $sSQL .= "     (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
 
 544                 $sSQL .= "     'place' AS class, ";
 
 545                 $sSQL .= "     'house' AS type, ";
 
 546                 $sSQL .= "     null AS admin_level, ";
 
 547                 $sSQL .= "     30 AS rank_search, ";
 
 548                 $sSQL .= "     30 AS rank_address, ";
 
 549                 $sSQL .= "     min(place_id) AS place_id, ";
 
 550                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
 
 551                 $sSQL .= "     'us' AS country_code, ";
 
 552                 $sSQL .= "     get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
 
 553                 $sSQL .= "     null AS placename, ";
 
 554                 $sSQL .= "     null AS ref, ";
 
 555                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
 
 556                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
 
 557                 $sSQL .= "     avg(st_x(centroid)) AS lon, ";
 
 558                 $sSQL .= "     avg(st_y(centroid)) AS lat,";
 
 559                 $sSQL .= "     ".$sImportanceSQL."-1.15 AS importance, ";
 
 561                 $sSQL .= "        SELECT max(p.importance*(p.rank_address+2))";
 
 563                 $sSQL .= "          place_addressline s, ";
 
 564                 $sSQL .= "          placex p";
 
 565                 $sSQL .= "        WHERE s.place_id = min(blub.parent_place_id)";
 
 566                 $sSQL .= "          AND p.place_id = s.address_place_id ";
 
 567                 $sSQL .= "          AND s.isaddress";
 
 568                 $sSQL .= "          AND p.importance is not null";
 
 569                 $sSQL .= "     ) AS addressimportance, ";
 
 570                 $sSQL .= "     null AS extra_place ";
 
 572                 $sSQL .= "     SELECT place_id, ";    // interpolate the Tiger housenumbers here
 
 573                 $sSQL .= "         ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
 
 574                 $sSQL .= "         parent_place_id, ";
 
 575                 $sSQL .= "         housenumber_for_place";
 
 577                 $sSQL .= "            location_property_tiger ";
 
 578                 $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
 
 580                 $sSQL .= "         housenumber_for_place>=0";
 
 581                 $sSQL .= "         AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
 
 582                 $sSQL .= " ) AS blub"; //postgres wants an alias here
 
 583                 $sSQL .= " GROUP BY";
 
 584                 $sSQL .= "      place_id, ";
 
 585                 $sSQL .= "      housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
 
 586                 if (!$this->bDeDupe) $sSQL .= ", place_id ";
 
 589             // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
 
 592             $sSQL .= "  'W' AS osm_type, ";
 
 593             $sSQL .= "  osm_id, ";
 
 594             $sSQL .= "  'place' AS class, ";
 
 595             $sSQL .= "  'house' AS type, ";
 
 596             $sSQL .= "  null AS admin_level, ";
 
 597             $sSQL .= "  30 AS rank_search, ";
 
 598             $sSQL .= "  30 AS rank_address, ";
 
 599             $sSQL .= "  min(place_id) as place_id, ";
 
 600             $sSQL .= "  min(parent_place_id) AS parent_place_id, ";
 
 601             $sSQL .= "  country_code, ";
 
 602             $sSQL .= "  get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
 
 603             $sSQL .= "  null AS placename, ";
 
 604             $sSQL .= "  null AS ref, ";
 
 605             if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
 
 606             if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
 
 607             $sSQL .= "  AVG(st_x(centroid)) AS lon, ";
 
 608             $sSQL .= "  AVG(st_y(centroid)) AS lat, ";
 
 609             $sSQL .= "  ".$sImportanceSQL."-0.1 AS importance, ";  // slightly smaller than the importance for normal houses with rank 30, which is 0
 
 612             $sSQL .= "       MAX(p.importance*(p.rank_address+2)) ";
 
 614             $sSQL .= "       place_addressline s, ";
 
 615             $sSQL .= "       placex p";
 
 616             $sSQL .= "     WHERE s.place_id = min(blub.parent_place_id) ";
 
 617             $sSQL .= "       AND p.place_id = s.address_place_id ";
 
 618             $sSQL .= "       AND s.isaddress ";
 
 619             $sSQL .= "       AND p.importance is not null";
 
 620             $sSQL .= "  ) AS addressimportance,";
 
 621             $sSQL .= "  null AS extra_place ";
 
 624             $sSQL .= "         osm_id, ";
 
 625             $sSQL .= "         place_id, ";
 
 626             $sSQL .= "         country_code, ";
 
 627             $sSQL .= "         CASE ";             // interpolate the housenumbers here
 
 628             $sSQL .= "           WHEN startnumber != endnumber ";
 
 629             $sSQL .= "           THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
 
 630             $sSQL .= "           ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
 
 631             $sSQL .= "         END as centroid, ";
 
 632             $sSQL .= "         parent_place_id, ";
 
 633             $sSQL .= "         housenumber_for_place ";
 
 635             $sSQL .= "            location_property_osmline ";
 
 636             $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
 
 638             $sSQL .= "     WHERE housenumber_for_place>=0 ";
 
 639             $sSQL .= "       AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
 
 640             $sSQL .= "  ) as blub"; //postgres wants an alias here
 
 641             $sSQL .= "  GROUP BY ";
 
 642             $sSQL .= "    osm_id, ";
 
 643             $sSQL .= "    place_id, ";
 
 644             $sSQL .= "    housenumber_for_place, ";
 
 645             $sSQL .= "    country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
 
 646             if (!$this->bDeDupe) $sSQL .= ", place_id ";
 
 648             if (CONST_Use_Aux_Location_data) {
 
 651                 $sSQL .= "     'L' AS osm_type, ";
 
 652                 $sSQL .= "     place_id AS osm_id, ";
 
 653                 $sSQL .= "     'place' AS class,";
 
 654                 $sSQL .= "     'house' AS type, ";
 
 655                 $sSQL .= "     null AS admin_level, ";
 
 656                 $sSQL .= "     0 AS rank_search,";
 
 657                 $sSQL .= "     0 AS rank_address, ";
 
 658                 $sSQL .= "     min(place_id) AS place_id,";
 
 659                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
 
 660                 $sSQL .= "     'us' AS country_code, ";
 
 661                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
 
 662                 $sSQL .= "     null AS placename, ";
 
 663                 $sSQL .= "     null AS ref, ";
 
 664                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
 
 665                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
 
 666                 $sSQL .= "     avg(ST_X(centroid)) AS lon, ";
 
 667                 $sSQL .= "     avg(ST_Y(centroid)) AS lat, ";
 
 668                 $sSQL .= "     ".$sImportanceSQL."-1.10 AS importance, ";
 
 670                 $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
 
 672                 $sSQL .= "          place_addressline s, ";
 
 673                 $sSQL .= "          placex p";
 
 674                 $sSQL .= "       WHERE s.place_id = min(location_property_aux.parent_place_id)";
 
 675                 $sSQL .= "         AND p.place_id = s.address_place_id ";
 
 676                 $sSQL .= "         AND s.isaddress";
 
 677                 $sSQL .= "         AND p.importance is not null";
 
 678                 $sSQL .= "     ) AS addressimportance, ";
 
 679                 $sSQL .= "     null AS extra_place ";
 
 680                 $sSQL .= "  FROM location_property_aux ";
 
 681                 $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
 
 682                 $sSQL .= "    AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 683                 $sSQL .= "  GROUP BY ";
 
 684                 $sSQL .= "     place_id, ";
 
 685                 if (!$this->bDeDupe) $sSQL .= "place_id, ";
 
 686                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
 
 690         $sSQL .= " order by importance desc";
 
 695         $aSearchResults = chksql(
 
 696             $this->oDB->getAll($sSQL),
 
 697             "Could not get details for place."
 
 700         return $aSearchResults;
 
 703     public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
 
 706              Calculate all searches using aValidTokens i.e.
 
 707              'Wodsworth Road, Sheffield' =>
 
 711              0      1       (wodsworth)(road)
 
 714              Score how good the search is so they can be ordered
 
 718         foreach ($aPhrases as $iPhrase => $aPhrase) {
 
 719             $aNewPhraseSearches = array();
 
 720             if ($bStructuredPhrases) {
 
 721                 $sPhraseType = $aPhraseTypes[$iPhrase];
 
 726             foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
 
 727                 // Too many permutations - too expensive
 
 728                 if ($iWordSet > 120) break;
 
 730                 $aWordsetSearches = $aSearches;
 
 732                 // Add all words from this wordset
 
 733                 foreach ($aWordset as $iToken => $sToken) {
 
 734                     //echo "<br><b>$sToken</b>";
 
 735                     $aNewWordsetSearches = array();
 
 737                     foreach ($aWordsetSearches as $oCurrentSearch) {
 
 739                         //var_dump($oCurrentSearch);
 
 742                         // If the token is valid
 
 743                         if (isset($aValidTokens[' '.$sToken])) {
 
 744                             // Recheck if the original word shows up in the query.
 
 745                             $bWordInQuery = false;
 
 746                             if (isset($aSearchTerm['word']) && $aSearchTerm['word']) {
 
 747                                 $bWordInQuery = $this->normTerm($aSearchTerm['word']) !== false;
 
 749                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
 
 750                                 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
 
 753                                     isset($aValidTokens[$sToken])
 
 754                                       && strpos($sToken, ' ') === false,
 
 756                                     $iToken == 0 && $iPhrase == 0,
 
 758                                     $iToken + 1 == sizeof($aWordset)
 
 759                                       && $iPhrase + 1 == sizeof($aPhrases),
 
 763                                 foreach ($aNewSearches as $oSearch) {
 
 764                                     if ($oSearch->getRank() < $this->iMaxRank) {
 
 765                                         $aNewWordsetSearches[] = $oSearch;
 
 770                         // Look for partial matches.
 
 771                         // Note that there is no point in adding country terms here
 
 772                         // because country is omitted in the address.
 
 773                         if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
 
 774                             // Allow searching for a word - but at extra cost
 
 775                             foreach ($aValidTokens[$sToken] as $aSearchTerm) {
 
 776                                 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
 
 780                                     $aWordFrequencyScores,
 
 781                                     isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
 
 784                                 foreach ($aNewSearches as $oSearch) {
 
 785                                     if ($oSearch->getRank() < $this->iMaxRank) {
 
 786                                         $aNewWordsetSearches[] = $oSearch;
 
 794                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
 
 795                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 797                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 799                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 800                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
 
 802                 $aSearchHash = array();
 
 803                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
 
 804                     $sHash = serialize($aSearch);
 
 805                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
 
 806                     else $aSearchHash[$sHash] = 1;
 
 809                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 812             // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 813             $aGroupedSearches = array();
 
 814             foreach ($aNewPhraseSearches as $aSearch) {
 
 815                 $iRank = $aSearch->getRank();
 
 816                 if ($iRank < $this->iMaxRank) {
 
 817                     if (!isset($aGroupedSearches[$iRank])) {
 
 818                         $aGroupedSearches[$iRank] = array();
 
 820                     $aGroupedSearches[$iRank][] = $aSearch;
 
 823             ksort($aGroupedSearches);
 
 826             $aSearches = array();
 
 827             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
 
 828                 $iSearchCount += sizeof($aNewSearches);
 
 829                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 830                 if ($iSearchCount > 50) break;
 
 833             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 836         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
 
 837         $aGroupedSearches = array();
 
 838         foreach ($aSearches as $oSearch) {
 
 839             if (!$oSearch->isValidSearch($this->aCountryCodes)) {
 
 843             $iRank = $oSearch->addToRank($iGlobalRank);
 
 844             if (!isset($aGroupedSearches[$iRank])) {
 
 845                 $aGroupedSearches[$iRank] = array();
 
 847             $aGroupedSearches[$iRank][] = $oSearch;
 
 849         ksort($aGroupedSearches);
 
 851         return $aGroupedSearches;
 
 854     /* Perform the actual query lookup.
 
 856         Returns an ordered list of results, each with the following fields:
 
 857             osm_type: type of corresponding OSM object
 
 861                         P - postcode (internally computed)
 
 862             osm_id: id of corresponding OSM object
 
 863             class: general object class (corresponds to tag key of primary OSM tag)
 
 864             type: subclass of object (corresponds to tag value of primary OSM tag)
 
 865             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
 
 866             rank_search: rank in search hierarchy
 
 867                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
 
 868             rank_address: rank in address hierarchy (determines orer in address)
 
 869             place_id: internal key (may differ between different instances)
 
 870             country_code: ISO country code
 
 871             langaddress: localized full address
 
 872             placename: localized name of object
 
 873             ref: content of ref tag (if available)
 
 876             importance: importance of place based on Wikipedia link count
 
 877             addressimportance: cumulated importance of address elements
 
 878             extra_place: type of place (for admin boundaries, if there is a place tag)
 
 879             aBoundingBox: bounding Box
 
 880             label: short description of the object class/type (English only)
 
 881             name: full name (currently the same as langaddress)
 
 882             foundorder: secondary ordering for places with same importance
 
 886     public function lookup()
 
 888         if (!$this->sQuery && !$this->aStructuredQuery) return array();
 
 890         $sNormQuery = $this->normTerm($this->sQuery);
 
 891         $sLanguagePrefArraySQL = getArraySQL(
 
 892             array_map("getDBQuoted",
 
 893             $this->aLangPrefOrder)
 
 895         $sCountryCodesSQL = false;
 
 896         if ($this->aCountryCodes) {
 
 897             $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
 
 900         $sQuery = $this->sQuery;
 
 901         if (!preg_match('//u', $sQuery)) {
 
 902             userError("Query string is not UTF-8 encoded.");
 
 905         // Conflicts between US state abreviations and various words for 'the' in different languages
 
 906         if (isset($this->aLangPrefOrder['name:en'])) {
 
 907             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
 
 908             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
 
 909             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
 
 912         $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
 
 913         if ($this->sViewboxCentreSQL) {
 
 914             // For complex viewboxes (routes) precompute the bounding geometry
 
 916                 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
 
 917                 "Could not get small viewbox"
 
 919             $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
 
 922                 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
 
 923                 "Could not get large viewbox"
 
 925             $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
 
 928         // Do we have anything that looks like a lat/lon pair?
 
 930         if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
 
 931             $oNearPoint = $aLooksLike['pt'];
 
 932             $sQuery = $aLooksLike['query'];
 
 935         $aSearchResults = array();
 
 936         if ($sQuery || $this->aStructuredQuery) {
 
 937             // Start with a single blank search
 
 938             $aSearches = array(new SearchDescription());
 
 941                 $aSearches[0]->setNear($oNearPoint);
 
 945                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
 
 951                     '/\\[([\\w ]*)\\]/u',
 
 956                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
 
 957                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 958                     if (!$sSpecialTerm) {
 
 959                         $sSpecialTerm = $aSpecialTerm[1];
 
 963             if (!$sSpecialTerm && $this->aStructuredQuery
 
 964                 && isset($this->aStructuredQuery['amenity'])) {
 
 965                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
 
 966                 unset($this->aStructuredQuery['amenity']);
 
 969             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
 
 970                 $sSpecialTerm = pg_escape_string($sSpecialTerm);
 
 972                     $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
 
 973                     "Cannot decode query. Wrong encoding?"
 
 975                 $sSQL = 'SELECT class, type FROM word ';
 
 976                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
 
 977                 $sSQL .= '   AND class is not null AND class not in (\'place\')';
 
 978                 if (CONST_Debug) var_Dump($sSQL);
 
 979                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
 
 980                 $aNewSearches = array();
 
 981                 foreach ($aSearches as $oSearch) {
 
 982                     foreach ($aSearchWords as $aSearchTerm) {
 
 983                         $oNewSearch = clone $oSearch;
 
 984                         $oNewSearch->setPoiSearch(
 
 986                             $aSearchTerm['class'],
 
 989                         $aNewSearches[] = $oNewSearch;
 
 992                 $aSearches = $aNewSearches;
 
 995             // Split query into phrases
 
 996             // Commas are used to reduce the search space by indicating where phrases split
 
 997             if ($this->aStructuredQuery) {
 
 998                 $aPhrases = $this->aStructuredQuery;
 
 999                 $bStructuredPhrases = true;
 
1001                 $aPhrases = explode(',', $sQuery);
 
1002                 $bStructuredPhrases = false;
 
1005             // Convert each phrase to standard form
 
1006             // Create a list of standard words
 
1007             // Get all 'sets' of words
 
1008             // Generate a complete list of all
 
1010             foreach ($aPhrases as $iPhrase => $sPhrase) {
 
1012                     $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
 
1013                     "Cannot normalize query string (is it a UTF-8 string?)"
 
1015                 if (trim($aPhrase['string'])) {
 
1016                     $aPhrases[$iPhrase] = $aPhrase;
 
1017                     $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
 
1018                     $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
 
1019                     $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
 
1021                     unset($aPhrases[$iPhrase]);
 
1025             // Reindex phrases - we make assumptions later on that they are numerically keyed in order
 
1026             $aPhraseTypes = array_keys($aPhrases);
 
1027             $aPhrases = array_values($aPhrases);
 
1029             if (sizeof($aTokens)) {
 
1030                 // Check which tokens we have, get the ID numbers
 
1031                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
 
1032                 $sSQL .= ' FROM word ';
 
1033                 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
 
1035                 if (CONST_Debug) var_Dump($sSQL);
 
1037                 $aValidTokens = array();
 
1038                 $aDatabaseWords = chksql(
 
1039                     $this->oDB->getAll($sSQL),
 
1040                     "Could not get word tokens."
 
1042                 $aPossibleMainWordIDs = array();
 
1043                 $aWordFrequencyScores = array();
 
1044                 foreach ($aDatabaseWords as $aToken) {
 
1045                     // Very special case - require 2 letter country param to match the country code found
 
1046                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
 
1047                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
 
1052                     if (isset($aValidTokens[$aToken['word_token']])) {
 
1053                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
1055                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
1057                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
 
1058                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
 
1060                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
1062                 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
 
1063                 foreach ($aTokens as $sToken) {
 
1064                     if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
 
1065                         if (isset($aValidTokens[$aData[1]])) {
 
1066                             foreach ($aValidTokens[$aData[1]] as $aToken) {
 
1067                                 if (!$aToken['class']) {
 
1068                                     if (isset($aValidTokens[$sToken])) {
 
1069                                         $aValidTokens[$sToken][] = $aToken;
 
1071                                         $aValidTokens[$sToken] = array($aToken);
 
1079                 foreach ($aTokens as $sToken) {
 
1080                     // Unknown single word token with a number - assume it is a house number
 
1081                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
 
1082                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
 
1086                 // Any words that have failed completely?
 
1087                 // TODO: suggestions
 
1089                 // Start the search process
 
1090                 // array with: placeid => -1 | tiger-housenumber
 
1091                 $aResultPlaceIDs = array();
 
1093                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
 
1095                 if ($this->bReverseInPlan) {
 
1096                     // Reverse phrase array and also reverse the order of the wordsets in
 
1097                     // the first and final phrase. Don't bother about phrases in the middle
 
1098                     // because order in the address doesn't matter.
 
1099                     $aPhrases = array_reverse($aPhrases);
 
1100                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
 
1101                     if (sizeof($aPhrases) > 1) {
 
1102                         $aFinalPhrase = end($aPhrases);
 
1103                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
 
1105                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
 
1107                     foreach ($aGroupedSearches as $aSearches) {
 
1108                         foreach ($aSearches as $aSearch) {
 
1109                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
 
1110                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
 
1112                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
 
1116                     $aGroupedSearches = $aReverseGroupedSearches;
 
1117                     ksort($aGroupedSearches);
 
1120                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
1121                 $aGroupedSearches = array();
 
1122                 foreach ($aSearches as $aSearch) {
 
1123                     if ($aSearch->getRank() < $this->iMaxRank) {
 
1124                         if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
 
1125                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
 
1128                 ksort($aGroupedSearches);
 
1131             // Filter out duplicate searches
 
1132             $aSearchHash = array();
 
1133             foreach ($aGroupedSearches as $iGroup => $aSearches) {
 
1134                 foreach ($aSearches as $iSearch => $aSearch) {
 
1135                     $sHash = serialize($aSearch);
 
1136                     if (isset($aSearchHash[$sHash])) {
 
1137                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
1138                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
 
1140                         $aSearchHash[$sHash] = 1;
 
1145             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
1149             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
 
1151                 foreach ($aSearches as $oSearch) {
 
1153                     $searchedHousenumber = -1;
 
1155                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
 
1156                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
 
1158                     $aPlaceIDs = array();
 
1159                     if ($oSearch->isCountrySearch()) {
 
1160                         // Just looking for a country - look it up
 
1161                         if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
 
1162                             $aPlaceIDs = $oSearch->queryCountry(
 
1164                                 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : ''
 
1167                     } elseif (!$oSearch->isNamedSearch()) {
 
1168                         // looking for a POI in a geographic area
 
1169                         if (!$bBoundingBoxSearch && !$oSearch->isNearSearch()) {
 
1173                         $aPlaceIDs = $oSearch->queryNearbyPoi(
 
1176                             $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
 
1177                             $this->sViewboxCentreSQL,
 
1178                             $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
 
1181                     } elseif ($oSearch->isOperator(Operator::POSTCODE)) {
 
1182                         $aPlaceIDs = $oSearch->queryPostcode(
 
1189                         // First search for places according to name and address.
 
1190                         $aNamedPlaceIDs = $oSearch->queryNamedPlace(
 
1192                             $aWordFrequencyScores,
 
1194                             $this->iMinAddressRank,
 
1195                             $this->iMaxAddressRank,
 
1196                             $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
 
1197                             $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
 
1198                             $bBoundingBoxSearch ? $this->sViewboxLargeSQL : '',
 
1202                         if (sizeof($aNamedPlaceIDs)) {
 
1203                             foreach ($aNamedPlaceIDs as $aRow) {
 
1204                                 $aPlaceIDs[] = $aRow['place_id'];
 
1205                                 $this->exactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
 
1209                         //now search for housenumber, if housenumber provided
 
1210                         if ($oSearch->hasHouseNumber() && sizeof($aPlaceIDs)) {
 
1211                             $aResult = $oSearch->queryHouseNumber(
 
1214                                 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
 
1218                             if (sizeof($aResult)) {
 
1219                                 $searchedHousenumber = $aResult['iHouseNumber'];
 
1220                                 $aPlaceIDs = $aResult['aPlaceIDs'];
 
1221                             } elseif (!$oSearch->looksLikeFullAddress()) {
 
1222                                 $aPlaceIDs = array();
 
1226                         // finally get POIs if requested
 
1227                         if ($oSearch->isPoiSearch() && sizeof($aPlaceIDs)) {
 
1228                             $aPlaceIDs = $oSearch->queryPoiByOperator(
 
1231                                 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
 
1238                         echo "<br><b>Place IDs:</b> ";
 
1239                         var_Dump($aPlaceIDs);
 
1242                     if (sizeof($aPlaceIDs) && $oSearch->getPostcode()) {
 
1243                         $sSQL = 'SELECT place_id FROM placex';
 
1244                         $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
 
1245                         $sSQL .= " AND postcode = '".$oSearch->getPostcode()."'";
 
1246                         if (CONST_Debug) var_dump($sSQL);
 
1247                         $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1248                         if ($aFilteredPlaceIDs) {
 
1249                             $aPlaceIDs = $aFilteredPlaceIDs;
 
1251                                 echo "<br><b>Place IDs after postcode filtering:</b> ";
 
1252                                 var_Dump($aPlaceIDs);
 
1257                     foreach ($aPlaceIDs as $iPlaceID) {
 
1258                         // array for placeID => -1 | Tiger housenumber
 
1259                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
 
1261                     if ($iQueryLoop > 20) break;
 
1264                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
 
1265                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
 
1266                     // reduces the number of place ids, like a filter
 
1267                     // rank_address is 30 for interpolated housenumbers
 
1268                     $sWherePlaceId = 'WHERE place_id in (';
 
1269                     $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
 
1271                     $sSQL = "SELECT place_id ";
 
1272                     $sSQL .= "FROM placex ".$sWherePlaceId;
 
1274                     $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
1275                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
 
1276                         $sSQL .= "     OR (extratags->'place') = 'city'";
 
1278                     if ($this->aAddressRankList) {
 
1279                         $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
 
1281                     $sSQL .= "  ) UNION ";
 
1282                     $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
 
1283                     $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
1284                     if ($this->aAddressRankList) {
 
1285                         $sSQL .= "     OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
 
1288                     if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
 
1290                         $sSQL .= "  SELECT place_id ";
 
1291                         $sSQL .= "  FROM location_property_tiger ".$sWherePlaceId;
 
1293                     if ($this->iMaxAddressRank == 30) {
 
1295                         $sSQL .= "  SELECT place_id ";
 
1296                         $sSQL .= "  FROM location_property_osmline ".$sWherePlaceId;
 
1298                     if (CONST_Debug) var_dump($sSQL);
 
1299                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
 
1301                     foreach ($aFilteredPlaceIDs as $placeID) {
 
1302                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
 
1304                     $aResultPlaceIDs = $tempIDs;
 
1308                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
 
1309                 if ($iGroupLoop > 4) break;
 
1310                 if ($iQueryLoop > 30) break;
 
1313             // Did we find anything?
 
1314             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
 
1315                 $aSearchResults = $this->getDetails($aResultPlaceIDs);
 
1318             // Just interpret as a reverse geocode
 
1319             $oReverse = new ReverseGeocode($this->oDB);
 
1320             $oReverse->setZoom(18);
 
1322             $aLookup = $oReverse->lookup(
 
1328             if (CONST_Debug) var_dump("Reverse search", $aLookup);
 
1330             if ($aLookup['place_id']) {
 
1331                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
 
1332                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
 
1334                 $aSearchResults = array();
 
1339         if (!sizeof($aSearchResults)) {
 
1340             if ($this->bFallback) {
 
1341                 if ($this->fallbackStructuredQuery()) {
 
1342                     return $this->lookup();
 
1349         $aClassType = getClassTypesWithImportance();
 
1350         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
 
1351         foreach ($aRecheckWords as $i => $sWord) {
 
1352             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
 
1356             echo '<i>Recheck words:<\i>';
 
1357             var_dump($aRecheckWords);
 
1360         $oPlaceLookup = new PlaceLookup($this->oDB);
 
1361         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
 
1362         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
 
1363         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
 
1364         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
 
1365         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
 
1366         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
 
1368         foreach ($aSearchResults as $iResNum => $aResult) {
 
1370             $fDiameter = getResultDiameter($aResult);
 
1372             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
 
1373             if ($aOutlineResult) {
 
1374                 $aResult = array_merge($aResult, $aOutlineResult);
 
1377             if ($aResult['extra_place'] == 'city') {
 
1378                 $aResult['class'] = 'place';
 
1379                 $aResult['type'] = 'city';
 
1380                 $aResult['rank_search'] = 16;
 
1383             // Is there an icon set for this type of result?
 
1384             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
 
1385                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
 
1387                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
1390             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
 
1391                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
 
1393                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
 
1394             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
 
1395                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
 
1397                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
1399             // if tag '&addressdetails=1' is set in query
 
1400             if ($this->bIncludeAddressDetails) {
 
1401                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
 
1402                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
 
1403                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
 
1404                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
 
1408             if ($this->bIncludeExtraTags) {
 
1409                 if ($aResult['extra']) {
 
1410                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
 
1412                     $aResult['sExtraTags'] = (object) array();
 
1416             if ($this->bIncludeNameDetails) {
 
1417                 if ($aResult['names']) {
 
1418                     $aResult['sNameDetails'] = json_decode($aResult['names']);
 
1420                     $aResult['sNameDetails'] = (object) array();
 
1424             // Adjust importance for the number of exact string matches in the result
 
1425             $aResult['importance'] = max(0.001, $aResult['importance']);
 
1427             $sAddress = $aResult['langaddress'];
 
1428             foreach ($aRecheckWords as $i => $sWord) {
 
1429                 if (stripos($sAddress, $sWord)!==false) {
 
1431                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
 
1435             $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
 
1437             $aResult['name'] = $aResult['langaddress'];
 
1438             // secondary ordering (for results with same importance (the smaller the better):
 
1439             // - approximate importance of address parts
 
1440             $aResult['foundorder'] = -$aResult['addressimportance']/10;
 
1441             // - number of exact matches from the query
 
1442             if (isset($this->exactMatchCache[$aResult['place_id']])) {
 
1443                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
 
1444             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
 
1445                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
 
1447             // - importance of the class/type
 
1448             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
 
1449                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
 
1451                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
1453                 $aResult['foundorder'] += 0.01;
 
1455             if (CONST_Debug) var_dump($aResult);
 
1456             $aSearchResults[$iResNum] = $aResult;
 
1458         uasort($aSearchResults, 'byImportance');
 
1460         $aOSMIDDone = array();
 
1461         $aClassTypeNameDone = array();
 
1462         $aToFilter = $aSearchResults;
 
1463         $aSearchResults = array();
 
1466         foreach ($aToFilter as $iResNum => $aResult) {
 
1467             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
1469                 $fLat = $aResult['lat'];
 
1470                 $fLon = $aResult['lon'];
 
1471                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
1474             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
1475                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
 
1477                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
1478                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
 
1479                 $aSearchResults[] = $aResult;
 
1482             // Absolute limit on number of results
 
1483             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
 
1486         return $aSearchResults;