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