5 require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
 
   6 require_once(CONST_BasePath.'/lib/SearchContext.php');
 
   7 require_once(CONST_BasePath.'/lib/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     /// Subset of word ids of full words making up the address.
 
  25     private $aFullNameAddress = array();
 
  26     /// List of word ids that appear in the name but should be ignored.
 
  27     private $aNameNonSearch = array();
 
  28     /// List of word ids that appear in the address but should be ignored.
 
  29     private $aAddressNonSearch = array();
 
  30     /// Kind of search for special searches, see Nominatim::Operator.
 
  31     private $iOperator = Operator::NONE;
 
  32     /// Class of special feature to search for.
 
  34     /// Type of special feature to search for.
 
  36     /// Housenumber of the object.
 
  37     private $sHouseNumber = '';
 
  38     /// Postcode for the object.
 
  39     private $sPostcode = '';
 
  40     /// Global search constraints.
 
  43     // Temporary values used while creating the search description.
 
  45     /// Index of phrase currently processed.
 
  46     private $iNamePhrase = -1;
 
  49      * Create an empty search description.
 
  51      * @param object $oContext Global context to use. Will be inherited by
 
  52      *                         all derived search objects.
 
  54     public function __construct($oContext)
 
  56         $this->oContext = $oContext;
 
  60      * Get current search rank.
 
  62      * The higher the search rank the lower the likelihood that the
 
  63      * search is a correct interpretation of the search query.
 
  65      * @return integer Search rank.
 
  67     public function getRank()
 
  69         return $this->iSearchRank;
 
  73      * Make this search a POI search.
 
  75      * In a POI search, objects are not (only) searched by their name
 
  76      * but also by the primary OSM key/value pair (class and type in Nominatim).
 
  78      * @param integer $iOperator Type of POI search
 
  79      * @param string  $sClass    Class (or OSM tag key) of POI.
 
  80      * @param string  $sType     Type (or OSM tag value) of POI.
 
  84     public function setPoiSearch($iOperator, $sClass, $sType)
 
  86         $this->iOperator = $iOperator;
 
  87         $this->sClass = $sClass;
 
  88         $this->sType = $sType;
 
  92      * Check if this might be a full address search.
 
  94      * @return bool True if the search contains name, address and housenumber.
 
  96     public function looksLikeFullAddress()
 
  98         return (!empty($this->aName))
 
  99                && (!empty($this->aAddress) || $this->sCountryCode)
 
 100                && preg_match('/[0-9]+/', $this->sHouseNumber);
 
 104      * Check if any operator is set.
 
 106      * @return bool True, if this is a special search operation.
 
 108     public function hasOperator()
 
 110         return $this->iOperator != Operator::NONE;
 
 114      * Extract key/value pairs from a query.
 
 116      * Key/value pairs are recognised if they are of the form [<key>=<value>].
 
 117      * If multiple terms of this kind are found then all terms are removed
 
 118      * but only the first is used for search.
 
 120      * @param string $sQuery Original query string.
 
 122      * @return string The query string with the special search patterns removed.
 
 124     public function extractKeyValuePairs($sQuery)
 
 126         // Search for terms of kind [<key>=<value>].
 
 128             '/\\[([\\w_]*)=([\\w_]*)\\]/',
 
 134         foreach ($aSpecialTermsRaw as $aTerm) {
 
 135             $sQuery = str_replace($aTerm[0], ' ', $sQuery);
 
 136             if (!$this->hasOperator()) {
 
 137                 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
 
 145      * Check if the combination of parameters is sensible.
 
 147      * @return bool True, if the search looks valid.
 
 149     public function isValidSearch()
 
 151         if (empty($this->aName)) {
 
 152             if ($this->sHouseNumber) {
 
 155             if (!$this->sClass && !$this->sCountryCode) {
 
 163     /////////// Search building functions
 
 167      * Derive new searches by adding a full term to the existing search.
 
 169      * @param object $oSearchTerm  Description of the token.
 
 170      * @param bool   $bHasPartial  True if there are also tokens of partial terms
 
 171      *                             with the same name.
 
 172      * @param string $sPhraseType  Type of phrase the token is contained in.
 
 173      * @param bool   $bFirstToken  True if the token is at the beginning of the
 
 175      * @param bool   $bFirstPhrase True if the token is in the first phrase of
 
 177      * @param bool   $bLastToken   True if the token is at the end of the query.
 
 179      * @return SearchDescription[] List of derived search descriptions.
 
 181     public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
 
 183         $aNewSearches = array();
 
 185         if (($sPhraseType == '' || $sPhraseType == 'country')
 
 186             && is_a($oSearchTerm, '\Nominatim\Token\Country')
 
 188             if (!$this->sCountryCode) {
 
 189                 $oSearch = clone $this;
 
 190                 $oSearch->iSearchRank++;
 
 191                 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
 
 192                 // Country is almost always at the end of the string
 
 193                 // - increase score for finding it anywhere else (optimisation)
 
 195                     $oSearch->iSearchRank += 5;
 
 197                 $aNewSearches[] = $oSearch;
 
 199         } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
 
 200                   && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
 
 202             // We need to try the case where the postal code is the primary element
 
 203             // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
 
 205             if (!$this->sPostcode) {
 
 206                 // If we have structured search or this is the first term,
 
 207                 // make the postcode the primary search element.
 
 208                 if ($this->iOperator == Operator::NONE
 
 209                     && ($sPhraseType == 'postalcode' || $bFirstToken)
 
 211                     $oSearch = clone $this;
 
 212                     $oSearch->iSearchRank++;
 
 213                     $oSearch->iOperator = Operator::POSTCODE;
 
 214                     $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
 
 216                         array($oSearchTerm->iId => $oSearchTerm->sPostcode);
 
 217                     $aNewSearches[] = $oSearch;
 
 220                 // If we have a structured search or this is not the first term,
 
 221                 // add the postcode as an addendum.
 
 222                 if ($this->iOperator != Operator::POSTCODE
 
 223                     && ($sPhraseType == 'postalcode' || !empty($this->aName))
 
 225                     $oSearch = clone $this;
 
 226                     $oSearch->iSearchRank++;
 
 227                     $oSearch->sPostcode = $oSearchTerm->sPostcode;
 
 228                     $aNewSearches[] = $oSearch;
 
 231         } elseif (($sPhraseType == '' || $sPhraseType == 'street')
 
 232                  && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
 
 234             if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
 
 235                 $oSearch = clone $this;
 
 236                 $oSearch->iSearchRank++;
 
 237                 $oSearch->sHouseNumber = $oSearchTerm->sToken;
 
 238                 // sanity check: if the housenumber is not mainly made
 
 239                 // up of numbers, add a penalty
 
 240                 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
 
 241                     || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
 
 242                     $oSearch->iSearchRank++;
 
 244                 if (empty($oSearchTerm->iId)) {
 
 245                     $oSearch->iSearchRank++;
 
 247                 // also must not appear in the middle of the address
 
 248                 if (!empty($this->aAddress)
 
 249                     || (!empty($this->aAddressNonSearch))
 
 252                     $oSearch->iSearchRank++;
 
 254                 $aNewSearches[] = $oSearch;
 
 256         } elseif ($sPhraseType == ''
 
 257                   && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
 
 259             if ($this->iOperator == Operator::NONE) {
 
 260                 $oSearch = clone $this;
 
 261                 $oSearch->iSearchRank++;
 
 263                 $iOp = $oSearchTerm->iOperator;
 
 264                 if ($iOp == Operator::NONE) {
 
 265                     if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
 
 266                         $iOp = Operator::NAME;
 
 268                         $iOp = Operator::NEAR;
 
 270                     $oSearch->iSearchRank += 2;
 
 273                 $oSearch->setPoiSearch(
 
 275                     $oSearchTerm->sClass,
 
 278                 $aNewSearches[] = $oSearch;
 
 280         } elseif ($sPhraseType != 'country'
 
 281                   && is_a($oSearchTerm, '\Nominatim\Token\Word')
 
 283             $iWordID = $oSearchTerm->iId;
 
 284             // Full words can only be a name if they appear at the beginning
 
 285             // of the phrase. In structured search the name must forcably in
 
 286             // the first phrase. In unstructured search it may be in a later
 
 287             // phrase when the first phrase is a house number.
 
 288             if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
 
 289                 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
 
 290                     $oSearch = clone $this;
 
 291                     $oSearch->iSearchRank += 2;
 
 292                     $oSearch->aAddress[$iWordID] = $iWordID;
 
 293                     $aNewSearches[] = $oSearch;
 
 295                     $this->aFullNameAddress[$iWordID] = $iWordID;
 
 298                 $oSearch = clone $this;
 
 299                 $oSearch->iSearchRank++;
 
 300                 $oSearch->aName = array($iWordID => $iWordID);
 
 301                 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
 
 302                     $oSearch->bRareName =
 
 303                         $oSearchTerm->iSearchNameCount
 
 304                           < CONST_Search_NameOnlySearchFrequencyThreshold;
 
 306                 $aNewSearches[] = $oSearch;
 
 310         return $aNewSearches;
 
 314      * Derive new searches by adding a partial term to the existing search.
 
 316      * @param string  $sToken             Term for the token.
 
 317      * @param object  $oSearchTerm        Description of the token.
 
 318      * @param bool    $bStructuredPhrases True if the search is structured.
 
 319      * @param integer $iPhrase            Number of the phrase the token is in.
 
 320      * @param array[] $aFullTokens        List of full term tokens with the
 
 323      * @return SearchDescription[] List of derived search descriptions.
 
 325     public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
 
 327         // Only allow name terms.
 
 328         if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
 
 332         $aNewSearches = array();
 
 333         $iWordID = $oSearchTerm->iId;
 
 335         if ((!$bStructuredPhrases || $iPhrase > 0)
 
 336             && (!empty($this->aName))
 
 337             && strpos($sToken, ' ') === false
 
 339             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
 
 340                 $oSearch = clone $this;
 
 341                 $oSearch->iSearchRank += 2;
 
 342                 $oSearch->aAddress[$iWordID] = $iWordID;
 
 343                 $aNewSearches[] = $oSearch;
 
 345                 $oSearch = clone $this;
 
 346                 $oSearch->iSearchRank++;
 
 347                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
 
 348                 if (preg_match('#^[0-9]+$#', $sToken)) {
 
 349                     $oSearch->iSearchRank += 2;
 
 351                 if (!empty($aFullTokens)) {
 
 352                     $oSearch->iSearchRank++;
 
 354                 $aNewSearches[] = $oSearch;
 
 356                 // revert to the token version?
 
 357                 foreach ($aFullTokens as $oSearchTermToken) {
 
 358                     if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
 
 359                         $oSearch = clone $this;
 
 360                         $oSearch->iSearchRank++;
 
 361                         $oSearch->aAddress[$oSearchTermToken->iId]
 
 362                             = $oSearchTermToken->iId;
 
 363                         $aNewSearches[] = $oSearch;
 
 369         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
 
 370             && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
 
 372             $oSearch = clone $this;
 
 373             $oSearch->iSearchRank += 2;
 
 374             if (empty($this->aName)) {
 
 375                 $oSearch->iSearchRank += 1;
 
 377             if (preg_match('#^[0-9]+$#', $sToken)) {
 
 378                 $oSearch->iSearchRank += 2;
 
 380             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
 
 381                 if (empty($this->aName)
 
 382                     && CONST_Search_NameOnlySearchFrequencyThreshold
 
 384                     $oSearch->bRareName =
 
 385                         $oSearchTerm->iSearchNameCount
 
 386                           < CONST_Search_NameOnlySearchFrequencyThreshold;
 
 388                     $oSearch->bRareName = false;
 
 390                 $oSearch->aName[$iWordID] = $iWordID;
 
 392                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
 
 394             $oSearch->iNamePhrase = $iPhrase;
 
 395             $aNewSearches[] = $oSearch;
 
 398         return $aNewSearches;
 
 401     /////////// Query functions
 
 405      * Query database for places that match this search.
 
 407      * @param object  $oDB      Nominatim::DB instance to use.
 
 408      * @param integer $iMinRank Minimum address rank to restrict search to.
 
 409      * @param integer $iMaxRank Maximum address rank to restrict search to.
 
 410      * @param integer $iLimit   Maximum number of results.
 
 412      * @return mixed[] An array with two fields: IDs contains the list of
 
 413      *                 matching place IDs and houseNumber the houseNumber
 
 414      *                 if appicable or -1 if not.
 
 416     public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
 
 421         if ($this->sCountryCode
 
 422             && empty($this->aName)
 
 425             && !$this->oContext->hasNearPoint()
 
 427             // Just looking for a country - look it up
 
 428             if (4 >= $iMinRank && 4 <= $iMaxRank) {
 
 429                 $aResults = $this->queryCountry($oDB);
 
 431         } elseif (empty($this->aName) && empty($this->aAddress)) {
 
 432             // Neither name nor address? Then we must be
 
 433             // looking for a POI in a geographic area.
 
 434             if ($this->oContext->isBoundedSearch()) {
 
 435                 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
 
 437         } elseif ($this->iOperator == Operator::POSTCODE) {
 
 438             // looking for postcode
 
 439             $aResults = $this->queryPostcode($oDB, $iLimit);
 
 442             // First search for places according to name and address.
 
 443             $aResults = $this->queryNamedPlace(
 
 450             //now search for housenumber, if housenumber provided
 
 451             if ($this->sHouseNumber && !empty($aResults)) {
 
 452                 // Downgrade the rank of the street results, they are missing
 
 454                 foreach ($aResults as $oRes) {
 
 455                     $oRes->iResultRank++;
 
 458                 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
 
 460                 if (!empty($aHnResults)) {
 
 461                     foreach ($aHnResults as $oRes) {
 
 462                         $aResults[$oRes->iId] = $oRes;
 
 467             // finally get POIs if requested
 
 468             if ($this->sClass && !empty($aResults)) {
 
 469                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
 
 473         Debug::printDebugTable('Place IDs', $aResults);
 
 475         if (!empty($aResults) && $this->sPostcode) {
 
 476             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
 
 478                 $sSQL = 'SELECT place_id FROM placex';
 
 479                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
 
 480                 $sSQL .= " AND postcode != '".$this->sPostcode."'";
 
 481                 Debug::printSQL($sSQL);
 
 482                 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
 
 483                 if ($aFilteredPlaceIDs) {
 
 484                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
 
 485                         $aResults[$iPlaceId]->iResultRank++;
 
 495     private function queryCountry(&$oDB)
 
 497         $sSQL = 'SELECT place_id FROM placex ';
 
 498         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
 
 499         $sSQL .= ' AND rank_search = 4';
 
 500         if ($this->oContext->bViewboxBounded) {
 
 501             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
 
 503         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
 
 505         Debug::printSQL($sSQL);
 
 507         $iPlaceId = $oDB->getOne($sSQL);
 
 511             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 517     private function queryNearbyPoi(&$oDB, $iLimit)
 
 519         if (!$this->sClass) {
 
 523         $aDBResults = array();
 
 524         $sPoiTable = $this->poiTable();
 
 526         if ($oDB->tableExists($sPoiTable)) {
 
 527             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
 
 528             if ($this->oContext->sqlCountryList) {
 
 529                 $sSQL .= ' JOIN placex USING (place_id)';
 
 531             if ($this->oContext->hasNearPoint()) {
 
 532                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
 
 533             } elseif ($this->oContext->bViewboxBounded) {
 
 534                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
 
 536             if ($this->oContext->sqlCountryList) {
 
 537                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 539             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 540             if ($this->oContext->sqlViewboxCentre) {
 
 541                 $sSQL .= ' ORDER BY ST_Distance(';
 
 542                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
 
 543             } elseif ($this->oContext->hasNearPoint()) {
 
 544                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
 
 546             $sSQL .= " LIMIT $iLimit";
 
 547             Debug::printSQL($sSQL);
 
 548             $aDBResults = $oDB->getCol($sSQL);
 
 551         if ($this->oContext->hasNearPoint()) {
 
 552             $sSQL = 'SELECT place_id FROM placex WHERE ';
 
 553             $sSQL .= 'class = :class and type = :type';
 
 554             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
 
 555             $sSQL .= ' AND linked_place_id is null';
 
 556             if ($this->oContext->sqlCountryList) {
 
 557                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 559             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
 
 560             $sSQL .= " LIMIT $iLimit";
 
 561             Debug::printSQL($sSQL);
 
 562             $aDBResults = $oDB->getCol(
 
 564                 array(':class' => $this->sClass, ':type' => $this->sType)
 
 569         foreach ($aDBResults as $iPlaceId) {
 
 570             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 576     private function queryPostcode(&$oDB, $iLimit)
 
 578         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
 
 580         if (!empty($this->aAddress)) {
 
 581             $sSQL .= ', search_name s ';
 
 582             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
 
 583             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
 
 584             $sSQL .= '      @> '.$oDB->getArraySQL($this->aAddress).' AND ';
 
 589         $sSQL .= "p.postcode = '".reset($this->aName)."'";
 
 590         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
 
 591         if ($this->oContext->bViewboxBounded) {
 
 592             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
 
 594         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
 
 595         $sSQL .= " LIMIT $iLimit";
 
 597         Debug::printSQL($sSQL);
 
 600         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 601             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
 
 607     private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
 
 612         // Sort by existence of the requested house number but only if not
 
 613         // too many results are expected for the street, i.e. if the result
 
 614         // will be narrowed down by an address. Remeber that with ordering
 
 615         // every single result has to be checked.
 
 616         if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
 
 617             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 619             $aOrder[0] .= 'EXISTS(';
 
 620             $aOrder[0] .= '  SELECT place_id';
 
 621             $aOrder[0] .= '  FROM placex';
 
 622             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 623             $aOrder[0] .= "    AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
 624             $aOrder[0] .= '  LIMIT 1';
 
 626             // also housenumbers from interpolation lines table are needed
 
 627             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
 
 628                 $iHouseNumber = intval($this->sHouseNumber);
 
 629                 $aOrder[0] .= 'OR EXISTS(';
 
 630                 $aOrder[0] .= '  SELECT place_id ';
 
 631                 $aOrder[0] .= '  FROM location_property_osmline ';
 
 632                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 633                 $aOrder[0] .= '    AND startnumber is not NULL';
 
 634                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
 
 635                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
 
 636                 $aOrder[0] .= '  LIMIT 1';
 
 639             $aOrder[0] .= ') DESC';
 
 642         if (!empty($this->aName)) {
 
 643             $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
 
 645         if (!empty($this->aAddress)) {
 
 646             // For infrequent name terms disable index usage for address
 
 647             if ($this->bRareName) {
 
 648                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
 
 650                 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
 
 654         $sCountryTerm = $this->countryCodeSQL('country_code');
 
 656             $aTerms[] = $sCountryTerm;
 
 659         if ($this->sHouseNumber) {
 
 660             $aTerms[] = 'address_rank between 16 and 27';
 
 661         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
 
 662             if ($iMinAddressRank > 0) {
 
 663                 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
 
 665             if ($iMaxAddressRank < 30) {
 
 666                 $aTerms[] = 'address_rank <= '.$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         if (!empty($this->aFullNameAddress)) {
 
 703             $sExactMatchSQL = ' ( ';
 
 704             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
 
 705             $sExactMatchSQL .= '  SELECT unnest('.$oDB->getArraySQL($this->aFullNameAddress).')';
 
 706             $sExactMatchSQL .= '    INTERSECT ';
 
 707             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
 
 708             $sExactMatchSQL .= ' ) s';
 
 709             $sExactMatchSQL .= ') as exactmatch';
 
 710             $aOrder[] = 'exactmatch DESC';
 
 712             $sExactMatchSQL = '0::int as exactmatch';
 
 715         if ($this->sHouseNumber || $this->sClass) {
 
 721         if (!empty($aTerms)) {
 
 722             $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
 
 723             $sSQL .= ' FROM search_name';
 
 724             $sSQL .= ' WHERE '.join(' and ', $aTerms);
 
 725             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
 
 726             $sSQL .= ' LIMIT '.$iLimit;
 
 728             Debug::printSQL($sSQL);
 
 730             $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
 
 732             foreach ($aDBResults as $aResult) {
 
 733                 $oResult = new Result($aResult['place_id']);
 
 734                 $oResult->iExactMatches = $aResult['exactmatch'];
 
 735                 $aResults[$aResult['place_id']] = $oResult;
 
 742     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
 
 745         $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
 
 751         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 752         $sSQL = 'SELECT place_id FROM placex ';
 
 753         $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
 
 754         $sSQL .= "  AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
 755         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 757         Debug::printSQL($sSQL);
 
 759         // XXX should inherit the exactMatches from its parent
 
 760         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 761             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 764         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
 
 765         $iHousenumber = intval($this->sHouseNumber);
 
 766         if ($bIsIntHouseNumber && empty($aResults)) {
 
 767             // if nothing found, search in the interpolation line table
 
 768             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
 
 769             $sSQL .= ' WHERE startnumber is not NULL';
 
 770             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
 
 771             if ($iHousenumber % 2 == 0) {
 
 772                 // If housenumber is even, look for housenumber in streets
 
 773                 // with interpolationtype even or all.
 
 774                 $sSQL .= "interpolationtype='even'";
 
 776                 // Else look for housenumber with interpolationtype odd or all.
 
 777                 $sSQL .= "interpolationtype='odd'";
 
 779             $sSQL .= " or interpolationtype='all') and ";
 
 780             $sSQL .= $iHousenumber.'>=startnumber and ';
 
 781             $sSQL .= $iHousenumber.'<=endnumber';
 
 782             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 784             Debug::printSQL($sSQL);
 
 786             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 787                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
 
 788                 $oResult->iHouseNumber = $iHousenumber;
 
 789                 $aResults[$iPlaceId] = $oResult;
 
 793         // If nothing found try the aux fallback table
 
 794         if (CONST_Use_Aux_Location_data && empty($aResults)) {
 
 795             $sSQL = 'SELECT place_id FROM location_property_aux';
 
 796             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
 
 797             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
 
 798             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 800             Debug::printSQL($sSQL);
 
 802             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 803                 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
 
 807         // If nothing found then search in Tiger data (location_property_tiger)
 
 808         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
 
 809             $sSQL = 'SELECT place_id FROM location_property_tiger';
 
 810             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
 
 811             if ($iHousenumber % 2 == 0) {
 
 812                 $sSQL .= "interpolationtype='even'";
 
 814                 $sSQL .= "interpolationtype='odd'";
 
 816             $sSQL .= " or interpolationtype='all') and ";
 
 817             $sSQL .= $iHousenumber.'>=startnumber and ';
 
 818             $sSQL .= $iHousenumber.'<=endnumber';
 
 819             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 821             Debug::printSQL($sSQL);
 
 823             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 824                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
 
 825                 $oResult->iHouseNumber = $iHousenumber;
 
 826                 $aResults[$iPlaceId] = $oResult;
 
 834     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
 
 837         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
 
 843         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
 
 844             // If they were searching for a named class (i.e. 'Kings Head pub')
 
 845             // then we might have an extra match
 
 846             $sSQL = 'SELECT place_id FROM placex ';
 
 847             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
 848             $sSQL .= "   AND class='".$this->sClass."' ";
 
 849             $sSQL .= "   AND type='".$this->sType."'";
 
 850             $sSQL .= '   AND linked_place_id is null';
 
 851             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 852             $sSQL .= ' ORDER BY rank_search ASC ';
 
 853             $sSQL .= " LIMIT $iLimit";
 
 855             Debug::printSQL($sSQL);
 
 857             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 858                 $aResults[$iPlaceId] = new Result($iPlaceId);
 
 862         // NEAR and IN are handled the same
 
 863         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
 
 864             $sClassTable = $this->poiTable();
 
 865             $bCacheTable = $oDB->tableExists($sClassTable);
 
 867             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
 
 868             Debug::printSQL($sSQL);
 
 869             $iMaxRank = (int) $oDB->getOne($sSQL);
 
 871             // For state / country level searches the normal radius search doesn't work very well
 
 873             if ($iMaxRank < 9 && $bCacheTable) {
 
 874                 // Try and get a polygon to search in instead
 
 875                 $sSQL = 'SELECT geometry FROM placex';
 
 876                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
 877                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
 
 878                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
 
 879                 $sSQL .= ' ORDER BY rank_search ASC ';
 
 881                 Debug::printSQL($sSQL);
 
 882                 $sPlaceGeom = $oDB->getOne($sSQL);
 
 889                 $sSQL = 'SELECT place_id FROM placex';
 
 890                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 891                 Debug::printSQL($sSQL);
 
 892                 $aPlaceIDs = $oDB->getCol($sSQL);
 
 893                 $sPlaceIDs = join(',', $aPlaceIDs);
 
 896             if ($sPlaceIDs || $sPlaceGeom) {
 
 899                     // More efficient - can make the range bigger
 
 903                     if ($this->oContext->hasNearPoint()) {
 
 904                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
 
 905                     } elseif ($sPlaceIDs) {
 
 906                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
 
 907                     } elseif ($sPlaceGeom) {
 
 908                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
 911                     $sSQL = 'SELECT distinct i.place_id';
 
 913                         $sSQL .= ', i.order_term';
 
 915                     $sSQL .= ' from (SELECT l.place_id';
 
 917                         $sSQL .= ','.$sOrderBySQL.' as order_term';
 
 919                     $sSQL .= ' from '.$sClassTable.' as l';
 
 922                         $sSQL .= ',placex as f WHERE ';
 
 923                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
 
 924                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
 
 925                     } elseif ($sPlaceGeom) {
 
 926                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
 
 929                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
 
 930                     $sSQL .= 'limit 300) i ';
 
 932                         $sSQL .= 'order by order_term asc';
 
 934                     $sSQL .= " limit $iLimit";
 
 936                     Debug::printSQL($sSQL);
 
 938                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 939                         $aResults[$iPlaceId] = new Result($iPlaceId);
 
 942                     if ($this->oContext->hasNearPoint()) {
 
 943                         $fRange = $this->oContext->nearRadius();
 
 947                     if ($this->oContext->hasNearPoint()) {
 
 948                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
 
 950                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
 
 953                     $sSQL = 'SELECT distinct l.place_id';
 
 955                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
 
 957                     $sSQL .= ' FROM placex as l, placex as f';
 
 958                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
 
 959                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
 
 960                     $sSQL .= "  AND l.class='".$this->sClass."'";
 
 961                     $sSQL .= "  AND l.type='".$this->sType."'";
 
 962                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
 
 964                         $sSQL .= 'ORDER BY orderterm ASC';
 
 966                     $sSQL .= " limit $iLimit";
 
 968                     Debug::printSQL($sSQL);
 
 970                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
 
 971                         $aResults[$iPlaceId] = new Result($iPlaceId);
 
 980     private function poiTable()
 
 982         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
 
 985     private function countryCodeSQL($sVar)
 
 987         if ($this->sCountryCode) {
 
 988             return $sVar.' = \''.$this->sCountryCode."'";
 
 990         if ($this->oContext->sqlCountryList) {
 
 991             return $sVar.' in '.$this->oContext->sqlCountryList;
 
 997     /////////// Sort functions
 
1000     public static function bySearchRank($a, $b)
 
1002         if ($a->iSearchRank == $b->iSearchRank) {
 
1003             return $a->iOperator + strlen($a->sHouseNumber)
 
1004                      - $b->iOperator - strlen($b->sHouseNumber);
 
1007         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
 
1010     //////////// Debugging functions
 
1013     public function debugInfo()
 
1016                 'Search rank' => $this->iSearchRank,
 
1017                 'Country code' => $this->sCountryCode,
 
1018                 'Name terms' => $this->aName,
 
1019                 'Name terms (stop words)' => $this->aNameNonSearch,
 
1020                 'Address terms' => $this->aAddress,
 
1021                 'Address terms (stop words)' => $this->aAddressNonSearch,
 
1022                 'Address terms (full words)' => $this->aFullNameAddress,
 
1023                 'Special search' => $this->iOperator,
 
1024                 'Class' => $this->sClass,
 
1025                 'Type' => $this->sType,
 
1026                 'House number' => $this->sHouseNumber,
 
1027                 'Postcode' => $this->sPostcode
 
1031     public function dumpAsHtmlTableRow(&$aWordIDs)
 
1033         $kf = function ($k) use (&$aWordIDs) {
 
1034             return $aWordIDs[$k];
 
1038         echo "<td>$this->iSearchRank</td>";
 
1039         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
 
1040         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
 
1041         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
 
1042         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
 
1043         echo '<td>'.$this->sCountryCode.'</td>';
 
1044         echo '<td>'.Operator::toString($this->iOperator).'</td>';
 
1045         echo '<td>'.$this->sClass.'</td>';
 
1046         echo '<td>'.$this->sType.'</td>';
 
1047         echo '<td>'.$this->sPostcode.'</td>';
 
1048         echo '<td>'.$this->sHouseNumber.'</td>';