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