]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/SearchDescription.php
Merge pull request #2390 from lonvia/responsible-disclosure
[nominatim.git] / lib-php / SearchDescription.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_LibDir.'/SpecialSearchOperator.php');
6 require_once(CONST_LibDir.'/SearchContext.php');
7 require_once(CONST_LibDir.'/Result.php');
8
9 /**
10  * Description of a single interpretation of a search query.
11  */
12 class SearchDescription
13 {
14     /// Ranking how well the description fits the query.
15     private $iSearchRank = 0;
16     /// Country code of country the result must belong to.
17     private $sCountryCode = '';
18     /// List of word ids making up the name of the object.
19     private $aName = array();
20     /// True if the name is rare enough to force index use on name.
21     private $bRareName = false;
22     /// List of word ids making up the address of the object.
23     private $aAddress = array();
24     /// List of word ids that appear in the name but should be ignored.
25     private $aNameNonSearch = array();
26     /// List of word ids that appear in the address but should be ignored.
27     private $aAddressNonSearch = array();
28     /// Kind of search for special searches, see Nominatim::Operator.
29     private $iOperator = Operator::NONE;
30     /// Class of special feature to search for.
31     private $sClass = '';
32     /// Type of special feature to search for.
33     private $sType = '';
34     /// Housenumber of the object.
35     private $sHouseNumber = '';
36     /// Postcode for the object.
37     private $sPostcode = '';
38     /// Global search constraints.
39     private $oContext;
40
41     // Temporary values used while creating the search description.
42
43     /// Index of phrase currently processed.
44     private $iNamePhrase = -1;
45
46     /**
47      * Create an empty search description.
48      *
49      * @param object $oContext Global context to use. Will be inherited by
50      *                         all derived search objects.
51      */
52     public function __construct($oContext)
53     {
54         $this->oContext = $oContext;
55     }
56
57     /**
58      * Get current search rank.
59      *
60      * The higher the search rank the lower the likelihood that the
61      * search is a correct interpretation of the search query.
62      *
63      * @return integer Search rank.
64      */
65     public function getRank()
66     {
67         return $this->iSearchRank;
68     }
69
70     /**
71      * Make this search a POI search.
72      *
73      * In a POI search, objects are not (only) searched by their name
74      * but also by the primary OSM key/value pair (class and type in Nominatim).
75      *
76      * @param integer $iOperator Type of POI search
77      * @param string  $sClass    Class (or OSM tag key) of POI.
78      * @param string  $sType     Type (or OSM tag value) of POI.
79      *
80      * @return void
81      */
82     public function setPoiSearch($iOperator, $sClass, $sType)
83     {
84         $this->iOperator = $iOperator;
85         $this->sClass = $sClass;
86         $this->sType = $sType;
87     }
88
89     /**
90      * Check if any operator is set.
91      *
92      * @return bool True, if this is a special search operation.
93      */
94     public function hasOperator()
95     {
96         return $this->iOperator != Operator::NONE;
97     }
98
99     /**
100      * Extract key/value pairs from a query.
101      *
102      * Key/value pairs are recognised if they are of the form [<key>=<value>].
103      * If multiple terms of this kind are found then all terms are removed
104      * but only the first is used for search.
105      *
106      * @param string $sQuery Original query string.
107      *
108      * @return string The query string with the special search patterns removed.
109      */
110     public function extractKeyValuePairs($sQuery)
111     {
112         // Search for terms of kind [<key>=<value>].
113         preg_match_all(
114             '/\\[([\\w_]*)=([\\w_]*)\\]/',
115             $sQuery,
116             $aSpecialTermsRaw,
117             PREG_SET_ORDER
118         );
119
120         foreach ($aSpecialTermsRaw as $aTerm) {
121             $sQuery = str_replace($aTerm[0], ' ', $sQuery);
122             if (!$this->hasOperator()) {
123                 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
124             }
125         }
126
127         return $sQuery;
128     }
129
130     /**
131      * Check if the combination of parameters is sensible.
132      *
133      * @return bool True, if the search looks valid.
134      */
135     public function isValidSearch()
136     {
137         if (empty($this->aName)) {
138             if ($this->sHouseNumber) {
139                 return false;
140             }
141             if (!$this->sClass && !$this->sCountryCode) {
142                 return false;
143             }
144         }
145
146         return true;
147     }
148
149     /////////// Search building functions
150
151
152     /**
153      * Derive new searches by adding a full term to the existing search.
154      *
155      * @param object $oSearchTerm  Description of the token.
156      * @param string $sPhraseType  Type of phrase the token is contained in.
157      * @param bool   $bFirstToken  True if the token is at the beginning of the
158      *                             query.
159      * @param bool   $bFirstPhrase True if the token is in the first phrase of
160      *                             the query.
161      * @param bool   $bLastToken   True if the token is at the end of the query.
162      *
163      * @return SearchDescription[] List of derived search descriptions.
164      */
165     public function extendWithFullTerm($oSearchTerm, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
166     {
167         $aNewSearches = array();
168
169         if (($sPhraseType == '' || $sPhraseType == 'country')
170             && is_a($oSearchTerm, '\Nominatim\Token\Country')
171         ) {
172             if (!$this->sCountryCode) {
173                 $oSearch = clone $this;
174                 $oSearch->iSearchRank++;
175                 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
176                 // Country is almost always at the end of the string
177                 // - increase score for finding it anywhere else (optimisation)
178                 if (!$bLastToken) {
179                     $oSearch->iSearchRank += 5;
180                     $oSearch->iNamePhrase = -1;
181                 }
182                 $aNewSearches[] = $oSearch;
183             }
184         } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
185                   && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
186         ) {
187             if (!$this->sPostcode) {
188                 // If we have structured search or this is the first term,
189                 // make the postcode the primary search element.
190                 if ($this->iOperator == Operator::NONE && $bFirstToken) {
191                     $oSearch = clone $this;
192                     $oSearch->iSearchRank++;
193                     $oSearch->iOperator = Operator::POSTCODE;
194                     $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
195                     $oSearch->aName =
196                         array($oSearchTerm->iId => $oSearchTerm->sPostcode);
197                     $aNewSearches[] = $oSearch;
198                 }
199
200                 // If we have a structured search or this is not the first term,
201                 // add the postcode as an addendum.
202                 if ($this->iOperator != Operator::POSTCODE
203                     && ($sPhraseType == 'postalcode' || !empty($this->aName))
204                 ) {
205                     $oSearch = clone $this;
206                     $oSearch->iSearchRank++;
207                     $oSearch->iNamePhrase = -1;
208                     if (strlen($oSearchTerm->sPostcode) < 4) {
209                         $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
210                     }
211                     $oSearch->sPostcode = $oSearchTerm->sPostcode;
212                     $aNewSearches[] = $oSearch;
213                 }
214             }
215         } elseif (($sPhraseType == '' || $sPhraseType == 'street')
216                  && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
217         ) {
218             if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
219                 // sanity check: if the housenumber is not mainly made
220                 // up of numbers, add a penalty
221                 $iSearchCost = 1;
222                 if (preg_match('/\\d/', $oSearchTerm->sToken) === 0
223                     || preg_match_all('/[^0-9]/', $oSearchTerm->sToken, $aMatches) > 2) {
224                     $iSearchCost++;
225                 }
226                 if ($this->iOperator != Operator::NONE) {
227                     $iSearchCost++;
228                 }
229                 if (empty($oSearchTerm->iId)) {
230                     $iSearchCost++;
231                 }
232                 // also must not appear in the middle of the address
233                 if (!empty($this->aAddress)
234                     || (!empty($this->aAddressNonSearch))
235                     || $this->sPostcode
236                 ) {
237                     $iSearchCost++;
238                 }
239
240                 $oSearch = clone $this;
241                 $oSearch->iSearchRank += $iSearchCost;
242                 $oSearch->iNamePhrase = -1;
243                 $oSearch->sHouseNumber = $oSearchTerm->sToken;
244                 $aNewSearches[] = $oSearch;
245
246                 // Housenumbers may appear in the name when the place has its own
247                 // address terms.
248                 if ($oSearchTerm->iId !== null
249                     && ($this->iNamePhrase >= 0 || empty($this->aName))
250                     && empty($this->aAddress)
251                    ) {
252                     $oSearch = clone $this;
253                     $oSearch->iSearchRank += $iSearchCost;
254                     $oSearch->aAddress = $this->aName;
255                     $oSearch->bRareName = false;
256                     $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
257                     $aNewSearches[] = $oSearch;
258                 }
259             }
260         } elseif ($sPhraseType == ''
261                   && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
262         ) {
263             if ($this->iOperator == Operator::NONE) {
264                 $oSearch = clone $this;
265                 $oSearch->iSearchRank += 2;
266                 $oSearch->iNamePhrase = -1;
267
268                 $iOp = $oSearchTerm->iOperator;
269                 if ($iOp == Operator::NONE) {
270                     if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
271                         $iOp = Operator::NAME;
272                     } else {
273                         $iOp = Operator::NEAR;
274                     }
275                     $oSearch->iSearchRank += 2;
276                 } elseif (!$bFirstToken && !$bLastToken) {
277                     $oSearch->iSearchRank += 2;
278                 }
279                 if ($this->sHouseNumber) {
280                     $oSearch->iSearchRank++;
281                 }
282
283                 $oSearch->setPoiSearch(
284                     $iOp,
285                     $oSearchTerm->sClass,
286                     $oSearchTerm->sType
287                 );
288                 $aNewSearches[] = $oSearch;
289             }
290         } elseif ($sPhraseType != 'country'
291                   && is_a($oSearchTerm, '\Nominatim\Token\Word')
292         ) {
293             $iWordID = $oSearchTerm->iId;
294             // Full words can only be a name if they appear at the beginning
295             // of the phrase. In structured search the name must forcably in
296             // the first phrase. In unstructured search it may be in a later
297             // phrase when the first phrase is a house number.
298             if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
299                 if (($sPhraseType == '' || !$bFirstPhrase) && $oSearchTerm->iTermCount > 1) {
300                     $oSearch = clone $this;
301                     $oSearch->iNamePhrase = -1;
302                     $oSearch->iSearchRank += 1;
303                     $oSearch->aAddress[$iWordID] = $iWordID;
304                     $aNewSearches[] = $oSearch;
305                 }
306             } elseif (empty($this->aNameNonSearch)) {
307                 $oSearch = clone $this;
308                 $oSearch->iSearchRank++;
309                 $oSearch->aName = array($iWordID => $iWordID);
310                 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
311                     $oSearch->bRareName =
312                         $oSearchTerm->iSearchNameCount
313                           < CONST_Search_NameOnlySearchFrequencyThreshold;
314                 }
315                 $aNewSearches[] = $oSearch;
316             }
317         }
318
319         return $aNewSearches;
320     }
321
322     /**
323      * Derive new searches by adding a partial term to the existing search.
324      *
325      * @param string  $sToken             Term for the token.
326      * @param object  $oSearchTerm        Description of the token.
327      * @param bool    $bStructuredPhrases True if the search is structured.
328      * @param integer $iPhrase            Number of the phrase the token is in.
329      * @param array[] $aFullTokens        List of full term tokens with the
330      *                                    same name.
331      *
332      * @return SearchDescription[] List of derived search descriptions.
333      */
334     public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
335     {
336         // Only allow name terms.
337         if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))
338             || strpos($sToken, ' ') !== false
339         ) {
340             return array();
341         }
342
343         $aNewSearches = array();
344         $iWordID = $oSearchTerm->iId;
345
346         if ((!$bStructuredPhrases || $iPhrase > 0)
347             && (!empty($this->aName))
348         ) {
349             $oSearch = clone $this;
350             $oSearch->iSearchRank++;
351             if (preg_match('#^[0-9 ]+$#', $sToken)) {
352                 $oSearch->iSearchRank++;
353             }
354             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
355                 $oSearch->aAddress[$iWordID] = $iWordID;
356             } else {
357                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
358                 if (!empty($aFullTokens)) {
359                     $oSearch->iSearchRank++;
360                 }
361             }
362             $aNewSearches[] = $oSearch;
363         }
364
365         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
366             && ((empty($this->aName) && empty($this->aNameNonSearch)) || $this->iNamePhrase == $iPhrase)
367         ) {
368             $oSearch = clone $this;
369             $oSearch->iSearchRank++;
370             if (empty($this->aName) && empty($this->aNameNonSearch)) {
371                 $oSearch->iSearchRank++;
372             }
373             if (preg_match('#^[0-9 ]+$#', $sToken)) {
374                 $oSearch->iSearchRank++;
375             }
376             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
377                 if (empty($this->aName)
378                     && CONST_Search_NameOnlySearchFrequencyThreshold
379                 ) {
380                     $oSearch->bRareName =
381                         $oSearchTerm->iSearchNameCount
382                           < CONST_Search_NameOnlySearchFrequencyThreshold;
383                 } else {
384                     $oSearch->bRareName = false;
385                 }
386                 $oSearch->aName[$iWordID] = $iWordID;
387             } else {
388                 if (!empty($aFullTokens)) {
389                     $oSearch->iSearchRank++;
390                 }
391                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
392             }
393             $oSearch->iNamePhrase = $iPhrase;
394             $aNewSearches[] = $oSearch;
395         }
396
397         return $aNewSearches;
398     }
399
400     /////////// Query functions
401
402
403     /**
404      * Query database for places that match this search.
405      *
406      * @param object  $oDB      Nominatim::DB instance to use.
407      * @param integer $iMinRank Minimum address rank to restrict search to.
408      * @param integer $iMaxRank Maximum address rank to restrict search to.
409      * @param integer $iLimit   Maximum number of results.
410      *
411      * @return mixed[] An array with two fields: IDs contains the list of
412      *                 matching place IDs and houseNumber the houseNumber
413      *                 if appicable or -1 if not.
414      */
415     public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
416     {
417         $aResults = array();
418         $iHousenumber = -1;
419
420         if ($this->sCountryCode
421             && empty($this->aName)
422             && !$this->iOperator
423             && !$this->sClass
424             && !$this->oContext->hasNearPoint()
425         ) {
426             // Just looking for a country - look it up
427             if (4 >= $iMinRank && 4 <= $iMaxRank) {
428                 $aResults = $this->queryCountry($oDB);
429             }
430         } elseif (empty($this->aName) && empty($this->aAddress)) {
431             // Neither name nor address? Then we must be
432             // looking for a POI in a geographic area.
433             if ($this->oContext->isBoundedSearch()) {
434                 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
435             }
436         } elseif ($this->iOperator == Operator::POSTCODE) {
437             // looking for postcode
438             $aResults = $this->queryPostcode($oDB, $iLimit);
439         } else {
440             // Ordinary search:
441             // First search for places according to name and address.
442             $aResults = $this->queryNamedPlace(
443                 $oDB,
444                 $iMinRank,
445                 $iMaxRank,
446                 $iLimit
447             );
448
449             // Now search for housenumber, if housenumber provided. Can be zero.
450             if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
451                 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
452
453                 // Downgrade the rank of the street results, they are missing
454                 // the housenumber. Also drop POI places (rank 30) here, they
455                 // cannot be a parent place and therefore must not be shown
456                 // as a result for a search with a missing housenumber.
457                 foreach ($aResults as $oRes) {
458                     if ($oRes->iAddressRank < 28) {
459                         if ($oRes->iAddressRank >= 26) {
460                             $oRes->iResultRank++;
461                         } else {
462                             $oRes->iResultRank += 2;
463                         }
464                         $aHnResults[$oRes->iId] = $oRes;
465                     }
466                 }
467
468                 $aResults = $aHnResults;
469             }
470
471             // finally get POIs if requested
472             if ($this->sClass && !empty($aResults)) {
473                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
474             }
475         }
476
477         Debug::printDebugTable('Place IDs', $aResults);
478
479         if (!empty($aResults) && $this->sPostcode) {
480             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
481             if ($sPlaceIds) {
482                 $sSQL = 'SELECT place_id FROM placex';
483                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
484                 $sSQL .= " AND postcode != '".$this->sPostcode."'";
485                 Debug::printSQL($sSQL);
486                 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
487                 if ($aFilteredPlaceIDs) {
488                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
489                         $aResults[$iPlaceId]->iResultRank++;
490                     }
491                 }
492             }
493         }
494
495         return $aResults;
496     }
497
498
499     private function queryCountry(&$oDB)
500     {
501         $sSQL = 'SELECT place_id FROM placex ';
502         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
503         $sSQL .= ' AND rank_search = 4';
504         if ($this->oContext->bViewboxBounded) {
505             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
506         }
507         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
508
509         Debug::printSQL($sSQL);
510
511         $iPlaceId = $oDB->getOne($sSQL);
512
513         $aResults = array();
514         if ($iPlaceId) {
515             $aResults[$iPlaceId] = new Result($iPlaceId);
516         }
517
518         return $aResults;
519     }
520
521     private function queryNearbyPoi(&$oDB, $iLimit)
522     {
523         if (!$this->sClass) {
524             return array();
525         }
526
527         $aDBResults = array();
528         $sPoiTable = $this->poiTable();
529
530         if ($oDB->tableExists($sPoiTable)) {
531             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
532             if ($this->oContext->sqlCountryList) {
533                 $sSQL .= ' JOIN placex USING (place_id)';
534             }
535             if ($this->oContext->hasNearPoint()) {
536                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
537             } elseif ($this->oContext->bViewboxBounded) {
538                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
539             }
540             if ($this->oContext->sqlCountryList) {
541                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
542             }
543             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
544             if ($this->oContext->sqlViewboxCentre) {
545                 $sSQL .= ' ORDER BY ST_Distance(';
546                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
547             } elseif ($this->oContext->hasNearPoint()) {
548                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
549             }
550             $sSQL .= " LIMIT $iLimit";
551             Debug::printSQL($sSQL);
552             $aDBResults = $oDB->getCol($sSQL);
553         }
554
555         if ($this->oContext->hasNearPoint()) {
556             $sSQL = 'SELECT place_id FROM placex WHERE ';
557             $sSQL .= 'class = :class and type = :type';
558             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
559             $sSQL .= ' AND linked_place_id is null';
560             if ($this->oContext->sqlCountryList) {
561                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
562             }
563             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
564             $sSQL .= " LIMIT $iLimit";
565             Debug::printSQL($sSQL);
566             $aDBResults = $oDB->getCol(
567                 $sSQL,
568                 array(':class' => $this->sClass, ':type' => $this->sType)
569             );
570         }
571
572         $aResults = array();
573         foreach ($aDBResults as $iPlaceId) {
574             $aResults[$iPlaceId] = new Result($iPlaceId);
575         }
576
577         return $aResults;
578     }
579
580     private function queryPostcode(&$oDB, $iLimit)
581     {
582         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
583
584         if (!empty($this->aAddress)) {
585             $sSQL .= ', search_name s ';
586             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
587             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
588             $sSQL .= '      @> '.$oDB->getArraySQL($this->aAddress).' AND ';
589         } else {
590             $sSQL .= 'WHERE ';
591         }
592
593         $sSQL .= "p.postcode = '".reset($this->aName)."'";
594         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
595         if ($this->oContext->bViewboxBounded) {
596             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
597         }
598         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
599         $sSQL .= " LIMIT $iLimit";
600
601         Debug::printSQL($sSQL);
602
603         $aResults = array();
604         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
605             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
606         }
607
608         return $aResults;
609     }
610
611     private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
612     {
613         $aTerms = array();
614         $aOrder = array();
615
616         // Sort by existence of the requested house number but only if not
617         // too many results are expected for the street, i.e. if the result
618         // will be narrowed down by an address. Remeber that with ordering
619         // every single result has to be checked.
620         if ($this->sHouseNumber && ($this->bRareName || !empty($this->aAddress) || $this->sPostcode)) {
621             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
622             $aOrder[] = ' (';
623             $aOrder[0] .= 'EXISTS(';
624             $aOrder[0] .= '  SELECT place_id';
625             $aOrder[0] .= '  FROM placex';
626             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
627             $aOrder[0] .= "    AND housenumber ~* E'".$sHouseNumberRegex."'";
628             $aOrder[0] .= '  LIMIT 1';
629             $aOrder[0] .= ') ';
630             // also housenumbers from interpolation lines table are needed
631             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
632                 $iHouseNumber = intval($this->sHouseNumber);
633                 $aOrder[0] .= 'OR EXISTS(';
634                 $aOrder[0] .= '  SELECT place_id ';
635                 $aOrder[0] .= '  FROM location_property_osmline ';
636                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
637                 $aOrder[0] .= '    AND startnumber is not NULL';
638                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
639                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
640                 $aOrder[0] .= '  LIMIT 1';
641                 $aOrder[0] .= ')';
642             }
643             $aOrder[0] .= ') DESC';
644         }
645
646         if (!empty($this->aName)) {
647             $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
648         }
649         if (!empty($this->aAddress)) {
650             // For infrequent name terms disable index usage for address
651             if ($this->bRareName) {
652                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
653             } else {
654                 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
655             }
656         }
657
658         $sCountryTerm = $this->countryCodeSQL('country_code');
659         if ($sCountryTerm) {
660             $aTerms[] = $sCountryTerm;
661         }
662
663         if ($this->sHouseNumber) {
664             $aTerms[] = 'address_rank between 16 and 30';
665         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
666             if ($iMinAddressRank > 0) {
667                 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
668             }
669         }
670
671         if ($this->oContext->hasNearPoint()) {
672             $aTerms[] = $this->oContext->withinSQL('centroid');
673             $aOrder[] = $this->oContext->distanceSQL('centroid');
674         } elseif ($this->sPostcode) {
675             if (empty($this->aAddress)) {
676                 $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             } else {
678                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
679             }
680         }
681
682         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
683         if ($sExcludeSQL) {
684             $aTerms[] = $sExcludeSQL;
685         }
686
687         if ($this->oContext->bViewboxBounded) {
688             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
689         }
690
691         if ($this->oContext->hasNearPoint()) {
692             $aOrder[] = $this->oContext->distanceSQL('centroid');
693         }
694
695         if ($this->sHouseNumber) {
696             $sImportanceSQL = '- abs(26 - address_rank) + 3';
697         } else {
698             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
699         }
700         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
701         $aOrder[] = "$sImportanceSQL DESC";
702
703         $aFullNameAddress = $this->oContext->getFullNameTerms();
704         if (!empty($aFullNameAddress)) {
705             $sExactMatchSQL = ' ( ';
706             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
707             $sExactMatchSQL .= '  SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
708             $sExactMatchSQL .= '    INTERSECT ';
709             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
710             $sExactMatchSQL .= ' ) s';
711             $sExactMatchSQL .= ') as exactmatch';
712             $aOrder[] = 'exactmatch DESC';
713         } else {
714             $sExactMatchSQL = '0::int as exactmatch';
715         }
716
717         if ($this->sHouseNumber || $this->sClass) {
718             $iLimit = 40;
719         }
720
721         $aResults = array();
722
723         if (!empty($aTerms)) {
724             $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
725             $sSQL .= ' FROM search_name';
726             $sSQL .= ' WHERE '.join(' and ', $aTerms);
727             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
728             $sSQL .= ' LIMIT '.$iLimit;
729
730             Debug::printSQL($sSQL);
731
732             $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
733
734             foreach ($aDBResults as $aResult) {
735                 $oResult = new Result($aResult['place_id']);
736                 $oResult->iExactMatches = $aResult['exactmatch'];
737                 $oResult->iAddressRank = $aResult['address_rank'];
738                 $aResults[$aResult['place_id']] = $oResult;
739             }
740         }
741
742         return $aResults;
743     }
744
745     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
746     {
747         $aResults = array();
748         $sRoadPlaceIDs = Result::joinIdsByTableMaxRank(
749             $aRoadPlaceIDs,
750             Result::TABLE_PLACEX,
751             27
752         );
753         $sPOIPlaceIDs = Result::joinIdsByTableMinRank(
754             $aRoadPlaceIDs,
755             Result::TABLE_PLACEX,
756             30
757         );
758
759         $aIDCondition = array();
760         if ($sRoadPlaceIDs) {
761             $aIDCondition[] = 'parent_place_id in ('.$sRoadPlaceIDs.')';
762         }
763         if ($sPOIPlaceIDs) {
764             $aIDCondition[] = 'place_id in ('.$sPOIPlaceIDs.')';
765         }
766
767         if (empty($aIDCondition)) {
768             return $aResults;
769         }
770
771         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
772         $sSQL = 'SELECT place_id FROM placex WHERE';
773         $sSQL .= "  housenumber ~* E'".$sHouseNumberRegex."'";
774         $sSQL .= ' AND ('.join(' OR ', $aIDCondition).')';
775         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
776
777         Debug::printSQL($sSQL);
778
779         // XXX should inherit the exactMatches from its parent
780         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
781             $aResults[$iPlaceId] = new Result($iPlaceId);
782         }
783
784         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
785         $iHousenumber = intval($this->sHouseNumber);
786         if ($bIsIntHouseNumber && $sRoadPlaceIDs && empty($aResults)) {
787             // if nothing found, search in the interpolation line table
788             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
789             $sSQL .= ' WHERE startnumber is not NULL';
790             $sSQL .= '  AND parent_place_id in ('.$sRoadPlaceIDs.') AND (';
791             if ($iHousenumber % 2 == 0) {
792                 // If housenumber is even, look for housenumber in streets
793                 // with interpolationtype even or all.
794                 $sSQL .= "interpolationtype='even'";
795             } else {
796                 // Else look for housenumber with interpolationtype odd or all.
797                 $sSQL .= "interpolationtype='odd'";
798             }
799             $sSQL .= " or interpolationtype='all') and ";
800             $sSQL .= $iHousenumber.'>=startnumber and ';
801             $sSQL .= $iHousenumber.'<=endnumber';
802             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
803
804             Debug::printSQL($sSQL);
805
806             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
807                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
808                 $oResult->iHouseNumber = $iHousenumber;
809                 $aResults[$iPlaceId] = $oResult;
810             }
811         }
812
813         // If nothing found then search in Tiger data (location_property_tiger)
814         if (CONST_Use_US_Tiger_Data && $sRoadPlaceIDs && $bIsIntHouseNumber && empty($aResults)) {
815             $sSQL = 'SELECT place_id FROM location_property_tiger';
816             $sSQL .= ' WHERE parent_place_id in ('.$sRoadPlaceIDs.') and (';
817             if ($iHousenumber % 2 == 0) {
818                 $sSQL .= "interpolationtype='even'";
819             } else {
820                 $sSQL .= "interpolationtype='odd'";
821             }
822             $sSQL .= " or interpolationtype='all') and ";
823             $sSQL .= $iHousenumber.'>=startnumber and ';
824             $sSQL .= $iHousenumber.'<=endnumber';
825             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
826
827             Debug::printSQL($sSQL);
828
829             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
830                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
831                 $oResult->iHouseNumber = $iHousenumber;
832                 $aResults[$iPlaceId] = $oResult;
833             }
834         }
835
836         return $aResults;
837     }
838
839
840     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
841     {
842         $aResults = array();
843         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
844
845         if (!$sPlaceIDs) {
846             return $aResults;
847         }
848
849         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
850             // If they were searching for a named class (i.e. 'Kings Head pub')
851             // then we might have an extra match
852             $sSQL = 'SELECT place_id FROM placex ';
853             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
854             $sSQL .= "   AND class='".$this->sClass."' ";
855             $sSQL .= "   AND type='".$this->sType."'";
856             $sSQL .= '   AND linked_place_id is null';
857             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
858             $sSQL .= ' ORDER BY rank_search ASC ';
859             $sSQL .= " LIMIT $iLimit";
860
861             Debug::printSQL($sSQL);
862
863             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
864                 $aResults[$iPlaceId] = new Result($iPlaceId);
865             }
866         }
867
868         // NEAR and IN are handled the same
869         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
870             $sClassTable = $this->poiTable();
871             $bCacheTable = $oDB->tableExists($sClassTable);
872
873             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
874             Debug::printSQL($sSQL);
875             $iMaxRank = (int) $oDB->getOne($sSQL);
876
877             // For state / country level searches the normal radius search doesn't work very well
878             $sPlaceGeom = false;
879             if ($iMaxRank < 9 && $bCacheTable) {
880                 // Try and get a polygon to search in instead
881                 $sSQL = 'SELECT geometry FROM placex';
882                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
883                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
884                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
885                 $sSQL .= ' ORDER BY rank_search ASC ';
886                 $sSQL .= ' LIMIT 1';
887                 Debug::printSQL($sSQL);
888                 $sPlaceGeom = $oDB->getOne($sSQL);
889             }
890
891             if ($sPlaceGeom) {
892                 $sPlaceIDs = false;
893             } else {
894                 $iMaxRank += 5;
895                 $sSQL = 'SELECT place_id FROM placex';
896                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
897                 Debug::printSQL($sSQL);
898                 $aPlaceIDs = $oDB->getCol($sSQL);
899                 $sPlaceIDs = join(',', $aPlaceIDs);
900             }
901
902             if ($sPlaceIDs || $sPlaceGeom) {
903                 $fRange = 0.01;
904                 if ($bCacheTable) {
905                     // More efficient - can make the range bigger
906                     $fRange = 0.05;
907
908                     $sOrderBySQL = '';
909                     if ($this->oContext->hasNearPoint()) {
910                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
911                     } elseif ($sPlaceIDs) {
912                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
913                     } elseif ($sPlaceGeom) {
914                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
915                     }
916
917                     $sSQL = 'SELECT distinct i.place_id';
918                     if ($sOrderBySQL) {
919                         $sSQL .= ', i.order_term';
920                     }
921                     $sSQL .= ' from (SELECT l.place_id';
922                     if ($sOrderBySQL) {
923                         $sSQL .= ','.$sOrderBySQL.' as order_term';
924                     }
925                     $sSQL .= ' from '.$sClassTable.' as l';
926
927                     if ($sPlaceIDs) {
928                         $sSQL .= ',placex as f WHERE ';
929                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
930                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
931                     } elseif ($sPlaceGeom) {
932                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
933                     }
934
935                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
936                     $sSQL .= 'limit 300) i ';
937                     if ($sOrderBySQL) {
938                         $sSQL .= 'order by order_term asc';
939                     }
940                     $sSQL .= " limit $iLimit";
941
942                     Debug::printSQL($sSQL);
943
944                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
945                         $aResults[$iPlaceId] = new Result($iPlaceId);
946                     }
947                 } else {
948                     if ($this->oContext->hasNearPoint()) {
949                         $fRange = $this->oContext->nearRadius();
950                     }
951
952                     $sOrderBySQL = '';
953                     if ($this->oContext->hasNearPoint()) {
954                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
955                     } else {
956                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
957                     }
958
959                     $sSQL = 'SELECT distinct l.place_id';
960                     if ($sOrderBySQL) {
961                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
962                     }
963                     $sSQL .= ' FROM placex as l, placex as f';
964                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
965                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
966                     $sSQL .= "  AND l.class='".$this->sClass."'";
967                     $sSQL .= "  AND l.type='".$this->sType."'";
968                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
969                     if ($sOrderBySQL) {
970                         $sSQL .= 'ORDER BY orderterm ASC';
971                     }
972                     $sSQL .= " limit $iLimit";
973
974                     Debug::printSQL($sSQL);
975
976                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
977                         $aResults[$iPlaceId] = new Result($iPlaceId);
978                     }
979                 }
980             }
981         }
982
983         return $aResults;
984     }
985
986     private function poiTable()
987     {
988         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
989     }
990
991     private function countryCodeSQL($sVar)
992     {
993         if ($this->sCountryCode) {
994             return $sVar.' = \''.$this->sCountryCode."'";
995         }
996         if ($this->oContext->sqlCountryList) {
997             return $sVar.' in '.$this->oContext->sqlCountryList;
998         }
999
1000         return '';
1001     }
1002
1003     /////////// Sort functions
1004
1005
1006     public static function bySearchRank($a, $b)
1007     {
1008         if ($a->iSearchRank == $b->iSearchRank) {
1009             return $a->iOperator + strlen($a->sHouseNumber)
1010                      - $b->iOperator - strlen($b->sHouseNumber);
1011         }
1012
1013         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1014     }
1015
1016     //////////// Debugging functions
1017
1018
1019     public function debugInfo()
1020     {
1021         return array(
1022                 'Search rank' => $this->iSearchRank,
1023                 'Country code' => $this->sCountryCode,
1024                 'Name terms' => $this->aName,
1025                 'Name terms (stop words)' => $this->aNameNonSearch,
1026                 'Address terms' => $this->aAddress,
1027                 'Address terms (stop words)' => $this->aAddressNonSearch,
1028                 'Address terms (full words)' => $this->aFullNameAddress ?? '',
1029                 'Special search' => $this->iOperator,
1030                 'Class' => $this->sClass,
1031                 'Type' => $this->sType,
1032                 'House number' => $this->sHouseNumber,
1033                 'Postcode' => $this->sPostcode
1034                );
1035     }
1036
1037     public function dumpAsHtmlTableRow(&$aWordIDs)
1038     {
1039         $kf = function ($k) use (&$aWordIDs) {
1040             return $aWordIDs[$k] ?? '['.$k.']';
1041         };
1042
1043         echo '<tr>';
1044         echo "<td>$this->iSearchRank</td>";
1045         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1046         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1047         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1048         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1049         echo '<td>'.$this->sCountryCode.'</td>';
1050         echo '<td>'.Operator::toString($this->iOperator).'</td>';
1051         echo '<td>'.$this->sClass.'</td>';
1052         echo '<td>'.$this->sType.'</td>';
1053         echo '<td>'.$this->sPostcode.'</td>';
1054         echo '<td>'.$this->sHouseNumber.'</td>';
1055
1056         echo '</tr>';
1057     }
1058 }