]> git.openstreetmap.org Git - nominatim.git/blob - lib/SearchDescription.php
downgrade housenumbers without numbers
[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      Database connection 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 = chksql($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         $aResults = array();
508         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
509             $aResults[$iPlaceId] = new Result($iPlaceId);
510         }
511
512         return $aResults;
513     }
514
515     private function queryNearbyPoi(&$oDB, $iLimit)
516     {
517         if (!$this->sClass) {
518             return array();
519         }
520
521         $aDBResults = array();
522         $sPoiTable = $this->poiTable();
523
524         $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
525         if (chksql($oDB->getOne($sSQL))) {
526             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
527             if ($this->oContext->sqlCountryList) {
528                 $sSQL .= ' JOIN placex USING (place_id)';
529             }
530             if ($this->oContext->hasNearPoint()) {
531                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
532             } elseif ($this->oContext->bViewboxBounded) {
533                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
534             }
535             if ($this->oContext->sqlCountryList) {
536                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
537             }
538             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
539             if ($this->oContext->sqlViewboxCentre) {
540                 $sSQL .= ' ORDER BY ST_Distance(';
541                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
542             } elseif ($this->oContext->hasNearPoint()) {
543                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
544             }
545             $sSQL .= " limit $iLimit";
546             Debug::printSQL($sSQL);
547             $aDBResults = chksql($oDB->getCol($sSQL));
548         }
549
550         if ($this->oContext->hasNearPoint()) {
551             $sSQL = 'SELECT place_id FROM placex WHERE ';
552             $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
553             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
554             $sSQL .= ' AND linked_place_id is null';
555             if ($this->oContext->sqlCountryList) {
556                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
557             }
558             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
559             $sSQL .= " LIMIT $iLimit";
560             Debug::printSQL($sSQL);
561             $aDBResults = chksql($oDB->getCol($sSQL));
562         }
563
564         $aResults = array();
565         foreach ($aDBResults as $iPlaceId) {
566             $aResults[$iPlaceId] = new Result($iPlaceId);
567         }
568
569         return $aResults;
570     }
571
572     private function queryPostcode(&$oDB, $iLimit)
573     {
574         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
575
576         if (!empty($this->aAddress)) {
577             $sSQL .= ', search_name s ';
578             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
579             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
580             $sSQL .= '      @> '.getArraySQL($this->aAddress).' AND ';
581         } else {
582             $sSQL .= 'WHERE ';
583         }
584
585         $sSQL .= "p.postcode = '".reset($this->aName)."'";
586         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
587         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
588         $sSQL .= " LIMIT $iLimit";
589
590         Debug::printSQL($sSQL);
591
592         $aResults = array();
593         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
594             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
595         }
596
597         return $aResults;
598     }
599
600     private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
601     {
602         $aTerms = array();
603         $aOrder = array();
604
605         // Sort by existence of the requested house number but only if not
606         // too many results are expected for the street, i.e. if the result
607         // will be narrowed down by an address. Remeber that with ordering
608         // every single result has to be checked.
609         if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
610             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
611             $aOrder[] = ' (';
612             $aOrder[0] .= 'EXISTS(';
613             $aOrder[0] .= '  SELECT place_id';
614             $aOrder[0] .= '  FROM placex';
615             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
616             $aOrder[0] .= "    AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
617             $aOrder[0] .= '  LIMIT 1';
618             $aOrder[0] .= ') ';
619             // also housenumbers from interpolation lines table are needed
620             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
621                 $iHouseNumber = intval($this->sHouseNumber);
622                 $aOrder[0] .= 'OR EXISTS(';
623                 $aOrder[0] .= '  SELECT place_id ';
624                 $aOrder[0] .= '  FROM location_property_osmline ';
625                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
626                 $aOrder[0] .= '    AND startnumber is not NULL';
627                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
628                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
629                 $aOrder[0] .= '  LIMIT 1';
630                 $aOrder[0] .= ')';
631             }
632             $aOrder[0] .= ') DESC';
633         }
634
635         if (!empty($this->aName)) {
636             $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
637         }
638         if (!empty($this->aAddress)) {
639             // For infrequent name terms disable index usage for address
640             if ($this->bRareName) {
641                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
642             } else {
643                 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
644             }
645         }
646
647         $sCountryTerm = $this->countryCodeSQL('country_code');
648         if ($sCountryTerm) {
649             $aTerms[] = $sCountryTerm;
650         }
651
652         if ($this->sHouseNumber) {
653             $aTerms[] = 'address_rank between 16 and 27';
654         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
655             if ($iMinAddressRank > 0) {
656                 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
657             }
658             if ($iMaxAddressRank < 30) {
659                 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
660             }
661         }
662
663         if ($this->oContext->hasNearPoint()) {
664             $aTerms[] = $this->oContext->withinSQL('centroid');
665             $aOrder[] = $this->oContext->distanceSQL('centroid');
666         } elseif ($this->sPostcode) {
667             if (empty($this->aAddress)) {
668                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
669             } else {
670                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
671             }
672         }
673
674         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
675         if ($sExcludeSQL) {
676             $aTerms[] = $sExcludeSQL;
677         }
678
679         if ($this->oContext->bViewboxBounded) {
680             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
681         }
682
683         if ($this->oContext->hasNearPoint()) {
684             $aOrder[] = $this->oContext->distanceSQL('centroid');
685         }
686
687         if ($this->sHouseNumber) {
688             $sImportanceSQL = '- abs(26 - address_rank) + 3';
689         } else {
690             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
691         }
692         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
693         $aOrder[] = "$sImportanceSQL DESC";
694
695         if (!empty($this->aFullNameAddress)) {
696             $sExactMatchSQL = ' ( ';
697             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
698             $sExactMatchSQL .= '  SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
699             $sExactMatchSQL .= '    INTERSECT ';
700             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
701             $sExactMatchSQL .= ' ) s';
702             $sExactMatchSQL .= ') as exactmatch';
703             $aOrder[] = 'exactmatch DESC';
704         } else {
705             $sExactMatchSQL = '0::int as exactmatch';
706         }
707
708         if ($this->sHouseNumber || $this->sClass) {
709             $iLimit = 40;
710         }
711
712         $aResults = array();
713
714         if (!empty($aTerms)) {
715             $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
716             $sSQL .= ' FROM search_name';
717             $sSQL .= ' WHERE '.join(' and ', $aTerms);
718             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
719             $sSQL .= ' LIMIT '.$iLimit;
720
721             Debug::printSQL($sSQL);
722
723             $aDBResults = chksql(
724                 $oDB->getAll($sSQL),
725                 'Could not get places for search terms.'
726             );
727
728             foreach ($aDBResults as $aResult) {
729                 $oResult = new Result($aResult['place_id']);
730                 $oResult->iExactMatches = $aResult['exactmatch'];
731                 $aResults[$aResult['place_id']] = $oResult;
732             }
733         }
734
735         return $aResults;
736     }
737
738     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
739     {
740         $aResults = array();
741         $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
742
743         if (!$sPlaceIDs) {
744             return $aResults;
745         }
746
747         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
748         $sSQL = 'SELECT place_id FROM placex ';
749         $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
750         $sSQL .= "  AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
751         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
752
753         Debug::printSQL($sSQL);
754
755         // XXX should inherit the exactMatches from its parent
756         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
757             $aResults[$iPlaceId] = new Result($iPlaceId);
758         }
759
760         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
761         $iHousenumber = intval($this->sHouseNumber);
762         if ($bIsIntHouseNumber && empty($aResults)) {
763             // if nothing found, search in the interpolation line table
764             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
765             $sSQL .= ' WHERE startnumber is not NULL';
766             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
767             if ($iHousenumber % 2 == 0) {
768                 // If housenumber is even, look for housenumber in streets
769                 // with interpolationtype even or all.
770                 $sSQL .= "interpolationtype='even'";
771             } else {
772                 // Else look for housenumber with interpolationtype odd or all.
773                 $sSQL .= "interpolationtype='odd'";
774             }
775             $sSQL .= " or interpolationtype='all') and ";
776             $sSQL .= $iHousenumber.'>=startnumber and ';
777             $sSQL .= $iHousenumber.'<=endnumber';
778             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
779
780             Debug::printSQL($sSQL);
781
782             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
783                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
784                 $oResult->iHouseNumber = $iHousenumber;
785                 $aResults[$iPlaceId] = $oResult;
786             }
787         }
788
789         // If nothing found try the aux fallback table
790         if (CONST_Use_Aux_Location_data && empty($aResults)) {
791             $sSQL = 'SELECT place_id FROM location_property_aux';
792             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
793             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
794             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
795
796             Debug::printSQL($sSQL);
797
798             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
799                 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
800             }
801         }
802
803         // If nothing found then search in Tiger data (location_property_tiger)
804         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
805             $sSQL = 'SELECT place_id FROM location_property_tiger';
806             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
807             if ($iHousenumber % 2 == 0) {
808                 $sSQL .= "interpolationtype='even'";
809             } else {
810                 $sSQL .= "interpolationtype='odd'";
811             }
812             $sSQL .= " or interpolationtype='all') and ";
813             $sSQL .= $iHousenumber.'>=startnumber and ';
814             $sSQL .= $iHousenumber.'<=endnumber';
815             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
816
817             Debug::printSQL($sSQL);
818
819             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
820                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
821                 $oResult->iHouseNumber = $iHousenumber;
822                 $aResults[$iPlaceId] = $oResult;
823             }
824         }
825
826         return $aResults;
827     }
828
829
830     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
831     {
832         $aResults = array();
833         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
834
835         if (!$sPlaceIDs) {
836             return $aResults;
837         }
838
839         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
840             // If they were searching for a named class (i.e. 'Kings Head pub')
841             // then we might have an extra match
842             $sSQL = 'SELECT place_id FROM placex ';
843             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
844             $sSQL .= "   AND class='".$this->sClass."' ";
845             $sSQL .= "   AND type='".$this->sType."'";
846             $sSQL .= '   AND linked_place_id is null';
847             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
848             $sSQL .= ' ORDER BY rank_search ASC ';
849             $sSQL .= " LIMIT $iLimit";
850
851             Debug::printSQL($sSQL);
852
853             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
854                 $aResults[$iPlaceId] = new Result($iPlaceId);
855             }
856         }
857
858         // NEAR and IN are handled the same
859         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
860             $sClassTable = $this->poiTable();
861             $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
862             $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
863
864             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
865             Debug::printSQL($sSQL);
866             $iMaxRank = (int)chksql($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 = chksql($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 = chksql($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 (chksql($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 (chksql($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 }