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