5 require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
 
   6 require_once(CONST_BasePath.'/lib/SearchContext.php');
 
   9  * Description of a single interpretation of a search query.
 
  11 class SearchDescription
 
  13     /// Ranking how well the description fits the query.
 
  14     private $iSearchRank = 0;
 
  15     /// Country code of country the result must belong to.
 
  16     private $sCountryCode = '';
 
  17     /// List of word ids making up the name of the object.
 
  18     private $aName = array();
 
  19     /// List of word ids making up the address of the object.
 
  20     private $aAddress = array();
 
  21     /// Subset of word ids of full words making up the address.
 
  22     private $aFullNameAddress = array();
 
  23     /// List of word ids that appear in the name but should be ignored.
 
  24     private $aNameNonSearch = array();
 
  25     /// List of word ids that appear in the address but should be ignored.
 
  26     private $aAddressNonSearch = array();
 
  27     /// Kind of search for special searches, see Nominatim::Operator.
 
  28     private $iOperator = Operator::NONE;
 
  29     /// Class of special feature to search for.
 
  31     /// Type of special feature to search for.
 
  33     /// Housenumber of the object.
 
  34     private $sHouseNumber = '';
 
  35     /// Postcode for the object.
 
  36     private $sPostcode = '';
 
  37     /// Global search constraints.
 
  40     // Temporary values used while creating the search description.
 
  42     /// Index of phrase currently processed.
 
  43     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 likelyhood 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      * Increase the search rank.
 
  73      * @param integer $iAddRank Number of ranks to increase.
 
  77     public function addToRank($iAddRank)
 
  79         $this->iSearchRank += $iAddRank;
 
  80         return $this->iSearchRank;
 
  84      * Make this search a POI search.
 
  86      * In a POI search, objects are not (only) searched by their name
 
  87      * but also by the primary OSM key/value pair (class and type in Nominatim).
 
  89      * @param integer $iOperator Type of POI search
 
  90      * @param string  $sClass    Class (or OSM tag key) of POI.
 
  91      * @param string  $sType     Type (or OSM tag value) of POI.
 
  95     public function setPoiSearch($iOperator, $sClass, $sType)
 
  97         $this->iOperator = $iOperator;
 
  98         $this->sClass = $sClass;
 
  99         $this->sType = $sType;
 
 103      * Check if this might be a full address search.
 
 105      * @return bool True if the search contains name, address and housenumber.
 
 107     public function looksLikeFullAddress()
 
 109         return sizeof($this->aName)
 
 110                && (sizeof($this->aAddress || $this->sCountryCode))
 
 111                && preg_match('/[0-9]+/', $this->sHouseNumber);
 
 115      * Check if any operator is set.
 
 117      * @return bool True, if this is a special search operation.
 
 119     public function hasOperator()
 
 121         return $this->iOperator != Operator::NONE;
 
 125      * Extract key/value pairs from a query.
 
 127      * Key/value pairs are recognised if they are of the form [<key>=<value>].
 
 128      * If multiple terms of this kind are found then all terms are removed
 
 129      * but only the first is used for search.
 
 131      * @param string $sQuery Original query string.
 
 133      * @return string The query string with the special search patterns removed.
 
 135     public function extractKeyValuePairs($sQuery)
 
 137         // Search for terms of kind [<key>=<value>].
 
 139             '/\\[([\\w_]*)=([\\w_]*)\\]/',
 
 145         foreach ($aSpecialTermsRaw as $aTerm) {
 
 146             $sQuery = str_replace($aTerm[0], ' ', $sQuery);
 
 147             if (!$this->hasOperator()) {
 
 148                 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
 
 156      * Check if the combination of parameters is sensible.
 
 158      * @param string[] $aCountryCodes List of country codes.
 
 160      * @return bool True, if the search looks valid.
 
 162     public function isValidSearch(&$aCountryCodes)
 
 164         if (!sizeof($this->aName)) {
 
 165             if ($this->sHouseNumber) {
 
 170             && $this->sCountryCode
 
 171             && !in_array($this->sCountryCode, $aCountryCodes)
 
 179     /////////// Search building functions
 
 183      * Derive new searches by adding a full term to the existing search.
 
 185      * @param mixed[] $aSearchTerm  Description of the token.
 
 186      * @param bool    $bWordInQuery True, if the normalised version of the word
 
 187      *                              is contained in the query.
 
 188      * @param bool    $bHasPartial  True if there are also tokens of partial terms
 
 189      *                              with the same name.
 
 190      * @param string  $sPhraseType  Type of phrase the token is contained in.
 
 191      * @param bool    $bFirstToken  True if the token is at the beginning of the
 
 193      * @param bool    $bFirstPhrase True if the token is in the first phrase of
 
 195      * @param bool    $bLastToken   True if the token is at the end of the query.
 
 196      * @param integer $iGlobalRank  Changable ranking of all searches in the
 
 199      * @return SearchDescription[] List of derived search descriptions.
 
 201     public function extendWithFullTerm($aSearchTerm, $bWordInQuery, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken, &$iGlobalRank)
 
 203         $aNewSearches = array();
 
 205         if (($sPhraseType == '' || $sPhraseType == 'country')
 
 206             && !empty($aSearchTerm['country_code'])
 
 207             && $aSearchTerm['country_code'] != '0'
 
 209             if (!$this->sCountryCode) {
 
 210                 $oSearch = clone $this;
 
 211                 $oSearch->iSearchRank++;
 
 212                 $oSearch->sCountryCode = $aSearchTerm['country_code'];
 
 213                 // Country is almost always at the end of the string
 
 214                 // - increase score for finding it anywhere else (optimisation)
 
 216                     $oSearch->iSearchRank += 5;
 
 218                 $aNewSearches[] = $oSearch;
 
 220                 // If it is at the beginning, we can be almost sure that
 
 221                 // the terms are in the wrong order. Increase score for all searches.
 
 226         } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
 
 227                   && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
 
 229             // We need to try the case where the postal code is the primary element
 
 230             // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
 
 232             if (!$this->sPostcode && $bWordInQuery
 
 233                 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
 
 235                 // If we have structured search or this is the first term,
 
 236                 // make the postcode the primary search element.
 
 237                 if ($this->iOperator == Operator::NONE
 
 238                     && ($sPhraseType == 'postalcode' || $bFirstToken)
 
 240                     $oSearch = clone $this;
 
 241                     $oSearch->iSearchRank++;
 
 242                     $oSearch->iOperator = Operator::POSTCODE;
 
 243                     $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
 
 245                         array($aSearchTerm['word_id'] => $aSearchTerm['word']);
 
 246                     $aNewSearches[] = $oSearch;
 
 249                 // If we have a structured search or this is not the first term,
 
 250                 // add the postcode as an addendum.
 
 251                 if ($this->iOperator != Operator::POSTCODE
 
 252                     && ($sPhraseType == 'postalcode' || sizeof($this->aName))
 
 254                     $oSearch = clone $this;
 
 255                     $oSearch->iSearchRank++;
 
 256                     $oSearch->sPostcode = $aSearchTerm['word'];
 
 257                     $aNewSearches[] = $oSearch;
 
 260         } elseif (($sPhraseType == '' || $sPhraseType == 'street')
 
 261                  && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
 
 263             if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
 
 264                 $oSearch = clone $this;
 
 265                 $oSearch->iSearchRank++;
 
 266                 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
 
 267                 // sanity check: if the housenumber is not mainly made
 
 268                 // up of numbers, add a penalty
 
 269                 if (preg_match_all("/[^0-9]/", $oSearch->sHouseNumber, $aMatches) > 2) {
 
 270                     $oSearch->iSearchRank++;
 
 272                 if (!isset($aSearchTerm['word_id'])) {
 
 273                     $oSearch->iSearchRank++;
 
 275                 // also must not appear in the middle of the address
 
 276                 if (sizeof($this->aAddress) || sizeof($this->aAddressNonSearch)) {
 
 277                     $oSearch->iSearchRank++;
 
 279                 $aNewSearches[] = $oSearch;
 
 281         } elseif ($sPhraseType == ''
 
 282                   && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null
 
 284             // require a normalized exact match of the term
 
 285             // if we have the normalizer version of the query
 
 287             if ($this->iOperator == Operator::NONE
 
 288                 && (isset($aSearchTerm['word']) && $aSearchTerm['word'])
 
 291                 $oSearch = clone $this;
 
 292                 $oSearch->iSearchRank++;
 
 294                 $iOp = Operator::NEAR; // near == in for the moment
 
 295                 if ($aSearchTerm['operator'] == '') {
 
 296                     if (sizeof($this->aName)) {
 
 297                         $iOp = Operator::NAME;
 
 299                     $oSearch->iSearchRank += 2;
 
 302                 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
 
 303                 $aNewSearches[] = $oSearch;
 
 305         } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
 
 306             $iWordID = $aSearchTerm['word_id'];
 
 307             if (sizeof($this->aName)) {
 
 308                 if (($sPhraseType == '' || !$bFirstPhrase)
 
 309                     && $sPhraseType != 'country'
 
 312                     $oSearch = clone $this;
 
 313                     $oSearch->iSearchRank++;
 
 314                     $oSearch->aAddress[$iWordID] = $iWordID;
 
 315                     $aNewSearches[] = $oSearch;
 
 317                     $this->aFullNameAddress[$iWordID] = $iWordID;
 
 320                 $oSearch = clone $this;
 
 321                 $oSearch->iSearchRank++;
 
 322                 $oSearch->aName = array($iWordID => $iWordID);
 
 323                 $aNewSearches[] = $oSearch;
 
 327         return $aNewSearches;
 
 331      * Derive new searches by adding a partial term to the existing search.
 
 333      * @param mixed[] $aSearchTerm          Description of the token.
 
 334      * @param bool    $bStructuredPhrases   True if the search is structured.
 
 335      * @param integer $iPhrase              Number of the phrase the token is in.
 
 336      * @param mixed[] $aWordFrequencyScores Number of times tokens appears
 
 337      *                                      overall in a planet database.
 
 338      * @param array[] $aFullTokens          List of full term tokens with the
 
 341      * @return SearchDescription[] List of derived search descriptions.
 
 343     public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, &$aWordFrequencyScores, $aFullTokens)
 
 345         // Only allow name terms.
 
 346         if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
 
 350         $aNewSearches = array();
 
 351         $iWordID = $aSearchTerm['word_id'];
 
 353         if ((!$bStructuredPhrases || $iPhrase > 0)
 
 354             && sizeof($this->aName)
 
 355             && strpos($aSearchTerm['word_token'], ' ') === false
 
 357             if ($aWordFrequencyScores[$iWordID] < CONST_Max_Word_Frequency) {
 
 358                 $oSearch = clone $this;
 
 359                 $oSearch->iSearchRank++;
 
 360                 $oSearch->aAddress[$iWordID] = $iWordID;
 
 361                 $aNewSearches[] = $oSearch;
 
 363                 $oSearch = clone $this;
 
 364                 $oSearch->iSearchRank++;
 
 365                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
 
 366                 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
 
 367                     $oSearch->iSearchRank += 2;
 
 369                 if (sizeof($aFullTokens)) {
 
 370                     $oSearch->iSearchRank++;
 
 372                 $aNewSearches[] = $oSearch;
 
 374                 // revert to the token version?
 
 375                 foreach ($aFullTokens as $aSearchTermToken) {
 
 376                     if (empty($aSearchTermToken['country_code'])
 
 377                         && empty($aSearchTermToken['lat'])
 
 378                         && empty($aSearchTermToken['class'])
 
 380                         $oSearch = clone $this;
 
 381                         $oSearch->iSearchRank++;
 
 382                         $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
 
 383                         $aNewSearches[] = $oSearch;
 
 389         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
 
 390             && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
 
 392             $oSearch = clone $this;
 
 393             $oSearch->iSearchRank++;
 
 394             if (!sizeof($this->aName)) {
 
 395                 $oSearch->iSearchRank += 1;
 
 397             if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
 
 398                 $oSearch->iSearchRank += 2;
 
 400             if ($aWordFrequencyScores[$iWordID] < CONST_Max_Word_Frequency) {
 
 401                 $oSearch->aName[$iWordID] = $iWordID;
 
 403                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
 
 405             $oSearch->iNamePhrase = $iPhrase;
 
 406             $aNewSearches[] = $oSearch;
 
 409         return $aNewSearches;
 
 412     /////////// Query functions
 
 416      * Query database for places that match this search.
 
 418      * @param object  $oDB                  Database connection to use.
 
 419      * @param mixed[] $aWordFrequencyScores Number of times tokens appears
 
 420      *                                      overall in a planet database.
 
 421      * @param mixed[] $aExactMatchCache     Saves number of exact matches.
 
 422      * @param integer $iMinRank             Minimum address rank to restrict
 
 424      * @param integer $iMaxRank             Maximum address rank to restrict
 
 426      * @param integer $iLimit               Maximum number of results.
 
 428      * @return mixed[] An array with two fields: IDs contains the list of
 
 429      *                 matching place IDs and houseNumber the houseNumber
 
 430      *                 if appicable or -1 if not.
 
 432     public function query(&$oDB, &$aWordFrequencyScores, &$aExactMatchCache, $iMinRank, $iMaxRank, $iLimit)
 
 434         $aPlaceIDs = array();
 
 437         if ($this->sCountryCode
 
 438             && !sizeof($this->aName)
 
 441             && !$this->oContext->hasNearPoint()
 
 443             // Just looking for a country - look it up
 
 444             if (4 >= $iMinRank && 4 <= $iMaxRank) {
 
 445                 $aPlaceIDs = $this->queryCountry($oDB);
 
 447         } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
 
 448             // Neither name nor address? Then we must be
 
 449             // looking for a POI in a geographic area.
 
 450             if ($this->oContext->isBoundedSearch()) {
 
 451                 $aPlaceIDs = $this->queryNearbyPoi($oDB, $iLimit);
 
 453         } elseif ($this->iOperator == Operator::POSTCODE) {
 
 454             // looking for postcode
 
 455             $aPlaceIDs = $this->queryPostcode($oDB, $iLimit);
 
 458             // First search for places according to name and address.
 
 459             $aNamedPlaceIDs = $this->queryNamedPlace(
 
 461                 $aWordFrequencyScores,
 
 467             if (sizeof($aNamedPlaceIDs)) {
 
 468                 foreach ($aNamedPlaceIDs as $aRow) {
 
 469                     $aPlaceIDs[] = $aRow['place_id'];
 
 470                     $aExactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
 
 474             //now search for housenumber, if housenumber provided
 
 475             if ($this->sHouseNumber && sizeof($aPlaceIDs)) {
 
 476                 $aResult = $this->queryHouseNumber($oDB, $aPlaceIDs, $iLimit);
 
 478                 if (sizeof($aResult)) {
 
 479                     $iHousenumber = $aResult['iHouseNumber'];
 
 480                     $aPlaceIDs = $aResult['aPlaceIDs'];
 
 481                 } elseif (!$this->looksLikeFullAddress()) {
 
 482                     $aPlaceIDs = array();
 
 486             // finally get POIs if requested
 
 487             if ($this->sClass && sizeof($aPlaceIDs)) {
 
 488                 $aPlaceIDs = $this->queryPoiByOperator($oDB, $aPlaceIDs, $iLimit);
 
 493             echo "<br><b>Place IDs:</b> ";
 
 494             var_Dump($aPlaceIDs);
 
 497         if (sizeof($aPlaceIDs) && $this->sPostcode) {
 
 498             $sSQL = 'SELECT place_id FROM placex';
 
 499             $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
 
 500             $sSQL .= " AND postcode = '".$this->sPostcode."'";
 
 501             if (CONST_Debug) var_dump($sSQL);
 
 502             $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
 
 503             if ($aFilteredPlaceIDs) {
 
 504                 $aPlaceIDs = $aFilteredPlaceIDs;
 
 506                     echo "<br><b>Place IDs after postcode filtering:</b> ";
 
 507                     var_Dump($aPlaceIDs);
 
 512         return array('IDs' => $aPlaceIDs, 'houseNumber' => $iHousenumber);
 
 516     private function queryCountry(&$oDB)
 
 518         $sSQL = 'SELECT place_id FROM placex ';
 
 519         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
 
 520         $sSQL .= ' AND rank_search = 4';
 
 521         if ($this->oContext->bViewboxBounded) {
 
 522             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
 
 524         $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
 
 526         if (CONST_Debug) var_dump($sSQL);
 
 528         return chksql($oDB->getCol($sSQL));
 
 531     private function queryNearbyPoi(&$oDB, $iLimit)
 
 533         if (!$this->sClass) {
 
 537         $sPoiTable = $this->poiTable();
 
 539         $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
 
 540         if (chksql($oDB->getOne($sSQL))) {
 
 541             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
 
 542             if ($this->oContext->sqlCountryList) {
 
 543                 $sSQL .= ' JOIN placex USING (place_id)';
 
 545             if ($this->oContext->hasNearPoint()) {
 
 546                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
 
 547             } elseif ($this->oContext->bViewboxBounded) {
 
 548                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
 
 550             if ($this->oContext->sqlCountryList) {
 
 551                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 553             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 554             if ($this->oContext->sqlViewboxCentre) {
 
 555                 $sSQL .= ' ORDER BY ST_Distance(';
 
 556                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
 
 557             } elseif ($this->oContext->hasNearPoint()) {
 
 558                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
 
 560             $sSQL .= " limit $iLimit";
 
 561             if (CONST_Debug) var_dump($sSQL);
 
 562             return chksql($oDB->getCol($sSQL));
 
 565         if ($this->oContext->hasNearPoint()) {
 
 566             $sSQL = 'SELECT place_id FROM placex WHERE ';
 
 567             $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
 
 568             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
 
 569             $sSQL .= ' AND linked_place_id is null';
 
 570             if ($this->oContext->sqlCountryList) {
 
 571                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
 
 573             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid')." ASC";
 
 574             $sSQL .= " LIMIT $iLimit";
 
 575             if (CONST_Debug) var_dump($sSQL);
 
 576             return chksql($oDB->getCol($sSQL));
 
 582     private function queryPostcode(&$oDB, $iLimit)
 
 584         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
 
 586         if (sizeof($this->aAddress)) {
 
 587             $sSQL .= ', search_name s ';
 
 588             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
 
 589             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
 
 590             $sSQL .= '      @> '.getArraySQL($this->aAddress).' AND ';
 
 595         $sSQL .= "p.postcode = '".reset($this->aName)."'";
 
 596         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
 
 597         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
 
 598         $sSQL .= " LIMIT $iLimit";
 
 600         if (CONST_Debug) var_dump($sSQL);
 
 602         return chksql($oDB->getCol($sSQL));
 
 605     private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
 
 610         if ($this->sHouseNumber && sizeof($this->aAddress)) {
 
 611             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 613             $aOrder[0] .= 'EXISTS(';
 
 614             $aOrder[0] .= '  SELECT place_id';
 
 615             $aOrder[0] .= '  FROM placex';
 
 616             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 617             $aOrder[0] .= "    AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
 618             $aOrder[0] .= '  LIMIT 1';
 
 620             // also housenumbers from interpolation lines table are needed
 
 621             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
 
 622                 $iHouseNumber = intval($this->sHouseNumber);
 
 623                 $aOrder[0] .= 'OR EXISTS(';
 
 624                 $aOrder[0] .= '  SELECT place_id ';
 
 625                 $aOrder[0] .= '  FROM location_property_osmline ';
 
 626                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
 
 627                 $aOrder[0] .= '    AND startnumber is not NULL';
 
 628                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
 
 629                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
 
 630                 $aOrder[0] .= '  LIMIT 1';
 
 633             $aOrder[0] .= ') DESC';
 
 636         if (sizeof($this->aName)) {
 
 637             $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
 
 639         if (sizeof($this->aAddress)) {
 
 640             // For infrequent name terms disable index usage for address
 
 641             if (CONST_Search_NameOnlySearchFrequencyThreshold
 
 642                 && sizeof($this->aName) == 1
 
 643                 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
 
 644                      < CONST_Search_NameOnlySearchFrequencyThreshold
 
 646                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
 
 648                 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
 
 652         $sCountryTerm = $this->countryCodeSQL('country_code');
 
 654             $aTerms[] = $sCountryTerm;
 
 657         if ($this->sHouseNumber) {
 
 658             $aTerms[] = "address_rank between 16 and 27";
 
 659         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
 
 660             if ($iMinAddressRank > 0) {
 
 661                 $aTerms[] = "address_rank >= ".$iMinAddressRank;
 
 663             if ($iMaxAddressRank < 30) {
 
 664                 $aTerms[] = "address_rank <= ".$iMaxAddressRank;
 
 668         if ($this->oContext->hasNearPoint()) {
 
 669             $aTerms[] = $this->oContext->withinSQL('centroid');
 
 670             $aOrder[] = $this->oContext->distanceSQL('centroid');
 
 671         } elseif ($this->sPostcode) {
 
 672             if (!sizeof($this->aAddress)) {
 
 673                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
 
 675                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
 
 679         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
 
 681             $aTerms[] = $sExcludeSQL;
 
 684         if ($this->oContext->bViewboxBounded) {
 
 685             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
 
 688         if ($this->oContext->hasNearPoint()) {
 
 689             $aOrder[] = $this->oContext->distanceSQL('centroid');
 
 692         if ($this->sHouseNumber) {
 
 693             $sImportanceSQL = '- abs(26 - address_rank) + 3';
 
 695             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
 
 697         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
 
 698         $aOrder[] = "$sImportanceSQL DESC";
 
 700         if (sizeof($this->aFullNameAddress)) {
 
 701             $sExactMatchSQL = ' ( ';
 
 702             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
 
 703             $sExactMatchSQL .= '  SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
 
 704             $sExactMatchSQL .= '    INTERSECT ';
 
 705             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
 
 706             $sExactMatchSQL .= ' ) s';
 
 707             $sExactMatchSQL .= ') as exactmatch';
 
 708             $aOrder[] = 'exactmatch DESC';
 
 710             $sExactMatchSQL = '0::int as exactmatch';
 
 713         if ($this->sHouseNumber || $this->sClass) {
 
 717         if (sizeof($aTerms)) {
 
 718             $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
 
 719             $sSQL .= ' FROM search_name';
 
 720             $sSQL .= ' WHERE '.join(' and ', $aTerms);
 
 721             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
 
 722             $sSQL .= ' LIMIT '.$iLimit;
 
 724             if (CONST_Debug) var_dump($sSQL);
 
 728                 "Could not get places for search terms."
 
 735     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
 
 737         $sPlaceIDs = join(',', $aRoadPlaceIDs);
 
 739         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
 
 740         $sSQL = 'SELECT place_id FROM placex ';
 
 741         $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
 
 742         $sSQL .= "  AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
 
 743         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 744         $sSQL .= " LIMIT $iLimit";
 
 746         if (CONST_Debug) var_dump($sSQL);
 
 748         $aPlaceIDs = chksql($oDB->getCol($sSQL));
 
 750         if (sizeof($aPlaceIDs)) {
 
 751             return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
 
 754         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
 
 755         $iHousenumber = intval($this->sHouseNumber);
 
 756         if ($bIsIntHouseNumber) {
 
 757             // if nothing found, search in the interpolation line table
 
 758             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
 
 759             $sSQL .= ' WHERE startnumber is not NULL';
 
 760             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
 
 761             if ($iHousenumber % 2 == 0) {
 
 762                 // If housenumber is even, look for housenumber in streets
 
 763                 // with interpolationtype even or all.
 
 764                 $sSQL .= "interpolationtype='even'";
 
 766                 // Else look for housenumber with interpolationtype odd or all.
 
 767                 $sSQL .= "interpolationtype='odd'";
 
 769             $sSQL .= " or interpolationtype='all') and ";
 
 770             $sSQL .= $iHousenumber.">=startnumber and ";
 
 771             $sSQL .= $iHousenumber."<=endnumber";
 
 772             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 773             $sSQL .= " limit $iLimit";
 
 775             if (CONST_Debug) var_dump($sSQL);
 
 777             $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
 
 779             if (sizeof($aPlaceIDs)) {
 
 780                 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
 
 784         // If nothing found try the aux fallback table
 
 785         if (CONST_Use_Aux_Location_data) {
 
 786             $sSQL = 'SELECT place_id FROM location_property_aux';
 
 787             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
 
 788             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
 
 789             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 790             $sSQL .= " limit $iLimit";
 
 792             if (CONST_Debug) var_dump($sSQL);
 
 794             $aPlaceIDs = chksql($oDB->getCol($sSQL));
 
 796             if (sizeof($aPlaceIDs)) {
 
 797                 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
 
 801         // If nothing found then search in Tiger data (location_property_tiger)
 
 802         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber) {
 
 803             $sSQL = 'SELECT distinct place_id FROM location_property_tiger';
 
 804             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
 
 805             if ($iHousenumber % 2 == 0) {
 
 806                 $sSQL .= "interpolationtype='even'";
 
 808                 $sSQL .= "interpolationtype='odd'";
 
 810             $sSQL .= " or interpolationtype='all') and ";
 
 811             $sSQL .= $iHousenumber.">=startnumber and ";
 
 812             $sSQL .= $iHousenumber."<=endnumber";
 
 813             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 814             $sSQL .= " limit $iLimit";
 
 816             if (CONST_Debug) var_dump($sSQL);
 
 818             $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
 
 820             if (sizeof($aPlaceIDs)) {
 
 821                 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
 
 829     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
 
 831         $sPlaceIDs = join(',', $aParentIDs);
 
 832         $aClassPlaceIDs = array();
 
 834         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
 
 835             // If they were searching for a named class (i.e. 'Kings Head pub')
 
 836             // then we might have an extra match
 
 837             $sSQL = 'SELECT place_id FROM placex ';
 
 838             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
 
 839             $sSQL .= "   AND class='".$this->sClass."' ";
 
 840             $sSQL .= "   AND type='".$this->sType."'";
 
 841             $sSQL .= "   AND linked_place_id is null";
 
 842             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
 
 843             $sSQL .= " ORDER BY rank_search ASC ";
 
 844             $sSQL .= " LIMIT $iLimit";
 
 846             if (CONST_Debug) var_dump($sSQL);
 
 848             $aClassPlaceIDs = chksql($oDB->getCol($sSQL));
 
 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                     $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
 
 930                     if ($this->oContext->hasNearPoint()) {
 
 931                         $fRange = $this->oContext->nearRadius();
 
 935                     if ($this->oContext->hasNearPoint()) {
 
 936                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
 
 938                         $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
 
 941                     $sSQL = 'SELECT distinct l.place_id';
 
 943                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
 
 945                     $sSQL .= ' FROM placex as l, placex as f';
 
 946                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
 
 947                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
 
 948                     $sSQL .= "  AND l.class='".$this->sClass."'";
 
 949                     $sSQL .= "  AND l.type='".$this->sType."'";
 
 950                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
 
 952                         $sSQL .= "ORDER BY orderterm ASC";
 
 954                     $sSQL .= " limit $iLimit";
 
 956                     if (CONST_Debug) var_dump($sSQL);
 
 958                     $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
 
 963         return $aClassPlaceIDs;
 
 966     private function poiTable()
 
 968         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
 
 971     private function countryCodeSQL($sVar)
 
 973         if ($this->sCountryCode) {
 
 974             return $sVar.' = \''.$this->sCountryCode."'";
 
 976         if ($this->oContext->sqlCountryList) {
 
 977             return $sVar.' in '.$this->oContext->sqlCountryList;
 
 983     /////////// Sort functions
 
 986     public static function bySearchRank($a, $b)
 
 988         if ($a->iSearchRank == $b->iSearchRank) {
 
 989             return $a->iOperator + strlen($a->sHouseNumber)
 
 990                      - $b->iOperator - strlen($b->sHouseNumber);
 
 993         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
 
 996     //////////// Debugging functions
 
 999     public function dumpAsHtmlTableRow(&$aWordIDs)
 
1001         $kf = function ($k) use (&$aWordIDs) {
 
1002             return $aWordIDs[$k];
 
1006         echo "<td>$this->iSearchRank</td>";
 
1007         echo "<td>".join(', ', array_map($kf, $this->aName))."</td>";
 
1008         echo "<td>".join(', ', array_map($kf, $this->aNameNonSearch))."</td>";
 
1009         echo "<td>".join(', ', array_map($kf, $this->aAddress))."</td>";
 
1010         echo "<td>".join(', ', array_map($kf, $this->aAddressNonSearch))."</td>";
 
1011         echo "<td>".$this->sCountryCode."</td>";
 
1012         echo "<td>".Operator::toString($this->iOperator)."</td>";
 
1013         echo "<td>".$this->sClass."</td>";
 
1014         echo "<td>".$this->sType."</td>";
 
1015         echo "<td>".$this->sPostcode."</td>";
 
1016         echo "<td>".$this->sHouseNumber."</td>";