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