5 require_once(CONST_LibDir.'/SpecialSearchOperator.php');
 
   6 require_once(CONST_LibDir.'/SearchContext.php');
 
   7 require_once(CONST_LibDir.'/Result.php');
 
  10  * Description of a single interpretation of a search query.
 
  12 class SearchDescription
 
  14     /// Ranking how well the description fits the query.
 
  15     private $iSearchRank = 0;
 
  16     /// Country code of country the result must belong to.
 
  17     private $sCountryCode = '';
 
  18     /// List of word ids making up the name of the object.
 
  19     private $aName = array();
 
  20     /// True if the name is rare enough to force index use on name.
 
  21     private $bRareName = false;
 
  22     /// List of word ids making up the address of the object.
 
  23     private $aAddress = array();
 
  24     /// List of word ids that appear in the name but should be ignored.
 
  25     private $aNameNonSearch = array();
 
  26     /// List of word ids that appear in the address but should be ignored.
 
  27     private $aAddressNonSearch = array();
 
  28     /// Kind of search for special searches, see Nominatim::Operator.
 
  29     private $iOperator = Operator::NONE;
 
  30     /// Class of special feature to search for.
 
  32     /// Type of special feature to search for.
 
  34     /// Housenumber of the object.
 
  35     private $sHouseNumber = '';
 
  36     /// Postcode for the object.
 
  37     private $sPostcode = '';
 
  38     /// Global search constraints.
 
  41     // Temporary values used while creating the search description.
 
  43     /// Index of phrase currently processed.
 
  44     private $iNamePhrase = -1;
 
  47      * Create an empty search description.
 
  49      * @param object $oContext Global context to use. Will be inherited by
 
  50      *                         all derived search objects.
 
  52     public function __construct($oContext)
 
  54         $this->oContext = $oContext;
 
  58      * Get current search rank.
 
  60      * The higher the search rank the lower the likelihood that the
 
  61      * search is a correct interpretation of the search query.
 
  63      * @return integer Search rank.
 
  65     public function getRank()
 
  67         return $this->iSearchRank;
 
  71      * Make this search a POI search.
 
  73      * In a POI search, objects are not (only) searched by their name
 
  74      * but also by the primary OSM key/value pair (class and type in Nominatim).
 
  76      * @param integer $iOperator Type of POI search
 
  77      * @param string  $sClass    Class (or OSM tag key) of POI.
 
  78      * @param string  $sType     Type (or OSM tag value) of POI.
 
  82     public function setPoiSearch($iOperator, $sClass, $sType)
 
  84         $this->iOperator = $iOperator;
 
  85         $this->sClass = $sClass;
 
  86         $this->sType = $sType;
 
  90      * Check if any operator is set.
 
  92      * @return bool True, if this is a special search operation.
 
  94     public function hasOperator()
 
  96         return $this->iOperator != Operator::NONE;
 
 100      * Extract key/value pairs from a query.
 
 102      * Key/value pairs are recognised if they are of the form [<key>=<value>].
 
 103      * If multiple terms of this kind are found then all terms are removed
 
 104      * but only the first is used for search.
 
 106      * @param string $sQuery Original query string.
 
 108      * @return string The query string with the special search patterns removed.
 
 110     public function extractKeyValuePairs($sQuery)
 
 112         // Search for terms of kind [<key>=<value>].
 
 114             '/\\[([\\w_]*)=([\\w_]*)\\]/',
 
 120         foreach ($aSpecialTermsRaw as $aTerm) {
 
 121             $sQuery = str_replace($aTerm[0], ' ', $sQuery);
 
 122             if (!$this->hasOperator()) {
 
 123                 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
 
 131      * Check if the combination of parameters is sensible.
 
 133      * @return bool True, if the search looks valid.
 
 135     public function isValidSearch()
 
 137         if (empty($this->aName)) {
 
 138             if ($this->sHouseNumber) {
 
 141             if (!$this->sClass && !$this->sCountryCode) {
 
 149     /////////// Search building functions
 
 153      * Derive new searches by adding a full term to the existing search.
 
 155      * @param object $oSearchTerm  Description of the token.
 
 156      * @param string $sPhraseType  Type of phrase the token is contained in.
 
 157      * @param bool   $bFirstToken  True if the token is at the beginning of the
 
 159      * @param bool   $bFirstPhrase True if the token is in the first phrase of
 
 161      * @param bool   $bLastToken   True if the token is at the end of the query.
 
 163      * @return SearchDescription[] List of derived search descriptions.
 
 165     public function extendWithFullTerm($oSearchTerm, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
 
 167         $aNewSearches = array();
 
 169         if (($sPhraseType == '' || $sPhraseType == 'country')
 
 170             && is_a($oSearchTerm, '\Nominatim\Token\Country')
 
 172             if (!$this->sCountryCode) {
 
 173                 $oSearch = clone $this;
 
 174                 $oSearch->iSearchRank++;
 
 175                 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
 
 176                 // Country is almost always at the end of the string
 
 177                 // - increase score for finding it anywhere else (optimisation)
 
 179                     $oSearch->iSearchRank += 5;
 
 180                     $oSearch->iNamePhrase = -1;
 
 182                 $aNewSearches[] = $oSearch;
 
 184         } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
 
 185                   && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
 
 187             if (!$this->sPostcode) {
 
 188                 // If we have structured search or this is the first term,
 
 189                 // make the postcode the primary search element.
 
 190                 if ($this->iOperator == Operator::NONE && $bFirstToken) {
 
 191                     $oSearch = clone $this;
 
 192                     $oSearch->iSearchRank++;
 
 193                     $oSearch->iOperator = Operator::POSTCODE;
 
 194                     $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
 
 196                         array($oSearchTerm->iId => $oSearchTerm->sPostcode);
 
 197                     $aNewSearches[] = $oSearch;
 
 200                 // If we have a structured search or this is not the first term,
 
 201                 // add the postcode as an addendum.
 
 202                 if ($this->iOperator != Operator::POSTCODE
 
 203                     && ($sPhraseType == 'postalcode' || !empty($this->aName))
 
 205                     $oSearch = clone $this;
 
 206                     $oSearch->iSearchRank++;
 
 207                     $oSearch->iNamePhrase = -1;
 
 208                     if (strlen($oSearchTerm->sPostcode) < 4) {
 
 209                         $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
 
 211                     $oSearch->sPostcode = $oSearchTerm->sPostcode;
 
 212                     $aNewSearches[] = $oSearch;
 
 215         } elseif (($sPhraseType == '' || $sPhraseType == 'street')
 
 216                  && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
 
 218             if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
 
 219                 // sanity check: if the housenumber is not mainly made
 
 220                 // up of numbers, add a penalty
 
 222                 if (preg_match('/\\d/', $oSearchTerm->sToken) === 0
 
 223                     || preg_match_all('/[^0-9]/', $oSearchTerm->sToken, $aMatches) > 2) {
 
 226                 if ($this->iOperator != Operator::NONE) {
 
 229                 if (empty($oSearchTerm->iId)) {
 
 232                 // also must not appear in the middle of the address
 
 233                 if (!empty($this->aAddress)
 
 234                     || (!empty($this->aAddressNonSearch))
 
 240                 $oSearch = clone $this;
 
 241                 $oSearch->iSearchRank += $iSearchCost;
 
 242                 $oSearch->iNamePhrase = -1;
 
 243                 $oSearch->sHouseNumber = $oSearchTerm->sToken;
 
 244                 $aNewSearches[] = $oSearch;
 
 246                 // Housenumbers may appear in the name when the place has its own
 
 248                 if ($oSearchTerm->iId !== null
 
 249                     && ($this->iNamePhrase >= 0 || empty($this->aName))
 
 250                     && empty($this->aAddress)
 
 252                     $oSearch = clone $this;
 
 253                     $oSearch->iSearchRank += $iSearchCost;
 
 254                     $oSearch->aAddress = $this->aName;
 
 255                     $oSearch->bRareName = false;
 
 256                     $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
 
 257                     $aNewSearches[] = $oSearch;
 
 260         } elseif ($sPhraseType == ''
 
 261                   && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
 
 263             if ($this->iOperator == Operator::NONE) {
 
 264                 $oSearch = clone $this;
 
 265                 $oSearch->iSearchRank += 2;
 
 266                 $oSearch->iNamePhrase = -1;
 
 268                 $iOp = $oSearchTerm->iOperator;
 
 269                 if ($iOp == Operator::NONE) {
 
 270                     if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
 
 271                         $iOp = Operator::NAME;
 
 273                         $iOp = Operator::NEAR;
 
 275                     $oSearch->iSearchRank += 2;
 
 276                 } elseif (!$bFirstToken && !$bLastToken) {
 
 277                     $oSearch->iSearchRank += 2;
 
 279                 if ($this->sHouseNumber) {
 
 280                     $oSearch->iSearchRank++;
 
 283                 $oSearch->setPoiSearch(
 
 285                     $oSearchTerm->sClass,
 
 288                 $aNewSearches[] = $oSearch;
 
 290         } elseif ($sPhraseType != 'country'
 
 291                   && is_a($oSearchTerm, '\Nominatim\Token\Word')
 
 293             $iWordID = $oSearchTerm->iId;
 
 294             // Full words can only be a name if they appear at the beginning
 
 295             // of the phrase. In structured search the name must forcably in
 
 296             // the first phrase. In unstructured search it may be in a later
 
 297             // phrase when the first phrase is a house number.
 
 298             if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
 
 299                 if (($sPhraseType == '' || !$bFirstPhrase) && $oSearchTerm->iTermCount > 1) {
 
 300                     $oSearch = clone $this;
 
 301                     $oSearch->iNamePhrase = -1;
 
 302                     $oSearch->iSearchRank += 1;
 
 303                     $oSearch->aAddress[$iWordID] = $iWordID;
 
 304                     $aNewSearches[] = $oSearch;
 
 306             } elseif (empty($this->aNameNonSearch)) {
 
 307                 $oSearch = clone $this;
 
 308                 $oSearch->iSearchRank++;
 
 309                 $oSearch->aName = array($iWordID => $iWordID);
 
 310                 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
 
 311                     $oSearch->bRareName =
 
 312                         $oSearchTerm->iSearchNameCount
 
 313                           < CONST_Search_NameOnlySearchFrequencyThreshold;
 
 315                 $aNewSearches[] = $oSearch;
 
 319         return $aNewSearches;
 
 323      * Derive new searches by adding a partial term to the existing search.
 
 325      * @param string  $sToken             Term for the token.
 
 326      * @param object  $oSearchTerm        Description of the token.
 
 327      * @param bool    $bStructuredPhrases True if the search is structured.
 
 328      * @param integer $iPhrase            Number of the phrase the token is in.
 
 329      * @param array[] $aFullTokens        List of full term tokens with the
 
 332      * @return SearchDescription[] List of derived search descriptions.
 
 334     public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
 
 336         // Only allow name terms.
 
 337         if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))
 
 338             || strpos($sToken, ' ') !== false
 
 343         $aNewSearches = array();
 
 344         $iWordID = $oSearchTerm->iId;
 
 346         if ((!$bStructuredPhrases || $iPhrase > 0)
 
 347             && (!empty($this->aName))
 
 349             $oSearch = clone $this;
 
 350             $oSearch->iSearchRank++;
 
 351             if (preg_match('#^[0-9 ]+$#', $sToken)) {
 
 352                 $oSearch->iSearchRank++;
 
 354             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
 
 355                 $oSearch->aAddress[$iWordID] = $iWordID;
 
 357                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
 
 358                 if (!empty($aFullTokens)) {
 
 359                     $oSearch->iSearchRank++;
 
 362             $aNewSearches[] = $oSearch;
 
 365         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
 
 366             && ((empty($this->aName) && empty($this->aNameNonSearch)) || $this->iNamePhrase == $iPhrase)
 
 368             $oSearch = clone $this;
 
 369             $oSearch->iSearchRank++;
 
 370             if (empty($this->aName) && empty($this->aNameNonSearch)) {
 
 371                 $oSearch->iSearchRank++;
 
 373             if (preg_match('#^[0-9 ]+$#', $sToken)) {
 
 374                 $oSearch->iSearchRank++;
 
 376             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
 
 377                 if (empty($this->aName)
 
 378                     && CONST_Search_NameOnlySearchFrequencyThreshold
 
 380                     $oSearch->bRareName =
 
 381                         $oSearchTerm->iSearchNameCount
 
 382                           < CONST_Search_NameOnlySearchFrequencyThreshold;
 
 384                     $oSearch->bRareName = false;
 
 386                 $oSearch->aName[$iWordID] = $iWordID;
 
 388                 if (!empty($aFullTokens)) {
 
 389                     $oSearch->iSearchRank++;
 
 391                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
 
 393             $oSearch->iNamePhrase = $iPhrase;
 
 394             $aNewSearches[] = $oSearch;
 
 397         return $aNewSearches;
 
 400     /////////// Query functions
 
 404      * Query database for places that match this search.
 
 406      * @param object  $oDB      Nominatim::DB instance to use.
 
 407      * @param integer $iMinRank Minimum address rank to restrict search to.
 
 408      * @param integer $iMaxRank Maximum address rank to restrict search to.
 
 409      * @param integer $iLimit   Maximum number of results.
 
 411      * @return mixed[] An array with two fields: IDs contains the list of
 
 412      *                 matching place IDs and houseNumber the houseNumber
 
 413      *                 if appicable or -1 if not.
 
 415     public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
 
 419         if ($this->sCountryCode
 
 420             && empty($this->aName)
 
 423             && !$this->oContext->hasNearPoint()
 
 425             // Just looking for a country - look it up
 
 426             if (4 >= $iMinRank && 4 <= $iMaxRank) {
 
 427                 $aResults = $this->queryCountry($oDB);
 
 429         } elseif (empty($this->aName) && empty($this->aAddress)) {
 
 430             // Neither name nor address? Then we must be
 
 431             // looking for a POI in a geographic area.
 
 432             if ($this->oContext->isBoundedSearch()) {
 
 433                 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
 
 435         } elseif ($this->iOperator == Operator::POSTCODE) {
 
 436             // looking for postcode
 
 437             $aResults = $this->queryPostcode($oDB, $iLimit);
 
 440             // First search for places according to name and address.
 
 441             $aResults = $this->queryNamedPlace(
 
 448             // Now search for housenumber, if housenumber provided. Can be zero.
 
 449             if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
 
 450                 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
 
 452                 // Downgrade the rank of the street results, they are missing
 
 453                 // the housenumber. Also drop POI places (rank 30) here, they
 
 454                 // cannot be a parent place and therefore must not be shown
 
 455                 // as a result for a search with a missing housenumber.
 
 456                 foreach ($aResults as $oRes) {
 
 457                     if ($oRes->iAddressRank < 28) {
 
 458                         if ($oRes->iAddressRank >= 26) {
 
 459                             $oRes->iResultRank++;
 
 461                             $oRes->iResultRank += 2;
 
 463                         $aHnResults[$oRes->iId] = $oRes;
 
 467                 $aResults = $aHnResults;
 
 470             // finally get POIs if requested
 
 471             if ($this->sClass && !empty($aResults)) {
 
 472                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
 
 476         Debug::printDebugTable('Place IDs', $aResults);
 
 478         if (!empty($aResults) && $this->sPostcode) {
 
 479             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
 
 481                 $sSQL = 'SELECT place_id FROM placex';
 
 482                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
 
 483                 $sSQL .= " AND postcode != '".$this->sPostcode."'";
 
 484                 Debug::printSQL($sSQL);
 
 485                 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
 
 486                 if ($aFilteredPlaceIDs) {
 
 487                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
 
 488                         $aResults[$iPlaceId]->iResultRank++;
 
 498     private function queryCountry(&$oDB)
 
 500         $sSQL = 'SELECT place_id FROM placex ';
 
 501         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
 
 502         $sSQL .= ' AND rank_search = 4';
 
 503         if ($this->oContext->bViewboxBounded) {
 
 504             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
 
 506         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
 
 508         Debug::printSQL($sSQL);
 
 510         $iPlaceId = $oDB->getOne($sSQL);
 
 514             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 520     private function queryNearbyPoi(&$oDB, $iLimit)
 
 522         if (!$this->sClass) {
 
 526         $aDBResults = array();
 
 527         $sPoiTable = $this->poiTable();
 
 529         if ($oDB->tableExists($sPoiTable)) {
 
 530             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
 
 531             if ($this->oContext->sqlCountryList) {
 
 532                 $sSQL .= ' JOIN placex USING (place_id)';
 
 534             if ($this->oContext->hasNearPoint()) {
 
 535                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
 
 536             } elseif ($this->oContext->bViewboxBounded) {
 
 537                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
 
 539             if ($this->oContext->sqlCountryList) {
 
 540                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 542             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 543             if ($this->oContext->sqlViewboxCentre) {
 
 544                 $sSQL .= ' ORDER BY ST_Distance(';
 
 545                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
 
 546             } elseif ($this->oContext->hasNearPoint()) {
 
 547                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
 
 549             $sSQL .= " LIMIT $iLimit";
 
 550             Debug::printSQL($sSQL);
 
 551             $aDBResults = $oDB->getCol($sSQL);
 
 554         if ($this->oContext->hasNearPoint()) {
 
 555             $sSQL = 'SELECT place_id FROM placex WHERE ';
 
 556             $sSQL .= 'class = :class and type = :type';
 
 557             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
 
 558             $sSQL .= ' AND linked_place_id is null';
 
 559             if ($this->oContext->sqlCountryList) {
 
 560                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 562             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
 
 563             $sSQL .= " LIMIT $iLimit";
 
 564             Debug::printSQL($sSQL);
 
 565             $aDBResults = $oDB->getCol(
 
 567                 array(':class' => $this->sClass, ':type' => $this->sType)
 
 572         foreach ($aDBResults as $iPlaceId) {
 
 573             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 579     private function queryPostcode(&$oDB, $iLimit)
 
 581         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
 
 583         if (!empty($this->aAddress)) {
 
 584             $sSQL .= ', search_name s ';
 
 585             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
 
 586             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
 
 587             $sSQL .= '      @> '.$oDB->getArraySQL($this->aAddress).' AND ';
 
 592         $sSQL .= "p.postcode = '".reset($this->aName)."'";
 
 593         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
 
 594         if ($this->oContext->bViewboxBounded) {
 
 595             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
 
 597         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
 
 598         $sSQL .= " LIMIT $iLimit";
 
 600         Debug::printSQL($sSQL);
 
 603         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 604             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
 
 610     private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
 
 615         // Sort by existence of the requested house number but only if not
 
 616         // too many results are expected for the street, i.e. if the result
 
 617         // will be narrowed down by an address. Remeber that with ordering
 
 618         // every single result has to be checked.
 
 619         if ($this->sHouseNumber && ($this->bRareName || !empty($this->aAddress) || $this->sPostcode)) {
 
 620             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 622             $aOrder[0] .= 'EXISTS(';
 
 623             $aOrder[0] .= '  SELECT place_id';
 
 624             $aOrder[0] .= '  FROM placex';
 
 625             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 626             $aOrder[0] .= "    AND housenumber ~* E'".$sHouseNumberRegex."'";
 
 627             $aOrder[0] .= '  LIMIT 1';
 
 629             // also housenumbers from interpolation lines table are needed
 
 630             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
 
 631                 $iHouseNumber = intval($this->sHouseNumber);
 
 632                 $aOrder[0] .= 'OR EXISTS(';
 
 633                 $aOrder[0] .= '  SELECT place_id ';
 
 634                 $aOrder[0] .= '  FROM location_property_osmline ';
 
 635                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 636                 $aOrder[0] .= '    AND startnumber is not NULL';
 
 637                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
 
 638                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
 
 639                 $aOrder[0] .= '  LIMIT 1';
 
 642             $aOrder[0] .= ') DESC';
 
 645         if (!empty($this->aName)) {
 
 646             $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
 
 648         if (!empty($this->aAddress)) {
 
 649             // For infrequent name terms disable index usage for address
 
 650             if ($this->bRareName) {
 
 651                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
 
 653                 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
 
 657         $sCountryTerm = $this->countryCodeSQL('country_code');
 
 659             $aTerms[] = $sCountryTerm;
 
 662         if ($this->sHouseNumber) {
 
 663             $aTerms[] = 'address_rank between 16 and 30';
 
 664         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
 
 665             if ($iMinAddressRank > 0) {
 
 666                 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
 
 670         if ($this->oContext->hasNearPoint()) {
 
 671             $aTerms[] = $this->oContext->withinSQL('centroid');
 
 672             $aOrder[] = $this->oContext->distanceSQL('centroid');
 
 673         } elseif ($this->sPostcode) {
 
 674             if (empty($this->aAddress)) {
 
 675                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
 
 677                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
 
 681         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
 
 683             $aTerms[] = $sExcludeSQL;
 
 686         if ($this->oContext->bViewboxBounded) {
 
 687             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
 
 690         if ($this->oContext->hasNearPoint()) {
 
 691             $aOrder[] = $this->oContext->distanceSQL('centroid');
 
 694         if ($this->sHouseNumber) {
 
 695             $sImportanceSQL = '- abs(26 - address_rank) + 3';
 
 697             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
 
 699         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
 
 700         $aOrder[] = "$sImportanceSQL DESC";
 
 702         $aFullNameAddress = $this->oContext->getFullNameTerms();
 
 703         if (!empty($aFullNameAddress)) {
 
 704             $sExactMatchSQL = ' ( ';
 
 705             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
 
 706             $sExactMatchSQL .= '  SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
 
 707             $sExactMatchSQL .= '    INTERSECT ';
 
 708             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
 
 709             $sExactMatchSQL .= ' ) s';
 
 710             $sExactMatchSQL .= ') as exactmatch';
 
 711             $aOrder[] = 'exactmatch DESC';
 
 713             $sExactMatchSQL = '0::int as exactmatch';
 
 716         if ($this->sHouseNumber || $this->sClass) {
 
 722         if (!empty($aTerms)) {
 
 723             $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
 
 724             $sSQL .= ' FROM search_name';
 
 725             $sSQL .= ' WHERE '.join(' and ', $aTerms);
 
 726             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
 
 727             $sSQL .= ' LIMIT '.$iLimit;
 
 729             Debug::printSQL($sSQL);
 
 731             $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
 
 733             foreach ($aDBResults as $aResult) {
 
 734                 $oResult = new Result($aResult['place_id']);
 
 735                 $oResult->iExactMatches = $aResult['exactmatch'];
 
 736                 $oResult->iAddressRank = $aResult['address_rank'];
 
 737                 $aResults[$aResult['place_id']] = $oResult;
 
 744     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
 
 747         $sRoadPlaceIDs = Result::joinIdsByTableMaxRank(
 
 749             Result::TABLE_PLACEX,
 
 752         $sPOIPlaceIDs = Result::joinIdsByTableMinRank(
 
 754             Result::TABLE_PLACEX,
 
 758         $aIDCondition = array();
 
 759         if ($sRoadPlaceIDs) {
 
 760             $aIDCondition[] = 'parent_place_id in ('.$sRoadPlaceIDs.')';
 
 763             $aIDCondition[] = 'place_id in ('.$sPOIPlaceIDs.')';
 
 766         if (empty($aIDCondition)) {
 
 770         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 771         $sSQL = 'SELECT place_id FROM placex WHERE';
 
 772         $sSQL .= "  housenumber ~* E'".$sHouseNumberRegex."'";
 
 773         $sSQL .= ' AND ('.join(' OR ', $aIDCondition).')';
 
 774         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 776         Debug::printSQL($sSQL);
 
 778         // XXX should inherit the exactMatches from its parent
 
 779         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 780             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 783         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
 
 784         $iHousenumber = intval($this->sHouseNumber);
 
 785         if ($bIsIntHouseNumber && $sRoadPlaceIDs && empty($aResults)) {
 
 786             // if nothing found, search in the interpolation line table
 
 787             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
 
 788             $sSQL .= ' WHERE startnumber is not NULL';
 
 789             $sSQL .= '  AND parent_place_id in ('.$sRoadPlaceIDs.') AND (';
 
 790             if ($iHousenumber % 2 == 0) {
 
 791                 // If housenumber is even, look for housenumber in streets
 
 792                 // with interpolationtype even or all.
 
 793                 $sSQL .= "interpolationtype='even'";
 
 795                 // Else look for housenumber with interpolationtype odd or all.
 
 796                 $sSQL .= "interpolationtype='odd'";
 
 798             $sSQL .= " or interpolationtype='all') and ";
 
 799             $sSQL .= $iHousenumber.'>=startnumber and ';
 
 800             $sSQL .= $iHousenumber.'<=endnumber';
 
 801             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 803             Debug::printSQL($sSQL);
 
 805             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 806                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
 
 807                 $oResult->iHouseNumber = $iHousenumber;
 
 808                 $aResults[$iPlaceId] = $oResult;
 
 812         // If nothing found then search in Tiger data (location_property_tiger)
 
 813         if (CONST_Use_US_Tiger_Data && $sRoadPlaceIDs && $bIsIntHouseNumber && empty($aResults)) {
 
 814             $sSQL = 'SELECT place_id FROM location_property_tiger';
 
 815             $sSQL .= ' WHERE parent_place_id in ('.$sRoadPlaceIDs.') and (';
 
 816             if ($iHousenumber % 2 == 0) {
 
 817                 $sSQL .= "interpolationtype='even'";
 
 819                 $sSQL .= "interpolationtype='odd'";
 
 821             $sSQL .= " or interpolationtype='all') and ";
 
 822             $sSQL .= $iHousenumber.'>=startnumber and ';
 
 823             $sSQL .= $iHousenumber.'<=endnumber';
 
 824             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 826             Debug::printSQL($sSQL);
 
 828             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 829                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
 
 830                 $oResult->iHouseNumber = $iHousenumber;
 
 831                 $aResults[$iPlaceId] = $oResult;
 
 839     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
 
 842         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
 
 848         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
 
 849             // If they were searching for a named class (i.e. 'Kings Head pub')
 
 850             // then we might have an extra match
 
 851             $sSQL = 'SELECT place_id FROM placex ';
 
 852             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
 853             $sSQL .= "   AND class='".$this->sClass."' ";
 
 854             $sSQL .= "   AND type='".$this->sType."'";
 
 855             $sSQL .= '   AND linked_place_id is null';
 
 856             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 857             $sSQL .= ' ORDER BY rank_search ASC ';
 
 858             $sSQL .= " LIMIT $iLimit";
 
 860             Debug::printSQL($sSQL);
 
 862             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 863                 $aResults[$iPlaceId] = new Result($iPlaceId);
 
 867         // NEAR and IN are handled the same
 
 868         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
 
 869             $sClassTable = $this->poiTable();
 
 870             $bCacheTable = $oDB->tableExists($sClassTable);
 
 872             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
 
 873             Debug::printSQL($sSQL);
 
 874             $iMaxRank = (int) $oDB->getOne($sSQL);
 
 876             // For state / country level searches the normal radius search doesn't work very well
 
 878             if ($iMaxRank < 9 && $bCacheTable) {
 
 879                 // Try and get a polygon to search in instead
 
 880                 $sSQL = 'SELECT geometry FROM placex';
 
 881                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
 882                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
 
 883                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
 
 884                 $sSQL .= ' ORDER BY rank_search ASC ';
 
 886                 Debug::printSQL($sSQL);
 
 887                 $sPlaceGeom = $oDB->getOne($sSQL);
 
 894                 $sSQL = 'SELECT place_id FROM placex';
 
 895                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 896                 Debug::printSQL($sSQL);
 
 897                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 898                 $sPlaceIDs = join(',', $aPlaceIDs);
 
 901             if ($sPlaceIDs || $sPlaceGeom) {
 
 904                     // More efficient - can make the range bigger
 
 908                     if ($this->oContext->hasNearPoint()) {
 
 909                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
 
 910                     } elseif ($sPlaceIDs) {
 
 911                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
 
 912                     } elseif ($sPlaceGeom) {
 
 913                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
 916                     $sSQL = 'SELECT distinct i.place_id';
 
 918                         $sSQL .= ', i.order_term';
 
 920                     $sSQL .= ' from (SELECT l.place_id';
 
 922                         $sSQL .= ','.$sOrderBySQL.' as order_term';
 
 924                     $sSQL .= ' from '.$sClassTable.' as l';
 
 927                         $sSQL .= ',placex as f WHERE ';
 
 928                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
 
 929                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
 
 930                     } elseif ($sPlaceGeom) {
 
 931                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
 
 934                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
 
 935                     $sSQL .= 'limit 300) i ';
 
 937                         $sSQL .= 'order by order_term asc';
 
 939                     $sSQL .= " limit $iLimit";
 
 941                     Debug::printSQL($sSQL);
 
 943                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 944                         $aResults[$iPlaceId] = new Result($iPlaceId);
 
 947                     if ($this->oContext->hasNearPoint()) {
 
 948                         $fRange = $this->oContext->nearRadius();
 
 952                     if ($this->oContext->hasNearPoint()) {
 
 953                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
 
 955                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
 
 958                     $sSQL = 'SELECT distinct l.place_id';
 
 960                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
 
 962                     $sSQL .= ' FROM placex as l, placex as f';
 
 963                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
 
 964                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
 
 965                     $sSQL .= "  AND l.class='".$this->sClass."'";
 
 966                     $sSQL .= "  AND l.type='".$this->sType."'";
 
 967                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
 
 969                         $sSQL .= 'ORDER BY orderterm ASC';
 
 971                     $sSQL .= " limit $iLimit";
 
 973                     Debug::printSQL($sSQL);
 
 975                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 976                         $aResults[$iPlaceId] = new Result($iPlaceId);
 
 985     private function poiTable()
 
 987         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
 
 990     private function countryCodeSQL($sVar)
 
 992         if ($this->sCountryCode) {
 
 993             return $sVar.' = \''.$this->sCountryCode."'";
 
 995         if ($this->oContext->sqlCountryList) {
 
 996             return $sVar.' in '.$this->oContext->sqlCountryList;
 
1002     /////////// Sort functions
 
1005     public static function bySearchRank($a, $b)
 
1007         if ($a->iSearchRank == $b->iSearchRank) {
 
1008             return $a->iOperator + strlen($a->sHouseNumber)
 
1009                      - $b->iOperator - strlen($b->sHouseNumber);
 
1012         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
 
1015     //////////// Debugging functions
 
1018     public function debugInfo()
 
1021                 'Search rank' => $this->iSearchRank,
 
1022                 'Country code' => $this->sCountryCode,
 
1023                 'Name terms' => $this->aName,
 
1024                 'Name terms (stop words)' => $this->aNameNonSearch,
 
1025                 'Address terms' => $this->aAddress,
 
1026                 'Address terms (stop words)' => $this->aAddressNonSearch,
 
1027                 'Address terms (full words)' => $this->aFullNameAddress ?? '',
 
1028                 'Special search' => $this->iOperator,
 
1029                 'Class' => $this->sClass,
 
1030                 'Type' => $this->sType,
 
1031                 'House number' => $this->sHouseNumber,
 
1032                 'Postcode' => $this->sPostcode
 
1036     public function dumpAsHtmlTableRow(&$aWordIDs)
 
1038         $kf = function ($k) use (&$aWordIDs) {
 
1039             return $aWordIDs[$k] ?? '['.$k.']';
 
1043         echo "<td>$this->iSearchRank</td>";
 
1044         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
 
1045         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
 
1046         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
 
1047         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
 
1048         echo '<td>'.$this->sCountryCode.'</td>';
 
1049         echo '<td>'.Operator::toString($this->iOperator).'</td>';
 
1050         echo '<td>'.$this->sClass.'</td>';
 
1051         echo '<td>'.$this->sType.'</td>';
 
1052         echo '<td>'.$this->sPostcode.'</td>';
 
1053         echo '<td>'.$this->sHouseNumber.'</td>';