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