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