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