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