]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/SearchDescription.php
Merge pull request #2212 from darkshredder/country-name
[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                 $oSearch = clone $this;
222                 $oSearch->iSearchRank++;
223                 $oSearch->iNamePhrase = -1;
224                 $oSearch->sHouseNumber = $oSearchTerm->sToken;
225                 if ($this->iOperator != Operator::NONE) {
226                     $oSearch->iSearchRank++;
227                 }
228                 // sanity check: if the housenumber is not mainly made
229                 // up of numbers, add a penalty
230                 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
231                     || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
232                     $oSearch->iSearchRank++;
233                 }
234                 if (empty($oSearchTerm->iId)) {
235                     $oSearch->iSearchRank++;
236                 }
237                 // also must not appear in the middle of the address
238                 if (!empty($this->aAddress)
239                     || (!empty($this->aAddressNonSearch))
240                     || $this->sPostcode
241                 ) {
242                     $oSearch->iSearchRank++;
243                 }
244                 $aNewSearches[] = $oSearch;
245                 // Housenumbers may appear in the name when the place has its own
246                 // address terms.
247                 if ($oSearchTerm->iId !== null
248                     && ($this->iNamePhrase >= 0 || empty($this->aName))
249                     && empty($this->aAddress)
250                    ) {
251                     $oSearch = clone $this;
252                     $oSearch->iSearchRank++;
253                     $oSearch->aAddress = $this->aName;
254                     $oSearch->bRareName = false;
255                     $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
256                     $aNewSearches[] = $oSearch;
257                 }
258             }
259         } elseif ($sPhraseType == ''
260                   && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
261         ) {
262             if ($this->iOperator == Operator::NONE) {
263                 $oSearch = clone $this;
264                 $oSearch->iSearchRank += 2;
265                 $oSearch->iNamePhrase = -1;
266
267                 $iOp = $oSearchTerm->iOperator;
268                 if ($iOp == Operator::NONE) {
269                     if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
270                         $iOp = Operator::NAME;
271                     } else {
272                         $iOp = Operator::NEAR;
273                     }
274                     $oSearch->iSearchRank += 2;
275                 } elseif (!$bFirstToken && !$bLastToken) {
276                     $oSearch->iSearchRank += 2;
277                 }
278                 if ($this->sHouseNumber) {
279                     $oSearch->iSearchRank++;
280                 }
281
282                 $oSearch->setPoiSearch(
283                     $iOp,
284                     $oSearchTerm->sClass,
285                     $oSearchTerm->sType
286                 );
287                 $aNewSearches[] = $oSearch;
288             }
289         } elseif ($sPhraseType != 'country'
290                   && is_a($oSearchTerm, '\Nominatim\Token\Word')
291         ) {
292             $iWordID = $oSearchTerm->iId;
293             // Full words can only be a name if they appear at the beginning
294             // of the phrase. In structured search the name must forcably in
295             // the first phrase. In unstructured search it may be in a later
296             // phrase when the first phrase is a house number.
297             if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
298                 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
299                     $oSearch = clone $this;
300                     $oSearch->iNamePhrase = -1;
301                     $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
302                     $oSearch->aAddress[$iWordID] = $iWordID;
303                     $aNewSearches[] = $oSearch;
304                 }
305             } elseif (empty($this->aNameNonSearch)) {
306                 $oSearch = clone $this;
307                 $oSearch->iSearchRank++;
308                 $oSearch->aName = array($iWordID => $iWordID);
309                 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
310                     $oSearch->bRareName =
311                         $oSearchTerm->iSearchNameCount
312                           < CONST_Search_NameOnlySearchFrequencyThreshold;
313                 }
314                 $aNewSearches[] = $oSearch;
315             }
316         }
317
318         return $aNewSearches;
319     }
320
321     /**
322      * Derive new searches by adding a partial term to the existing search.
323      *
324      * @param string  $sToken             Term for the token.
325      * @param object  $oSearchTerm        Description of the token.
326      * @param bool    $bStructuredPhrases True if the search is structured.
327      * @param integer $iPhrase            Number of the phrase the token is in.
328      * @param array[] $aFullTokens        List of full term tokens with the
329      *                                    same name.
330      *
331      * @return SearchDescription[] List of derived search descriptions.
332      */
333     public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
334     {
335         // Only allow name terms.
336         if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
337             return array();
338         }
339
340         $aNewSearches = array();
341         $iWordID = $oSearchTerm->iId;
342
343         if ((!$bStructuredPhrases || $iPhrase > 0)
344             && (!empty($this->aName))
345         ) {
346             $oSearch = clone $this;
347             $oSearch->iSearchRank++;
348             if (preg_match('#^[0-9 ]+$#', $sToken)) {
349                 $oSearch->iSearchRank++;
350             }
351             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
352                 $oSearch->aAddress[$iWordID] = $iWordID;
353             } else {
354                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
355                 if (!empty($aFullTokens)) {
356                     $oSearch->iSearchRank++;
357                 }
358             }
359             $aNewSearches[] = $oSearch;
360         }
361
362         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
363             && ((empty($this->aName) && empty($this->aNameNonSearch)) || $this->iNamePhrase == $iPhrase)
364             && strpos($sToken, ' ') === false
365         ) {
366             $oSearch = clone $this;
367             $oSearch->iSearchRank++;
368             if (empty($this->aName) && empty($this->aNameNonSearch)) {
369                 $oSearch->iSearchRank++;
370             }
371             if (preg_match('#^[0-9 ]+$#', $sToken)) {
372                 $oSearch->iSearchRank++;
373             }
374             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
375                 if (empty($this->aName)
376                     && CONST_Search_NameOnlySearchFrequencyThreshold
377                 ) {
378                     $oSearch->bRareName =
379                         $oSearchTerm->iSearchNameCount
380                           < CONST_Search_NameOnlySearchFrequencyThreshold;
381                 } else {
382                     $oSearch->bRareName = false;
383                 }
384                 $oSearch->aName[$iWordID] = $iWordID;
385             } else {
386                 if (!empty($aFullTokens)) {
387                     $oSearch->iSearchRank++;
388                 }
389                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
390             }
391             $oSearch->iNamePhrase = $iPhrase;
392             $aNewSearches[] = $oSearch;
393         }
394
395         return $aNewSearches;
396     }
397
398     /////////// Query functions
399
400
401     /**
402      * Query database for places that match this search.
403      *
404      * @param object  $oDB      Nominatim::DB instance to use.
405      * @param integer $iMinRank Minimum address rank to restrict search to.
406      * @param integer $iMaxRank Maximum address rank to restrict search to.
407      * @param integer $iLimit   Maximum number of results.
408      *
409      * @return mixed[] An array with two fields: IDs contains the list of
410      *                 matching place IDs and houseNumber the houseNumber
411      *                 if appicable or -1 if not.
412      */
413     public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
414     {
415         $aResults = array();
416         $iHousenumber = -1;
417
418         if ($this->sCountryCode
419             && empty($this->aName)
420             && !$this->iOperator
421             && !$this->sClass
422             && !$this->oContext->hasNearPoint()
423         ) {
424             // Just looking for a country - look it up
425             if (4 >= $iMinRank && 4 <= $iMaxRank) {
426                 $aResults = $this->queryCountry($oDB);
427             }
428         } elseif (empty($this->aName) && empty($this->aAddress)) {
429             // Neither name nor address? Then we must be
430             // looking for a POI in a geographic area.
431             if ($this->oContext->isBoundedSearch()) {
432                 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
433             }
434         } elseif ($this->iOperator == Operator::POSTCODE) {
435             // looking for postcode
436             $aResults = $this->queryPostcode($oDB, $iLimit);
437         } else {
438             // Ordinary search:
439             // First search for places according to name and address.
440             $aResults = $this->queryNamedPlace(
441                 $oDB,
442                 $iMinRank,
443                 $iMaxRank,
444                 $iLimit
445             );
446
447             // Now search for housenumber, if housenumber provided. Can be zero.
448             if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
449                 // Downgrade the rank of the street results, they are missing
450                 // the housenumber.
451                 foreach ($aResults as $oRes) {
452                     if ($oRes->iAddressRank >= 26) {
453                         $oRes->iResultRank++;
454                     } else {
455                         $oRes->iResultRank += 2;
456                     }
457                 }
458
459                 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
460
461                 if (!empty($aHnResults)) {
462                     foreach ($aHnResults as $oRes) {
463                         $aResults[$oRes->iId] = $oRes;
464                     }
465                 }
466             }
467
468             // finally get POIs if requested
469             if ($this->sClass && !empty($aResults)) {
470                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
471             }
472         }
473
474         Debug::printDebugTable('Place IDs', $aResults);
475
476         if (!empty($aResults) && $this->sPostcode) {
477             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
478             if ($sPlaceIds) {
479                 $sSQL = 'SELECT place_id FROM placex';
480                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
481                 $sSQL .= " AND postcode != '".$this->sPostcode."'";
482                 Debug::printSQL($sSQL);
483                 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
484                 if ($aFilteredPlaceIDs) {
485                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
486                         $aResults[$iPlaceId]->iResultRank++;
487                     }
488                 }
489             }
490         }
491
492         return $aResults;
493     }
494
495
496     private function queryCountry(&$oDB)
497     {
498         $sSQL = 'SELECT place_id FROM placex ';
499         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
500         $sSQL .= ' AND rank_search = 4';
501         if ($this->oContext->bViewboxBounded) {
502             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
503         }
504         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
505
506         Debug::printSQL($sSQL);
507
508         $iPlaceId = $oDB->getOne($sSQL);
509
510         $aResults = array();
511         if ($iPlaceId) {
512             $aResults[$iPlaceId] = new Result($iPlaceId);
513         }
514
515         return $aResults;
516     }
517
518     private function queryNearbyPoi(&$oDB, $iLimit)
519     {
520         if (!$this->sClass) {
521             return array();
522         }
523
524         $aDBResults = array();
525         $sPoiTable = $this->poiTable();
526
527         if ($oDB->tableExists($sPoiTable)) {
528             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
529             if ($this->oContext->sqlCountryList) {
530                 $sSQL .= ' JOIN placex USING (place_id)';
531             }
532             if ($this->oContext->hasNearPoint()) {
533                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
534             } elseif ($this->oContext->bViewboxBounded) {
535                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
536             }
537             if ($this->oContext->sqlCountryList) {
538                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
539             }
540             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
541             if ($this->oContext->sqlViewboxCentre) {
542                 $sSQL .= ' ORDER BY ST_Distance(';
543                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
544             } elseif ($this->oContext->hasNearPoint()) {
545                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
546             }
547             $sSQL .= " LIMIT $iLimit";
548             Debug::printSQL($sSQL);
549             $aDBResults = $oDB->getCol($sSQL);
550         }
551
552         if ($this->oContext->hasNearPoint()) {
553             $sSQL = 'SELECT place_id FROM placex WHERE ';
554             $sSQL .= 'class = :class and type = :type';
555             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
556             $sSQL .= ' AND linked_place_id is null';
557             if ($this->oContext->sqlCountryList) {
558                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
559             }
560             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
561             $sSQL .= " LIMIT $iLimit";
562             Debug::printSQL($sSQL);
563             $aDBResults = $oDB->getCol(
564                 $sSQL,
565                 array(':class' => $this->sClass, ':type' => $this->sType)
566             );
567         }
568
569         $aResults = array();
570         foreach ($aDBResults as $iPlaceId) {
571             $aResults[$iPlaceId] = new Result($iPlaceId);
572         }
573
574         return $aResults;
575     }
576
577     private function queryPostcode(&$oDB, $iLimit)
578     {
579         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
580
581         if (!empty($this->aAddress)) {
582             $sSQL .= ', search_name s ';
583             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
584             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
585             $sSQL .= '      @> '.$oDB->getArraySQL($this->aAddress).' AND ';
586         } else {
587             $sSQL .= 'WHERE ';
588         }
589
590         $sSQL .= "p.postcode = '".reset($this->aName)."'";
591         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
592         if ($this->oContext->bViewboxBounded) {
593             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
594         }
595         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
596         $sSQL .= " LIMIT $iLimit";
597
598         Debug::printSQL($sSQL);
599
600         $aResults = array();
601         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
602             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
603         }
604
605         return $aResults;
606     }
607
608     private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
609     {
610         $aTerms = array();
611         $aOrder = array();
612
613         // Sort by existence of the requested house number but only if not
614         // too many results are expected for the street, i.e. if the result
615         // will be narrowed down by an address. Remeber that with ordering
616         // every single result has to be checked.
617         if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
618             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
619             $aOrder[] = ' (';
620             $aOrder[0] .= 'EXISTS(';
621             $aOrder[0] .= '  SELECT place_id';
622             $aOrder[0] .= '  FROM placex';
623             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
624             $aOrder[0] .= "    AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
625             $aOrder[0] .= '  LIMIT 1';
626             $aOrder[0] .= ') ';
627             // also housenumbers from interpolation lines table are needed
628             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
629                 $iHouseNumber = intval($this->sHouseNumber);
630                 $aOrder[0] .= 'OR EXISTS(';
631                 $aOrder[0] .= '  SELECT place_id ';
632                 $aOrder[0] .= '  FROM location_property_osmline ';
633                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
634                 $aOrder[0] .= '    AND startnumber is not NULL';
635                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
636                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
637                 $aOrder[0] .= '  LIMIT 1';
638                 $aOrder[0] .= ')';
639             }
640             $aOrder[0] .= ') DESC';
641         }
642
643         if (!empty($this->aName)) {
644             $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
645         }
646         if (!empty($this->aAddress)) {
647             // For infrequent name terms disable index usage for address
648             if ($this->bRareName) {
649                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
650             } else {
651                 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
652             }
653         }
654
655         $sCountryTerm = $this->countryCodeSQL('country_code');
656         if ($sCountryTerm) {
657             $aTerms[] = $sCountryTerm;
658         }
659
660         if ($this->sHouseNumber) {
661             $aTerms[] = 'address_rank between 16 and 30';
662         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
663             if ($iMinAddressRank > 0) {
664                 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
665             }
666         }
667
668         if ($this->oContext->hasNearPoint()) {
669             $aTerms[] = $this->oContext->withinSQL('centroid');
670             $aOrder[] = $this->oContext->distanceSQL('centroid');
671         } elseif ($this->sPostcode) {
672             if (empty($this->aAddress)) {
673                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
674             } else {
675                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
676             }
677         }
678
679         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
680         if ($sExcludeSQL) {
681             $aTerms[] = $sExcludeSQL;
682         }
683
684         if ($this->oContext->bViewboxBounded) {
685             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
686         }
687
688         if ($this->oContext->hasNearPoint()) {
689             $aOrder[] = $this->oContext->distanceSQL('centroid');
690         }
691
692         if ($this->sHouseNumber) {
693             $sImportanceSQL = '- abs(26 - address_rank) + 3';
694         } else {
695             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
696         }
697         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
698         $aOrder[] = "$sImportanceSQL DESC";
699
700         $aFullNameAddress = $this->oContext->getFullNameTerms();
701         if (!empty($aFullNameAddress)) {
702             $sExactMatchSQL = ' ( ';
703             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
704             $sExactMatchSQL .= '  SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
705             $sExactMatchSQL .= '    INTERSECT ';
706             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
707             $sExactMatchSQL .= ' ) s';
708             $sExactMatchSQL .= ') as exactmatch';
709             $aOrder[] = 'exactmatch DESC';
710         } else {
711             $sExactMatchSQL = '0::int as exactmatch';
712         }
713
714         if ($this->sHouseNumber || $this->sClass) {
715             $iLimit = 40;
716         }
717
718         $aResults = array();
719
720         if (!empty($aTerms)) {
721             $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
722             $sSQL .= ' FROM search_name';
723             $sSQL .= ' WHERE '.join(' and ', $aTerms);
724             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
725             $sSQL .= ' LIMIT '.$iLimit;
726
727             Debug::printSQL($sSQL);
728
729             $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
730
731             foreach ($aDBResults as $aResult) {
732                 $oResult = new Result($aResult['place_id']);
733                 $oResult->iExactMatches = $aResult['exactmatch'];
734                 $oResult->iAddressRank = $aResult['address_rank'];
735                 $aResults[$aResult['place_id']] = $oResult;
736             }
737         }
738
739         return $aResults;
740     }
741
742     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
743     {
744         $aResults = array();
745         $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
746
747         if (!$sPlaceIDs) {
748             return $aResults;
749         }
750
751         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
752         $sSQL = 'SELECT place_id FROM placex ';
753         $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
754         $sSQL .= "  AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
755         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
756
757         Debug::printSQL($sSQL);
758
759         // XXX should inherit the exactMatches from its parent
760         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
761             $aResults[$iPlaceId] = new Result($iPlaceId);
762         }
763
764         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
765         $iHousenumber = intval($this->sHouseNumber);
766         if ($bIsIntHouseNumber && empty($aResults)) {
767             // if nothing found, search in the interpolation line table
768             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
769             $sSQL .= ' WHERE startnumber is not NULL';
770             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
771             if ($iHousenumber % 2 == 0) {
772                 // If housenumber is even, look for housenumber in streets
773                 // with interpolationtype even or all.
774                 $sSQL .= "interpolationtype='even'";
775             } else {
776                 // Else look for housenumber with interpolationtype odd or all.
777                 $sSQL .= "interpolationtype='odd'";
778             }
779             $sSQL .= " or interpolationtype='all') and ";
780             $sSQL .= $iHousenumber.'>=startnumber and ';
781             $sSQL .= $iHousenumber.'<=endnumber';
782             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
783
784             Debug::printSQL($sSQL);
785
786             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
787                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
788                 $oResult->iHouseNumber = $iHousenumber;
789                 $aResults[$iPlaceId] = $oResult;
790             }
791         }
792
793         // If nothing found try the aux fallback table
794         if (CONST_Use_Aux_Location_data && empty($aResults)) {
795             $sSQL = 'SELECT place_id FROM location_property_aux';
796             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
797             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
798             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
799
800             Debug::printSQL($sSQL);
801
802             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
803                 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
804             }
805         }
806
807         // If nothing found then search in Tiger data (location_property_tiger)
808         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
809             $sSQL = 'SELECT place_id FROM location_property_tiger';
810             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
811             if ($iHousenumber % 2 == 0) {
812                 $sSQL .= "interpolationtype='even'";
813             } else {
814                 $sSQL .= "interpolationtype='odd'";
815             }
816             $sSQL .= " or interpolationtype='all') and ";
817             $sSQL .= $iHousenumber.'>=startnumber and ';
818             $sSQL .= $iHousenumber.'<=endnumber';
819             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
820
821             Debug::printSQL($sSQL);
822
823             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
824                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
825                 $oResult->iHouseNumber = $iHousenumber;
826                 $aResults[$iPlaceId] = $oResult;
827             }
828         }
829
830         return $aResults;
831     }
832
833
834     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
835     {
836         $aResults = array();
837         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
838
839         if (!$sPlaceIDs) {
840             return $aResults;
841         }
842
843         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
844             // If they were searching for a named class (i.e. 'Kings Head pub')
845             // then we might have an extra match
846             $sSQL = 'SELECT place_id FROM placex ';
847             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
848             $sSQL .= "   AND class='".$this->sClass."' ";
849             $sSQL .= "   AND type='".$this->sType."'";
850             $sSQL .= '   AND linked_place_id is null';
851             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
852             $sSQL .= ' ORDER BY rank_search ASC ';
853             $sSQL .= " LIMIT $iLimit";
854
855             Debug::printSQL($sSQL);
856
857             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
858                 $aResults[$iPlaceId] = new Result($iPlaceId);
859             }
860         }
861
862         // NEAR and IN are handled the same
863         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
864             $sClassTable = $this->poiTable();
865             $bCacheTable = $oDB->tableExists($sClassTable);
866
867             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
868             Debug::printSQL($sSQL);
869             $iMaxRank = (int) $oDB->getOne($sSQL);
870
871             // For state / country level searches the normal radius search doesn't work very well
872             $sPlaceGeom = false;
873             if ($iMaxRank < 9 && $bCacheTable) {
874                 // Try and get a polygon to search in instead
875                 $sSQL = 'SELECT geometry FROM placex';
876                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
877                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
878                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
879                 $sSQL .= ' ORDER BY rank_search ASC ';
880                 $sSQL .= ' LIMIT 1';
881                 Debug::printSQL($sSQL);
882                 $sPlaceGeom = $oDB->getOne($sSQL);
883             }
884
885             if ($sPlaceGeom) {
886                 $sPlaceIDs = false;
887             } else {
888                 $iMaxRank += 5;
889                 $sSQL = 'SELECT place_id FROM placex';
890                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
891                 Debug::printSQL($sSQL);
892                 $aPlaceIDs = $oDB->getCol($sSQL);
893                 $sPlaceIDs = join(',', $aPlaceIDs);
894             }
895
896             if ($sPlaceIDs || $sPlaceGeom) {
897                 $fRange = 0.01;
898                 if ($bCacheTable) {
899                     // More efficient - can make the range bigger
900                     $fRange = 0.05;
901
902                     $sOrderBySQL = '';
903                     if ($this->oContext->hasNearPoint()) {
904                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
905                     } elseif ($sPlaceIDs) {
906                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
907                     } elseif ($sPlaceGeom) {
908                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
909                     }
910
911                     $sSQL = 'SELECT distinct i.place_id';
912                     if ($sOrderBySQL) {
913                         $sSQL .= ', i.order_term';
914                     }
915                     $sSQL .= ' from (SELECT l.place_id';
916                     if ($sOrderBySQL) {
917                         $sSQL .= ','.$sOrderBySQL.' as order_term';
918                     }
919                     $sSQL .= ' from '.$sClassTable.' as l';
920
921                     if ($sPlaceIDs) {
922                         $sSQL .= ',placex as f WHERE ';
923                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
924                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
925                     } elseif ($sPlaceGeom) {
926                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
927                     }
928
929                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
930                     $sSQL .= 'limit 300) i ';
931                     if ($sOrderBySQL) {
932                         $sSQL .= 'order by order_term asc';
933                     }
934                     $sSQL .= " limit $iLimit";
935
936                     Debug::printSQL($sSQL);
937
938                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
939                         $aResults[$iPlaceId] = new Result($iPlaceId);
940                     }
941                 } else {
942                     if ($this->oContext->hasNearPoint()) {
943                         $fRange = $this->oContext->nearRadius();
944                     }
945
946                     $sOrderBySQL = '';
947                     if ($this->oContext->hasNearPoint()) {
948                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
949                     } else {
950                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
951                     }
952
953                     $sSQL = 'SELECT distinct l.place_id';
954                     if ($sOrderBySQL) {
955                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
956                     }
957                     $sSQL .= ' FROM placex as l, placex as f';
958                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
959                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
960                     $sSQL .= "  AND l.class='".$this->sClass."'";
961                     $sSQL .= "  AND l.type='".$this->sType."'";
962                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
963                     if ($sOrderBySQL) {
964                         $sSQL .= 'ORDER BY orderterm ASC';
965                     }
966                     $sSQL .= " limit $iLimit";
967
968                     Debug::printSQL($sSQL);
969
970                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
971                         $aResults[$iPlaceId] = new Result($iPlaceId);
972                     }
973                 }
974             }
975         }
976
977         return $aResults;
978     }
979
980     private function poiTable()
981     {
982         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
983     }
984
985     private function countryCodeSQL($sVar)
986     {
987         if ($this->sCountryCode) {
988             return $sVar.' = \''.$this->sCountryCode."'";
989         }
990         if ($this->oContext->sqlCountryList) {
991             return $sVar.' in '.$this->oContext->sqlCountryList;
992         }
993
994         return '';
995     }
996
997     /////////// Sort functions
998
999
1000     public static function bySearchRank($a, $b)
1001     {
1002         if ($a->iSearchRank == $b->iSearchRank) {
1003             return $a->iOperator + strlen($a->sHouseNumber)
1004                      - $b->iOperator - strlen($b->sHouseNumber);
1005         }
1006
1007         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1008     }
1009
1010     //////////// Debugging functions
1011
1012
1013     public function debugInfo()
1014     {
1015         return array(
1016                 'Search rank' => $this->iSearchRank,
1017                 'Country code' => $this->sCountryCode,
1018                 'Name terms' => $this->aName,
1019                 'Name terms (stop words)' => $this->aNameNonSearch,
1020                 'Address terms' => $this->aAddress,
1021                 'Address terms (stop words)' => $this->aAddressNonSearch,
1022                 'Address terms (full words)' => $this->aFullNameAddress ?? '',
1023                 'Special search' => $this->iOperator,
1024                 'Class' => $this->sClass,
1025                 'Type' => $this->sType,
1026                 'House number' => $this->sHouseNumber,
1027                 'Postcode' => $this->sPostcode
1028                );
1029     }
1030
1031     public function dumpAsHtmlTableRow(&$aWordIDs)
1032     {
1033         $kf = function ($k) use (&$aWordIDs) {
1034             return $aWordIDs[$k] ?? '['.$k.']';
1035         };
1036
1037         echo '<tr>';
1038         echo "<td>$this->iSearchRank</td>";
1039         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1040         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1041         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1042         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1043         echo '<td>'.$this->sCountryCode.'</td>';
1044         echo '<td>'.Operator::toString($this->iOperator).'</td>';
1045         echo '<td>'.$this->sClass.'</td>';
1046         echo '<td>'.$this->sType.'</td>';
1047         echo '<td>'.$this->sPostcode.'</td>';
1048         echo '<td>'.$this->sHouseNumber.'</td>';
1049
1050         echo '</tr>';
1051     }
1052 }