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