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