]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/SearchDescription.php
respect exclude_place_ids for housenumber search
[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             // finally get POIs if requested
424             if ($this->sClass && !empty($aResults)) {
425                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
426             }
427         }
428
429         Debug::printDebugTable('Place IDs', $aResults);
430
431         if (!empty($aResults) && $this->sPostcode) {
432             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
433             if ($sPlaceIds) {
434                 $sSQL = 'SELECT place_id FROM placex';
435                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
436                 $sSQL .= " AND postcode != '".$this->sPostcode."'";
437                 Debug::printSQL($sSQL);
438                 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
439                 if ($aFilteredPlaceIDs) {
440                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
441                         $aResults[$iPlaceId]->iResultRank++;
442                     }
443                 }
444             }
445         }
446
447         return $aResults;
448     }
449
450
451     private function queryCountry(&$oDB)
452     {
453         $sSQL = 'SELECT place_id FROM placex ';
454         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
455         $sSQL .= ' AND rank_search = 4';
456         if ($this->oContext->bViewboxBounded) {
457             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
458         }
459         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
460
461         Debug::printSQL($sSQL);
462
463         $iPlaceId = $oDB->getOne($sSQL);
464
465         $aResults = array();
466         if ($iPlaceId) {
467             $aResults[$iPlaceId] = new Result($iPlaceId);
468         }
469
470         return $aResults;
471     }
472
473     private function queryNearbyPoi(&$oDB, $iLimit)
474     {
475         if (!$this->sClass) {
476             return array();
477         }
478
479         $aDBResults = array();
480         $sPoiTable = $this->poiTable();
481
482         if ($oDB->tableExists($sPoiTable)) {
483             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
484             if ($this->oContext->sqlCountryList) {
485                 $sSQL .= ' JOIN placex USING (place_id)';
486             }
487             if ($this->oContext->hasNearPoint()) {
488                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
489             } elseif ($this->oContext->bViewboxBounded) {
490                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
491             }
492             if ($this->oContext->sqlCountryList) {
493                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
494             }
495             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
496             if ($this->oContext->sqlViewboxCentre) {
497                 $sSQL .= ' ORDER BY ST_Distance(';
498                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
499             } elseif ($this->oContext->hasNearPoint()) {
500                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
501             }
502             $sSQL .= " LIMIT $iLimit";
503             Debug::printSQL($sSQL);
504             $aDBResults = $oDB->getCol($sSQL);
505         }
506
507         if ($this->oContext->hasNearPoint()) {
508             $sSQL = 'SELECT place_id FROM placex WHERE ';
509             $sSQL .= 'class = :class and type = :type';
510             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
511             $sSQL .= ' AND linked_place_id is null';
512             if ($this->oContext->sqlCountryList) {
513                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
514             }
515             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
516             $sSQL .= " LIMIT $iLimit";
517             Debug::printSQL($sSQL);
518             $aDBResults = $oDB->getCol(
519                 $sSQL,
520                 array(':class' => $this->sClass, ':type' => $this->sType)
521             );
522         }
523
524         $aResults = array();
525         foreach ($aDBResults as $iPlaceId) {
526             $aResults[$iPlaceId] = new Result($iPlaceId);
527         }
528
529         return $aResults;
530     }
531
532     private function queryPostcode(&$oDB, $iLimit)
533     {
534         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
535
536         if (!empty($this->aAddress)) {
537             $sSQL .= ', search_name s ';
538             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
539             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
540             $sSQL .= '      @> '.$oDB->getArraySQL($this->aAddress).' AND ';
541         } else {
542             $sSQL .= 'WHERE ';
543         }
544
545         $sSQL .= "p.postcode = '".reset($this->aName)."'";
546         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
547         if ($this->oContext->bViewboxBounded) {
548             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
549         }
550         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
551         $sSQL .= " LIMIT $iLimit";
552
553         Debug::printSQL($sSQL);
554
555         $aResults = array();
556         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
557             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
558         }
559
560         return $aResults;
561     }
562
563     private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
564     {
565         $aTerms = array();
566         $aOrder = array();
567
568         if (!empty($this->aName)) {
569             $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
570         }
571         if (!empty($this->aAddress)) {
572             // For infrequent name terms disable index usage for address
573             if ($this->bRareName) {
574                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
575             } else {
576                 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
577             }
578         }
579
580         $sCountryTerm = $this->countryCodeSQL('country_code');
581         if ($sCountryTerm) {
582             $aTerms[] = $sCountryTerm;
583         }
584
585         if ($this->sHouseNumber) {
586             $aTerms[] = 'address_rank between 16 and 30';
587         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
588             if ($iMinAddressRank > 0) {
589                 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
590             }
591         }
592
593         if ($this->oContext->hasNearPoint()) {
594             $aTerms[] = $this->oContext->withinSQL('centroid');
595             $aOrder[] = $this->oContext->distanceSQL('centroid');
596         } elseif ($this->sPostcode) {
597             if (empty($this->aAddress)) {
598                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.12))";
599             } else {
600                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
601             }
602         }
603
604         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
605         if ($sExcludeSQL) {
606             $aTerms[] = $sExcludeSQL;
607         }
608
609         if ($this->oContext->bViewboxBounded) {
610             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
611         }
612
613         if ($this->sHouseNumber) {
614             $sImportanceSQL = '- abs(26 - address_rank) + 3';
615         } else {
616             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
617         }
618         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
619         $aOrder[] = "$sImportanceSQL DESC";
620
621         $aFullNameAddress = $this->oContext->getFullNameTerms();
622         if (!empty($aFullNameAddress)) {
623             $sExactMatchSQL = ' ( ';
624             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
625             $sExactMatchSQL .= '  SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
626             $sExactMatchSQL .= '    INTERSECT ';
627             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
628             $sExactMatchSQL .= ' ) s';
629             $sExactMatchSQL .= ') as exactmatch';
630             $aOrder[] = 'exactmatch DESC';
631         } else {
632             $sExactMatchSQL = '0::int as exactmatch';
633         }
634
635         if (empty($aTerms)) {
636             return array();
637         }
638
639         if ($this->hasHousenumber()) {
640             $sHouseNumberRegex = $oDB->getDBQuoted('\\\\m'.$this->sHouseNumber.'\\\\M');
641
642             // Housenumbers on streets and places.
643             $sPlacexSql = 'SELECT array_agg(place_id) FROM placex';
644             $sPlacexSql .= ' WHERE parent_place_id = sin.place_id AND sin.address_rank < 30';
645             $sPlacexSql .= $this->oContext->excludeSQL(' AND place_id');
646             $sPlacexSql .= '       and housenumber ~* E'.$sHouseNumberRegex;
647
648             // Interpolations on streets and places.
649             $sInterpolSql = 'null';
650             $sTigerSql = 'null';
651             if (preg_match('/^[0-9]+$/', $this->sHouseNumber)) {
652                 $sIpolHnr = 'WHERE parent_place_id = sin.place_id ';
653                 $sIpolHnr .= '  AND startnumber is not NULL AND sin.address_rank < 30';
654                 $sIpolHnr .= '  AND '.$this->sHouseNumber.' between startnumber and endnumber';
655                 $sIpolHnr .= '  AND ('.$this->sHouseNumber.' - startnumber) % step = 0';
656
657                 $sInterpolSql = 'SELECT array_agg(place_id) FROM location_property_osmline '.$sIpolHnr;
658                 if (CONST_Use_US_Tiger_Data) {
659                     $sTigerSql = 'SELECT array_agg(place_id) FROM location_property_tiger '.$sIpolHnr;
660                     $sTigerSql .= "      and sin.country_code = 'us'";
661                 }
662             }
663
664             if ($this->sClass) {
665                 $iLimit = 40;
666             }
667
668             $sSelfHnr = 'SELECT * FROM placex WHERE place_id = search_name.place_id';
669             $sSelfHnr .= '    AND housenumber ~* E'.$sHouseNumberRegex;
670
671             $aTerms[] = '(address_rank < 30 or exists('.$sSelfHnr.'))';
672
673
674             $sSQL = 'SELECT sin.*, ';
675             $sSQL .=        '('.$sPlacexSql.') as placex_hnr, ';
676             $sSQL .=        '('.$sInterpolSql.') as interpol_hnr, ';
677             $sSQL .=        '('.$sTigerSql.') as tiger_hnr ';
678             $sSQL .= ' FROM (';
679             $sSQL .= '    SELECT place_id, address_rank, country_code,'.$sExactMatchSQL.',';
680             $sSQL .= '            CASE WHEN importance = 0 OR importance IS NULL';
681             $sSQL .= '               THEN 0.75001-(search_rank::float/40) ELSE importance END as importance';
682             $sSQL .= '     FROM search_name';
683             $sSQL .= '     WHERE '.join(' and ', $aTerms);
684             $sSQL .= '     ORDER BY '.join(', ', $aOrder);
685             $sSQL .= '     LIMIT 40000';
686             $sSQL .= ') as sin';
687             $sSQL .= ' ORDER BY address_rank = 30 desc, placex_hnr, interpol_hnr, tiger_hnr,';
688             $sSQL .= '          importance';
689             $sSQL .= ' LIMIT '.$iLimit;
690         } else {
691             if ($this->sClass) {
692                 $iLimit = 40;
693             }
694
695             $sSQL = 'SELECT place_id, address_rank, '.$sExactMatchSQL;
696             $sSQL .= ' FROM search_name';
697             $sSQL .= ' WHERE '.join(' and ', $aTerms);
698             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
699             $sSQL .= ' LIMIT '.$iLimit;
700         }
701
702         Debug::printSQL($sSQL);
703
704         $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
705
706         $aResults = array();
707
708         foreach ($aDBResults as $aResult) {
709             $oResult = new Result($aResult['place_id']);
710             $oResult->iExactMatches = $aResult['exactmatch'];
711             $oResult->iAddressRank = $aResult['address_rank'];
712
713             $bNeedResult = true;
714             if ($this->hasHousenumber() && $aResult['address_rank'] < 30) {
715                 if ($aResult['placex_hnr']) {
716                     foreach (explode(',', substr($aResult['placex_hnr'], 1, -1)) as $sPlaceID) {
717                         $iPlaceID = intval($sPlaceID);
718                         $oHnrResult = new Result($iPlaceID);
719                         $oHnrResult->iExactMatches = $aResult['exactmatch'];
720                         $oHnrResult->iAddressRank = 30;
721                         $aResults[$iPlaceID] = $oHnrResult;
722                         $bNeedResult = false;
723                     }
724                 }
725                 if ($aResult['interpol_hnr']) {
726                     foreach (explode(',', substr($aResult['interpol_hnr'], 1, -1)) as $sPlaceID) {
727                         $iPlaceID = intval($sPlaceID);
728                         $oHnrResult = new Result($iPlaceID, Result::TABLE_OSMLINE);
729                         $oHnrResult->iExactMatches = $aResult['exactmatch'];
730                         $oHnrResult->iAddressRank = 30;
731                         $oHnrResult->iHouseNumber = intval($this->sHouseNumber);
732                         $aResults[$iPlaceID] = $oHnrResult;
733                         $bNeedResult = false;
734                     }
735                 }
736                 if ($aResult['tiger_hnr']) {
737                     foreach (explode(',', substr($aResult['tiger_hnr'], 1, -1)) as $sPlaceID) {
738                         $iPlaceID = intval($sPlaceID);
739                         $oHnrResult = new Result($iPlaceID, Result::TABLE_TIGER);
740                         $oHnrResult->iExactMatches = $aResult['exactmatch'];
741                         $oHnrResult->iAddressRank = 30;
742                         $oHnrResult->iHouseNumber = intval($this->sHouseNumber);
743                         $aResults[$iPlaceID] = $oHnrResult;
744                         $bNeedResult = false;
745                     }
746                 }
747
748                 if ($aResult['address_rank'] < 26) {
749                     $oResult->iResultRank += 2;
750                 } else {
751                     $oResult->iResultRank++;
752                 }
753             }
754
755             if ($bNeedResult) {
756                 $aResults[$aResult['place_id']] = $oResult;
757             }
758         }
759
760         return $aResults;
761     }
762
763
764     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
765     {
766         $aResults = array();
767         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
768
769         if (!$sPlaceIDs) {
770             return $aResults;
771         }
772
773         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
774             // If they were searching for a named class (i.e. 'Kings Head pub')
775             // then we might have an extra match
776             $sSQL = 'SELECT place_id FROM placex ';
777             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
778             $sSQL .= "   AND class='".$this->sClass."' ";
779             $sSQL .= "   AND type='".$this->sType."'";
780             $sSQL .= '   AND linked_place_id is null';
781             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
782             $sSQL .= ' ORDER BY rank_search ASC ';
783             $sSQL .= " LIMIT $iLimit";
784
785             Debug::printSQL($sSQL);
786
787             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
788                 $aResults[$iPlaceId] = new Result($iPlaceId);
789             }
790         }
791
792         // NEAR and IN are handled the same
793         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
794             $sClassTable = $this->poiTable();
795             $bCacheTable = $oDB->tableExists($sClassTable);
796
797             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
798             Debug::printSQL($sSQL);
799             $iMaxRank = (int) $oDB->getOne($sSQL);
800
801             // For state / country level searches the normal radius search doesn't work very well
802             $sPlaceGeom = false;
803             if ($iMaxRank < 9 && $bCacheTable) {
804                 // Try and get a polygon to search in instead
805                 $sSQL = 'SELECT geometry FROM placex';
806                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
807                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
808                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
809                 $sSQL .= ' ORDER BY rank_search ASC ';
810                 $sSQL .= ' LIMIT 1';
811                 Debug::printSQL($sSQL);
812                 $sPlaceGeom = $oDB->getOne($sSQL);
813             }
814
815             if ($sPlaceGeom) {
816                 $sPlaceIDs = false;
817             } else {
818                 $iMaxRank += 5;
819                 $sSQL = 'SELECT place_id FROM placex';
820                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
821                 Debug::printSQL($sSQL);
822                 $aPlaceIDs = $oDB->getCol($sSQL);
823                 $sPlaceIDs = join(',', $aPlaceIDs);
824             }
825
826             if ($sPlaceIDs || $sPlaceGeom) {
827                 $fRange = 0.01;
828                 if ($bCacheTable) {
829                     // More efficient - can make the range bigger
830                     $fRange = 0.05;
831
832                     $sOrderBySQL = '';
833                     if ($this->oContext->hasNearPoint()) {
834                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
835                     } elseif ($sPlaceIDs) {
836                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
837                     } elseif ($sPlaceGeom) {
838                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
839                     }
840
841                     $sSQL = 'SELECT distinct i.place_id';
842                     if ($sOrderBySQL) {
843                         $sSQL .= ', i.order_term';
844                     }
845                     $sSQL .= ' from (SELECT l.place_id';
846                     if ($sOrderBySQL) {
847                         $sSQL .= ','.$sOrderBySQL.' as order_term';
848                     }
849                     $sSQL .= ' from '.$sClassTable.' as l';
850
851                     if ($sPlaceIDs) {
852                         $sSQL .= ',placex as f WHERE ';
853                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
854                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
855                     } elseif ($sPlaceGeom) {
856                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
857                     }
858
859                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
860                     $sSQL .= 'limit 300) i ';
861                     if ($sOrderBySQL) {
862                         $sSQL .= 'order by order_term asc';
863                     }
864                     $sSQL .= " limit $iLimit";
865
866                     Debug::printSQL($sSQL);
867
868                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
869                         $aResults[$iPlaceId] = new Result($iPlaceId);
870                     }
871                 } else {
872                     if ($this->oContext->hasNearPoint()) {
873                         $fRange = $this->oContext->nearRadius();
874                     }
875
876                     $sOrderBySQL = '';
877                     if ($this->oContext->hasNearPoint()) {
878                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
879                     } else {
880                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
881                     }
882
883                     $sSQL = 'SELECT distinct l.place_id';
884                     if ($sOrderBySQL) {
885                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
886                     }
887                     $sSQL .= ' FROM placex as l, placex as f';
888                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
889                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
890                     $sSQL .= "  AND l.class='".$this->sClass."'";
891                     $sSQL .= "  AND l.type='".$this->sType."'";
892                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
893                     if ($sOrderBySQL) {
894                         $sSQL .= 'ORDER BY orderterm ASC';
895                     }
896                     $sSQL .= " limit $iLimit";
897
898                     Debug::printSQL($sSQL);
899
900                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
901                         $aResults[$iPlaceId] = new Result($iPlaceId);
902                     }
903                 }
904             }
905         }
906
907         return $aResults;
908     }
909
910     private function poiTable()
911     {
912         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
913     }
914
915     private function countryCodeSQL($sVar)
916     {
917         if ($this->sCountryCode) {
918             return $sVar.' = \''.$this->sCountryCode."'";
919         }
920         if ($this->oContext->sqlCountryList) {
921             return $sVar.' in '.$this->oContext->sqlCountryList;
922         }
923
924         return '';
925     }
926
927     /////////// Sort functions
928
929
930     public static function bySearchRank($a, $b)
931     {
932         if ($a->iSearchRank == $b->iSearchRank) {
933             return $a->iOperator + strlen($a->sHouseNumber)
934                      - $b->iOperator - strlen($b->sHouseNumber);
935         }
936
937         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
938     }
939
940     //////////// Debugging functions
941
942
943     public function debugInfo()
944     {
945         return array(
946                 'Search rank' => $this->iSearchRank,
947                 'Country code' => $this->sCountryCode,
948                 'Name terms' => $this->aName,
949                 'Name terms (stop words)' => $this->aNameNonSearch,
950                 'Address terms' => $this->aAddress,
951                 'Address terms (stop words)' => $this->aAddressNonSearch,
952                 'Address terms (full words)' => $this->aFullNameAddress ?? '',
953                 'Special search' => $this->iOperator,
954                 'Class' => $this->sClass,
955                 'Type' => $this->sType,
956                 'House number' => $this->sHouseNumber,
957                 'Postcode' => $this->sPostcode
958                );
959     }
960
961     public function dumpAsHtmlTableRow(&$aWordIDs)
962     {
963         $kf = function ($k) use (&$aWordIDs) {
964             return $aWordIDs[$k] ?? '['.$k.']';
965         };
966
967         echo '<tr>';
968         echo "<td>$this->iSearchRank</td>";
969         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
970         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
971         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
972         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
973         echo '<td>'.$this->sCountryCode.'</td>';
974         echo '<td>'.Operator::toString($this->iOperator).'</td>';
975         echo '<td>'.$this->sClass.'</td>';
976         echo '<td>'.$this->sType.'</td>';
977         echo '<td>'.$this->sPostcode.'</td>';
978         echo '<td>'.$this->sHouseNumber.'</td>';
979
980         echo '</tr>';
981     }
982 }