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