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     /// List of word ids making up the address of the object.
 
  21     private $aAddress = array();
 
  22     /// Subset of word ids of full words making up the address.
 
  23     private $aFullNameAddress = 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;
 
  48      * Create an empty search description.
 
  50      * @param object $oContext Global context to use. Will be inherited by
 
  51      *                         all derived search objects.
 
  53     public function __construct($oContext)
 
  55         $this->oContext = $oContext;
 
  59      * Get current search rank.
 
  61      * The higher the search rank the lower the likelihood that the
 
  62      * search is a correct interpretation of the search query.
 
  64      * @return integer Search rank.
 
  66     public function getRank()
 
  68         return $this->iSearchRank;
 
  72      * Make this search a POI search.
 
  74      * In a POI search, objects are not (only) searched by their name
 
  75      * but also by the primary OSM key/value pair (class and type in Nominatim).
 
  77      * @param integer $iOperator Type of POI search
 
  78      * @param string  $sClass    Class (or OSM tag key) of POI.
 
  79      * @param string  $sType     Type (or OSM tag value) of POI.
 
  83     public function setPoiSearch($iOperator, $sClass, $sType)
 
  85         $this->iOperator = $iOperator;
 
  86         $this->sClass = $sClass;
 
  87         $this->sType = $sType;
 
  91      * Check if this might be a full address search.
 
  93      * @return bool True if the search contains name, address and housenumber.
 
  95     public function looksLikeFullAddress()
 
  97         return sizeof($this->aName)
 
  98                && (sizeof($this->aAddress || $this->sCountryCode))
 
  99                && preg_match('/[0-9]+/', $this->sHouseNumber);
 
 103      * Check if any operator is set.
 
 105      * @return bool True, if this is a special search operation.
 
 107     public function hasOperator()
 
 109         return $this->iOperator != Operator::NONE;
 
 113      * Extract key/value pairs from a query.
 
 115      * Key/value pairs are recognised if they are of the form [<key>=<value>].
 
 116      * If multiple terms of this kind are found then all terms are removed
 
 117      * but only the first is used for search.
 
 119      * @param string $sQuery Original query string.
 
 121      * @return string The query string with the special search patterns removed.
 
 123     public function extractKeyValuePairs($sQuery)
 
 125         // Search for terms of kind [<key>=<value>].
 
 127             '/\\[([\\w_]*)=([\\w_]*)\\]/',
 
 133         foreach ($aSpecialTermsRaw as $aTerm) {
 
 134             $sQuery = str_replace($aTerm[0], ' ', $sQuery);
 
 135             if (!$this->hasOperator()) {
 
 136                 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
 
 144      * Check if the combination of parameters is sensible.
 
 146      * @return bool True, if the search looks valid.
 
 148     public function isValidSearch()
 
 150         if (!sizeof($this->aName)) {
 
 151             if ($this->sHouseNumber) {
 
 154             if (!$this->sClass && !$this->sCountryCode) {
 
 162     /////////// Search building functions
 
 166      * Derive new searches by adding a full term to the existing search.
 
 168      * @param mixed[] $aSearchTerm  Description of the token.
 
 169      * @param bool    $bHasPartial  True if there are also tokens of partial terms
 
 170      *                              with the same name.
 
 171      * @param string  $sPhraseType  Type of phrase the token is contained in.
 
 172      * @param bool    $bFirstToken  True if the token is at the beginning of the
 
 174      * @param bool    $bFirstPhrase True if the token is in the first phrase of
 
 176      * @param bool    $bLastToken   True if the token is at the end of the query.
 
 178      * @return SearchDescription[] List of derived search descriptions.
 
 180     public function extendWithFullTerm($aSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
 
 182         $aNewSearches = array();
 
 184         if (($sPhraseType == '' || $sPhraseType == 'country')
 
 185             && !empty($aSearchTerm['country_code'])
 
 186             && $aSearchTerm['country_code'] != '0'
 
 188             if (!$this->sCountryCode) {
 
 189                 $oSearch = clone $this;
 
 190                 $oSearch->iSearchRank++;
 
 191                 $oSearch->sCountryCode = $aSearchTerm['country_code'];
 
 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                   && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == '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                 && $aSearchTerm['word']
 
 207                 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
 
 209                 // If we have structured search or this is the first term,
 
 210                 // make the postcode the primary search element.
 
 211                 if ($this->iOperator == Operator::NONE
 
 212                     && ($sPhraseType == 'postalcode' || $bFirstToken)
 
 214                     $oSearch = clone $this;
 
 215                     $oSearch->iSearchRank++;
 
 216                     $oSearch->iOperator = Operator::POSTCODE;
 
 217                     $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
 
 219                         array($aSearchTerm['word_id'] => $aSearchTerm['word']);
 
 220                     $aNewSearches[] = $oSearch;
 
 223                 // If we have a structured search or this is not the first term,
 
 224                 // add the postcode as an addendum.
 
 225                 if ($this->iOperator != Operator::POSTCODE
 
 226                     && ($sPhraseType == 'postalcode' || sizeof($this->aName))
 
 228                     $oSearch = clone $this;
 
 229                     $oSearch->iSearchRank++;
 
 230                     $oSearch->sPostcode = $aSearchTerm['word'];
 
 231                     $aNewSearches[] = $oSearch;
 
 234         } elseif (($sPhraseType == '' || $sPhraseType == 'street')
 
 235                  && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
 
 237             if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
 
 238                 $oSearch = clone $this;
 
 239                 $oSearch->iSearchRank++;
 
 240                 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
 
 241                 // sanity check: if the housenumber is not mainly made
 
 242                 // up of numbers, add a penalty
 
 243                 if (preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
 
 244                     $oSearch->iSearchRank++;
 
 246                 if (!isset($aSearchTerm['word_id'])) {
 
 247                     $oSearch->iSearchRank++;
 
 249                 // also must not appear in the middle of the address
 
 250                 if (sizeof($this->aAddress)
 
 251                     || sizeof($this->aAddressNonSearch)
 
 254                     $oSearch->iSearchRank++;
 
 256                 $aNewSearches[] = $oSearch;
 
 258         } elseif ($sPhraseType == '' && $aSearchTerm['class']) {
 
 259             if ($this->iOperator == Operator::NONE) {
 
 260                 $oSearch = clone $this;
 
 261                 $oSearch->iSearchRank++;
 
 263                 $iOp = Operator::NEAR; // near == in for the moment
 
 264                 if ($aSearchTerm['operator'] == '') {
 
 265                     if (sizeof($this->aName) || $this->oContext->isBoundedSearch()) {
 
 266                         $iOp = Operator::NAME;
 
 268                     $oSearch->iSearchRank += 2;
 
 271                 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
 
 272                 $aNewSearches[] = $oSearch;
 
 274         } elseif (isset($aSearchTerm['word_id'])
 
 275                   && $aSearchTerm['word_id']
 
 276                   && $sPhraseType != 'country'
 
 278             $iWordID = $aSearchTerm['word_id'];
 
 279             // Full words can only be a name if they appear at the beginning
 
 280             // of the phrase. In structured search the name must forcably in
 
 281             // the first phrase. In unstructured search it may be in a later
 
 282             // phrase when the first phrase is a house number.
 
 283             if (sizeof($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
 
 284                 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
 
 285                     $oSearch = clone $this;
 
 286                     $oSearch->iSearchRank++;
 
 287                     $oSearch->aAddress[$iWordID] = $iWordID;
 
 288                     $aNewSearches[] = $oSearch;
 
 290                     $this->aFullNameAddress[$iWordID] = $iWordID;
 
 293                 $oSearch = clone $this;
 
 294                 $oSearch->iSearchRank++;
 
 295                 $oSearch->aName = array($iWordID => $iWordID);
 
 296                 $aNewSearches[] = $oSearch;
 
 300         return $aNewSearches;
 
 304      * Derive new searches by adding a partial term to the existing search.
 
 306      * @param mixed[] $aSearchTerm        Description of the token.
 
 307      * @param bool    $bStructuredPhrases True if the search is structured.
 
 308      * @param integer $iPhrase            Number of the phrase the token is in.
 
 309      * @param array[] $aFullTokens        List of full term tokens with the
 
 312      * @return SearchDescription[] List of derived search descriptions.
 
 314     public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
 
 316         // Only allow name terms.
 
 317         if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
 
 321         $aNewSearches = array();
 
 322         $iWordID = $aSearchTerm['word_id'];
 
 324         if ((!$bStructuredPhrases || $iPhrase > 0)
 
 325             && sizeof($this->aName)
 
 326             && strpos($aSearchTerm['word_token'], ' ') === false
 
 328             if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
 
 329                 $oSearch = clone $this;
 
 330                 $oSearch->iSearchRank += 2;
 
 331                 $oSearch->aAddress[$iWordID] = $iWordID;
 
 332                 $aNewSearches[] = $oSearch;
 
 334                 $oSearch = clone $this;
 
 335                 $oSearch->iSearchRank++;
 
 336                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
 
 337                 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
 
 338                     $oSearch->iSearchRank += 2;
 
 340                 if (sizeof($aFullTokens)) {
 
 341                     $oSearch->iSearchRank++;
 
 343                 $aNewSearches[] = $oSearch;
 
 345                 // revert to the token version?
 
 346                 foreach ($aFullTokens as $aSearchTermToken) {
 
 347                     if (empty($aSearchTermToken['country_code'])
 
 348                         && empty($aSearchTermToken['lat'])
 
 349                         && empty($aSearchTermToken['class'])
 
 351                         $oSearch = clone $this;
 
 352                         $oSearch->iSearchRank++;
 
 353                         $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
 
 354                         $aNewSearches[] = $oSearch;
 
 360         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
 
 361             && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
 
 363             $oSearch = clone $this;
 
 364             $oSearch->iSearchRank += 2;
 
 365             if (!sizeof($this->aName)) {
 
 366                 $oSearch->iSearchRank += 1;
 
 368             if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
 
 369                 $oSearch->iSearchRank += 2;
 
 371             if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
 
 372                 $oSearch->aName[$iWordID] = $iWordID;
 
 374                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
 
 376             $oSearch->iNamePhrase = $iPhrase;
 
 377             $aNewSearches[] = $oSearch;
 
 380         return $aNewSearches;
 
 383     /////////// Query functions
 
 387      * Query database for places that match this search.
 
 389      * @param object  $oDB                  Database connection to use.
 
 390      * @param mixed[] $aWordFrequencyScores Number of times tokens appears
 
 391      *                                      overall in a planet database.
 
 392      * @param integer $iMinRank             Minimum address rank to restrict
 
 394      * @param integer $iMaxRank             Maximum address rank to restrict
 
 396      * @param integer $iLimit               Maximum number of results.
 
 398      * @return mixed[] An array with two fields: IDs contains the list of
 
 399      *                 matching place IDs and houseNumber the houseNumber
 
 400      *                 if appicable or -1 if not.
 
 402     public function query(&$oDB, &$aWordFrequencyScores, $iMinRank, $iMaxRank, $iLimit)
 
 407         if ($this->sCountryCode
 
 408             && !sizeof($this->aName)
 
 411             && !$this->oContext->hasNearPoint()
 
 413             // Just looking for a country - look it up
 
 414             if (4 >= $iMinRank && 4 <= $iMaxRank) {
 
 415                 $aResults = $this->queryCountry($oDB);
 
 417         } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
 
 418             // Neither name nor address? Then we must be
 
 419             // looking for a POI in a geographic area.
 
 420             if ($this->oContext->isBoundedSearch()) {
 
 421                 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
 
 423         } elseif ($this->iOperator == Operator::POSTCODE) {
 
 424             // looking for postcode
 
 425             $aResults = $this->queryPostcode($oDB, $iLimit);
 
 428             // First search for places according to name and address.
 
 429             $aResults = $this->queryNamedPlace(
 
 431                 $aWordFrequencyScores,
 
 437             //now search for housenumber, if housenumber provided
 
 438             if ($this->sHouseNumber && sizeof($aResults)) {
 
 439                 $aNamedPlaceIDs = $aResults;
 
 440                 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs, $iLimit);
 
 442                 if (!sizeof($aResults) && $this->looksLikeFullAddress()) {
 
 443                     $aResults = $aNamedPlaceIDs;
 
 447             // finally get POIs if requested
 
 448             if ($this->sClass && sizeof($aResults)) {
 
 449                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
 
 454             echo '<br><b>Place IDs:</b> ';
 
 455             var_dump(array_keys($aResults));
 
 458         if (sizeof($aResults) && $this->sPostcode) {
 
 459             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
 
 461                 $sSQL = 'SELECT place_id FROM placex';
 
 462                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
 
 463                 $sSQL .= " AND postcode = '".$this->sPostcode."'";
 
 464                 if (CONST_Debug) var_dump($sSQL);
 
 465                 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
 
 466                 if ($aFilteredPlaceIDs) {
 
 467                     $aNewResults = array();
 
 468                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
 
 469                         $aNewResults[$iPlaceId] = $aResults[$iPlaceId];
 
 471                     $aResults = $aNewResults;
 
 473                         echo '<br><b>Place IDs after postcode filtering:</b> ';
 
 474                         var_dump(array_keys($aResults));
 
 484     private function queryCountry(&$oDB)
 
 486         $sSQL = 'SELECT place_id FROM placex ';
 
 487         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
 
 488         $sSQL .= ' AND rank_search = 4';
 
 489         if ($this->oContext->bViewboxBounded) {
 
 490             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
 
 492         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
 
 494         if (CONST_Debug) var_dump($sSQL);
 
 497         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 498             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 504     private function queryNearbyPoi(&$oDB, $iLimit)
 
 506         if (!$this->sClass) {
 
 510         $aDBResults = array();
 
 511         $sPoiTable = $this->poiTable();
 
 513         $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
 
 514         if (chksql($oDB->getOne($sSQL))) {
 
 515             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
 
 516             if ($this->oContext->sqlCountryList) {
 
 517                 $sSQL .= ' JOIN placex USING (place_id)';
 
 519             if ($this->oContext->hasNearPoint()) {
 
 520                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
 
 521             } elseif ($this->oContext->bViewboxBounded) {
 
 522                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
 
 524             if ($this->oContext->sqlCountryList) {
 
 525                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 527             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 528             if ($this->oContext->sqlViewboxCentre) {
 
 529                 $sSQL .= ' ORDER BY ST_Distance(';
 
 530                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
 
 531             } elseif ($this->oContext->hasNearPoint()) {
 
 532                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
 
 534             $sSQL .= " limit $iLimit";
 
 535             if (CONST_Debug) var_dump($sSQL);
 
 536             $aDBResults = chksql($oDB->getCol($sSQL));
 
 539         if ($this->oContext->hasNearPoint()) {
 
 540             $sSQL = 'SELECT place_id FROM placex WHERE ';
 
 541             $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
 
 542             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
 
 543             $sSQL .= ' AND linked_place_id is null';
 
 544             if ($this->oContext->sqlCountryList) {
 
 545                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 547             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
 
 548             $sSQL .= " LIMIT $iLimit";
 
 549             if (CONST_Debug) var_dump($sSQL);
 
 550             $aDBResults = chksql($oDB->getCol($sSQL));
 
 554         foreach ($aDBResults as $iPlaceId) {
 
 555             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 561     private function queryPostcode(&$oDB, $iLimit)
 
 563         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
 
 565         if (sizeof($this->aAddress)) {
 
 566             $sSQL .= ', search_name s ';
 
 567             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
 
 568             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
 
 569             $sSQL .= '      @> '.getArraySQL($this->aAddress).' AND ';
 
 574         $sSQL .= "p.postcode = '".reset($this->aName)."'";
 
 575         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
 
 576         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
 
 577         $sSQL .= " LIMIT $iLimit";
 
 579         if (CONST_Debug) var_dump($sSQL);
 
 582         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 583             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
 
 589     private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
 
 594         if ($this->sHouseNumber && sizeof($this->aAddress)) {
 
 595             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 597             $aOrder[0] .= 'EXISTS(';
 
 598             $aOrder[0] .= '  SELECT place_id';
 
 599             $aOrder[0] .= '  FROM placex';
 
 600             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 601             $aOrder[0] .= "    AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
 602             $aOrder[0] .= '  LIMIT 1';
 
 604             // also housenumbers from interpolation lines table are needed
 
 605             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
 
 606                 $iHouseNumber = intval($this->sHouseNumber);
 
 607                 $aOrder[0] .= 'OR EXISTS(';
 
 608                 $aOrder[0] .= '  SELECT place_id ';
 
 609                 $aOrder[0] .= '  FROM location_property_osmline ';
 
 610                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 611                 $aOrder[0] .= '    AND startnumber is not NULL';
 
 612                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
 
 613                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
 
 614                 $aOrder[0] .= '  LIMIT 1';
 
 617             $aOrder[0] .= ') DESC';
 
 620         if (sizeof($this->aName)) {
 
 621             $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
 
 623         if (sizeof($this->aAddress)) {
 
 624             // For infrequent name terms disable index usage for address
 
 625             if (CONST_Search_NameOnlySearchFrequencyThreshold
 
 626                 && sizeof($this->aName) == 1
 
 627                 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
 
 628                      < CONST_Search_NameOnlySearchFrequencyThreshold
 
 630                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
 
 632                 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
 
 636         $sCountryTerm = $this->countryCodeSQL('country_code');
 
 638             $aTerms[] = $sCountryTerm;
 
 641         if ($this->sHouseNumber) {
 
 642             $aTerms[] = 'address_rank between 16 and 27';
 
 643         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
 
 644             if ($iMinAddressRank > 0) {
 
 645                 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
 
 647             if ($iMaxAddressRank < 30) {
 
 648                 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
 
 652         if ($this->oContext->hasNearPoint()) {
 
 653             $aTerms[] = $this->oContext->withinSQL('centroid');
 
 654             $aOrder[] = $this->oContext->distanceSQL('centroid');
 
 655         } elseif ($this->sPostcode) {
 
 656             if (!sizeof($this->aAddress)) {
 
 657                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
 
 659                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
 
 663         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
 
 665             $aTerms[] = $sExcludeSQL;
 
 668         if ($this->oContext->bViewboxBounded) {
 
 669             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
 
 672         if ($this->oContext->hasNearPoint()) {
 
 673             $aOrder[] = $this->oContext->distanceSQL('centroid');
 
 676         if ($this->sHouseNumber) {
 
 677             $sImportanceSQL = '- abs(26 - address_rank) + 3';
 
 679             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
 
 681         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
 
 682         $aOrder[] = "$sImportanceSQL DESC";
 
 684         if (sizeof($this->aFullNameAddress)) {
 
 685             $sExactMatchSQL = ' ( ';
 
 686             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
 
 687             $sExactMatchSQL .= '  SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
 
 688             $sExactMatchSQL .= '    INTERSECT ';
 
 689             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
 
 690             $sExactMatchSQL .= ' ) s';
 
 691             $sExactMatchSQL .= ') as exactmatch';
 
 692             $aOrder[] = 'exactmatch DESC';
 
 694             $sExactMatchSQL = '0::int as exactmatch';
 
 697         if ($this->sHouseNumber || $this->sClass) {
 
 703         if (sizeof($aTerms)) {
 
 704             $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
 
 705             $sSQL .= ' FROM search_name';
 
 706             $sSQL .= ' WHERE '.join(' and ', $aTerms);
 
 707             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
 
 708             $sSQL .= ' LIMIT '.$iLimit;
 
 710             if (CONST_Debug) var_dump($sSQL);
 
 712             $aDBResults = chksql(
 
 714                 'Could not get places for search terms.'
 
 717             foreach ($aDBResults as $aResult) {
 
 718                 $oResult = new Result($aResult['place_id']);
 
 719                 $oResult->iExactMatches = $aResult['exactmatch'];
 
 720                 $aResults[$aResult['place_id']] = $oResult;
 
 727     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
 
 730         $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
 
 736         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 737         $sSQL = 'SELECT place_id FROM placex ';
 
 738         $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
 
 739         $sSQL .= "  AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
 740         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 741         $sSQL .= " LIMIT $iLimit";
 
 743         if (CONST_Debug) var_dump($sSQL);
 
 745         // XXX should inherit the exactMatches from its parent
 
 746         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 747             $aResults[$iPlaceId] = new Result($iPlaceId);
 
 750         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
 
 751         $iHousenumber = intval($this->sHouseNumber);
 
 752         if ($bIsIntHouseNumber && !sizeof($aResults)) {
 
 753             // if nothing found, search in the interpolation line table
 
 754             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
 
 755             $sSQL .= ' WHERE startnumber is not NULL';
 
 756             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
 
 757             if ($iHousenumber % 2 == 0) {
 
 758                 // If housenumber is even, look for housenumber in streets
 
 759                 // with interpolationtype even or all.
 
 760                 $sSQL .= "interpolationtype='even'";
 
 762                 // Else look for housenumber with interpolationtype odd or all.
 
 763                 $sSQL .= "interpolationtype='odd'";
 
 765             $sSQL .= " or interpolationtype='all') and ";
 
 766             $sSQL .= $iHousenumber.'>=startnumber and ';
 
 767             $sSQL .= $iHousenumber.'<=endnumber';
 
 768             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 769             $sSQL .= " limit $iLimit";
 
 771             if (CONST_Debug) var_dump($sSQL);
 
 773             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 774                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
 
 775                 $oResult->iHouseNumber = $iHousenumber;
 
 776                 $aResults[$iPlaceId] = $oResult;
 
 780         // If nothing found try the aux fallback table
 
 781         if (CONST_Use_Aux_Location_data && !sizeof($aResults)) {
 
 782             $sSQL = 'SELECT place_id FROM location_property_aux';
 
 783             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
 
 784             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
 
 785             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 786             $sSQL .= " limit $iLimit";
 
 788             if (CONST_Debug) var_dump($sSQL);
 
 790             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 791                 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
 
 795         // If nothing found then search in Tiger data (location_property_tiger)
 
 796         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && !sizeof($aResults)) {
 
 797             $sSQL = 'SELECT place_id FROM location_property_tiger';
 
 798             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
 
 799             if ($iHousenumber % 2 == 0) {
 
 800                 $sSQL .= "interpolationtype='even'";
 
 802                 $sSQL .= "interpolationtype='odd'";
 
 804             $sSQL .= " or interpolationtype='all') and ";
 
 805             $sSQL .= $iHousenumber.'>=startnumber and ';
 
 806             $sSQL .= $iHousenumber.'<=endnumber';
 
 807             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 808             $sSQL .= " limit $iLimit";
 
 810             if (CONST_Debug) var_dump($sSQL);
 
 812             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 813                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
 
 814                 $oResult->iHouseNumber = $iHousenumber;
 
 815                 $aResults[$iPlaceId] = $oResult;
 
 823     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
 
 826         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
 
 832         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
 
 833             // If they were searching for a named class (i.e. 'Kings Head pub')
 
 834             // then we might have an extra match
 
 835             $sSQL = 'SELECT place_id FROM placex ';
 
 836             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
 837             $sSQL .= "   AND class='".$this->sClass."' ";
 
 838             $sSQL .= "   AND type='".$this->sType."'";
 
 839             $sSQL .= '   AND linked_place_id is null';
 
 840             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 841             $sSQL .= ' ORDER BY rank_search ASC ';
 
 842             $sSQL .= " LIMIT $iLimit";
 
 844             if (CONST_Debug) var_dump($sSQL);
 
 846             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 847                 $aResults[$iPlaceId] = new Result($iPlaceId);
 
 851         // NEAR and IN are handled the same
 
 852         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
 
 853             $sClassTable = $this->poiTable();
 
 854             $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
 
 855             $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
 
 857             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
 
 858             if (CONST_Debug) var_dump($sSQL);
 
 859             $iMaxRank = (int)chksql($oDB->getOne($sSQL));
 
 861             // For state / country level searches the normal radius search doesn't work very well
 
 863             if ($iMaxRank < 9 && $bCacheTable) {
 
 864                 // Try and get a polygon to search in instead
 
 865                 $sSQL = 'SELECT geometry FROM placex';
 
 866                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
 867                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
 
 868                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
 
 869                 $sSQL .= ' ORDER BY rank_search ASC ';
 
 871                 if (CONST_Debug) var_dump($sSQL);
 
 872                 $sPlaceGeom = chksql($oDB->getOne($sSQL));
 
 879                 $sSQL = 'SELECT place_id FROM placex';
 
 880                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
 
 881                 if (CONST_Debug) var_dump($sSQL);
 
 882                 $aPlaceIDs = chksql($oDB->getCol($sSQL));
 
 883                 $sPlaceIDs = join(',', $aPlaceIDs);
 
 886             if ($sPlaceIDs || $sPlaceGeom) {
 
 889                     // More efficient - can make the range bigger
 
 893                     if ($this->oContext->hasNearPoint()) {
 
 894                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
 
 895                     } elseif ($sPlaceIDs) {
 
 896                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
 
 897                     } elseif ($sPlaceGeom) {
 
 898                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
 
 901                     $sSQL = 'SELECT distinct i.place_id';
 
 903                         $sSQL .= ', i.order_term';
 
 905                     $sSQL .= ' from (SELECT l.place_id';
 
 907                         $sSQL .= ','.$sOrderBySQL.' as order_term';
 
 909                     $sSQL .= ' from '.$sClassTable.' as l';
 
 912                         $sSQL .= ',placex as f WHERE ';
 
 913                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
 
 914                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
 
 915                     } elseif ($sPlaceGeom) {
 
 916                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
 
 919                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
 
 920                     $sSQL .= 'limit 300) i ';
 
 922                         $sSQL .= 'order by order_term asc';
 
 924                     $sSQL .= " limit $iLimit";
 
 926                     if (CONST_Debug) var_dump($sSQL);
 
 928                     foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 929                         $aResults[$iPlaceId] = new Result($iPlaceId);
 
 932                     if ($this->oContext->hasNearPoint()) {
 
 933                         $fRange = $this->oContext->nearRadius();
 
 937                     if ($this->oContext->hasNearPoint()) {
 
 938                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
 
 940                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
 
 943                     $sSQL = 'SELECT distinct l.place_id';
 
 945                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
 
 947                     $sSQL .= ' FROM placex as l, placex as f';
 
 948                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
 
 949                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
 
 950                     $sSQL .= "  AND l.class='".$this->sClass."'";
 
 951                     $sSQL .= "  AND l.type='".$this->sType."'";
 
 952                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
 
 954                         $sSQL .= 'ORDER BY orderterm ASC';
 
 956                     $sSQL .= " limit $iLimit";
 
 958                     if (CONST_Debug) var_dump($sSQL);
 
 960                     foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
 
 961                         $aResults[$iPlaceId] = new Result($iPlaceId);
 
 970     private function poiTable()
 
 972         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
 
 975     private function countryCodeSQL($sVar)
 
 977         if ($this->sCountryCode) {
 
 978             return $sVar.' = \''.$this->sCountryCode."'";
 
 980         if ($this->oContext->sqlCountryList) {
 
 981             return $sVar.' in '.$this->oContext->sqlCountryList;
 
 987     /////////// Sort functions
 
 990     public static function bySearchRank($a, $b)
 
 992         if ($a->iSearchRank == $b->iSearchRank) {
 
 993             return $a->iOperator + strlen($a->sHouseNumber)
 
 994                      - $b->iOperator - strlen($b->sHouseNumber);
 
 997         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
 
1000     //////////// Debugging functions
 
1003     public function dumpAsHtmlTableRow(&$aWordIDs)
 
1005         $kf = function ($k) use (&$aWordIDs) {
 
1006             return $aWordIDs[$k];
 
1010         echo "<td>$this->iSearchRank</td>";
 
1011         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
 
1012         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
 
1013         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
 
1014         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
 
1015         echo '<td>'.$this->sCountryCode.'</td>';
 
1016         echo '<td>'.Operator::toString($this->iOperator).'</td>';
 
1017         echo '<td>'.$this->sClass.'</td>';
 
1018         echo '<td>'.$this->sType.'</td>';
 
1019         echo '<td>'.$this->sPostcode.'</td>';
 
1020         echo '<td>'.$this->sHouseNumber.'</td>';