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