]> git.openstreetmap.org Git - nominatim.git/blob - lib/SearchDescription.php
Merge pull request #1005 from lonvia/no-limit-for-housenumber-search
[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);
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)
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
735         Debug::printSQL($sSQL);
736
737         // XXX should inherit the exactMatches from its parent
738         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
739             $aResults[$iPlaceId] = new Result($iPlaceId);
740         }
741
742         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
743         $iHousenumber = intval($this->sHouseNumber);
744         if ($bIsIntHouseNumber && empty($aResults)) {
745             // if nothing found, search in the interpolation line table
746             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
747             $sSQL .= ' WHERE startnumber is not NULL';
748             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
749             if ($iHousenumber % 2 == 0) {
750                 // If housenumber is even, look for housenumber in streets
751                 // with interpolationtype even or all.
752                 $sSQL .= "interpolationtype='even'";
753             } else {
754                 // Else look for housenumber with interpolationtype odd or all.
755                 $sSQL .= "interpolationtype='odd'";
756             }
757             $sSQL .= " or interpolationtype='all') and ";
758             $sSQL .= $iHousenumber.'>=startnumber and ';
759             $sSQL .= $iHousenumber.'<=endnumber';
760             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
761
762             Debug::printSQL($sSQL);
763
764             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
765                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
766                 $oResult->iHouseNumber = $iHousenumber;
767                 $aResults[$iPlaceId] = $oResult;
768             }
769         }
770
771         // If nothing found try the aux fallback table
772         if (CONST_Use_Aux_Location_data && empty($aResults)) {
773             $sSQL = 'SELECT place_id FROM location_property_aux';
774             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
775             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
776             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
777
778             Debug::printSQL($sSQL);
779
780             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
781                 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
782             }
783         }
784
785         // If nothing found then search in Tiger data (location_property_tiger)
786         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
787             $sSQL = 'SELECT place_id FROM location_property_tiger';
788             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
789             if ($iHousenumber % 2 == 0) {
790                 $sSQL .= "interpolationtype='even'";
791             } else {
792                 $sSQL .= "interpolationtype='odd'";
793             }
794             $sSQL .= " or interpolationtype='all') and ";
795             $sSQL .= $iHousenumber.'>=startnumber and ';
796             $sSQL .= $iHousenumber.'<=endnumber';
797             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
798
799             Debug::printSQL($sSQL);
800
801             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
802                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
803                 $oResult->iHouseNumber = $iHousenumber;
804                 $aResults[$iPlaceId] = $oResult;
805             }
806         }
807
808         return $aResults;
809     }
810
811
812     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
813     {
814         $aResults = array();
815         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
816
817         if (!$sPlaceIDs) {
818             return $aResults;
819         }
820
821         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
822             // If they were searching for a named class (i.e. 'Kings Head pub')
823             // then we might have an extra match
824             $sSQL = 'SELECT place_id FROM placex ';
825             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
826             $sSQL .= "   AND class='".$this->sClass."' ";
827             $sSQL .= "   AND type='".$this->sType."'";
828             $sSQL .= '   AND linked_place_id is null';
829             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
830             $sSQL .= ' ORDER BY rank_search ASC ';
831             $sSQL .= " LIMIT $iLimit";
832
833             Debug::printSQL($sSQL);
834
835             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
836                 $aResults[$iPlaceId] = new Result($iPlaceId);
837             }
838         }
839
840         // NEAR and IN are handled the same
841         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
842             $sClassTable = $this->poiTable();
843             $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
844             $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
845
846             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
847             Debug::printSQL($sSQL);
848             $iMaxRank = (int)chksql($oDB->getOne($sSQL));
849
850             // For state / country level searches the normal radius search doesn't work very well
851             $sPlaceGeom = false;
852             if ($iMaxRank < 9 && $bCacheTable) {
853                 // Try and get a polygon to search in instead
854                 $sSQL = 'SELECT geometry FROM placex';
855                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
856                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
857                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
858                 $sSQL .= ' ORDER BY rank_search ASC ';
859                 $sSQL .= ' LIMIT 1';
860                 Debug::printSQL($sSQL);
861                 $sPlaceGeom = chksql($oDB->getOne($sSQL));
862             }
863
864             if ($sPlaceGeom) {
865                 $sPlaceIDs = false;
866             } else {
867                 $iMaxRank += 5;
868                 $sSQL = 'SELECT place_id FROM placex';
869                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
870                 Debug::printSQL($sSQL);
871                 $aPlaceIDs = chksql($oDB->getCol($sSQL));
872                 $sPlaceIDs = join(',', $aPlaceIDs);
873             }
874
875             if ($sPlaceIDs || $sPlaceGeom) {
876                 $fRange = 0.01;
877                 if ($bCacheTable) {
878                     // More efficient - can make the range bigger
879                     $fRange = 0.05;
880
881                     $sOrderBySQL = '';
882                     if ($this->oContext->hasNearPoint()) {
883                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
884                     } elseif ($sPlaceIDs) {
885                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
886                     } elseif ($sPlaceGeom) {
887                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
888                     }
889
890                     $sSQL = 'SELECT distinct i.place_id';
891                     if ($sOrderBySQL) {
892                         $sSQL .= ', i.order_term';
893                     }
894                     $sSQL .= ' from (SELECT l.place_id';
895                     if ($sOrderBySQL) {
896                         $sSQL .= ','.$sOrderBySQL.' as order_term';
897                     }
898                     $sSQL .= ' from '.$sClassTable.' as l';
899
900                     if ($sPlaceIDs) {
901                         $sSQL .= ',placex as f WHERE ';
902                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
903                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
904                     } elseif ($sPlaceGeom) {
905                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
906                     }
907
908                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
909                     $sSQL .= 'limit 300) i ';
910                     if ($sOrderBySQL) {
911                         $sSQL .= 'order by order_term asc';
912                     }
913                     $sSQL .= " limit $iLimit";
914
915                     Debug::printSQL($sSQL);
916
917                     foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
918                         $aResults[$iPlaceId] = new Result($iPlaceId);
919                     }
920                 } else {
921                     if ($this->oContext->hasNearPoint()) {
922                         $fRange = $this->oContext->nearRadius();
923                     }
924
925                     $sOrderBySQL = '';
926                     if ($this->oContext->hasNearPoint()) {
927                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
928                     } else {
929                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
930                     }
931
932                     $sSQL = 'SELECT distinct l.place_id';
933                     if ($sOrderBySQL) {
934                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
935                     }
936                     $sSQL .= ' FROM placex as l, placex as f';
937                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
938                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
939                     $sSQL .= "  AND l.class='".$this->sClass."'";
940                     $sSQL .= "  AND l.type='".$this->sType."'";
941                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
942                     if ($sOrderBySQL) {
943                         $sSQL .= 'ORDER BY orderterm ASC';
944                     }
945                     $sSQL .= " limit $iLimit";
946
947                     Debug::printSQL($sSQL);
948
949                     foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
950                         $aResults[$iPlaceId] = new Result($iPlaceId);
951                     }
952                 }
953             }
954         }
955
956         return $aResults;
957     }
958
959     private function poiTable()
960     {
961         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
962     }
963
964     private function countryCodeSQL($sVar)
965     {
966         if ($this->sCountryCode) {
967             return $sVar.' = \''.$this->sCountryCode."'";
968         }
969         if ($this->oContext->sqlCountryList) {
970             return $sVar.' in '.$this->oContext->sqlCountryList;
971         }
972
973         return '';
974     }
975
976     /////////// Sort functions
977
978
979     public static function bySearchRank($a, $b)
980     {
981         if ($a->iSearchRank == $b->iSearchRank) {
982             return $a->iOperator + strlen($a->sHouseNumber)
983                      - $b->iOperator - strlen($b->sHouseNumber);
984         }
985
986         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
987     }
988
989     //////////// Debugging functions
990
991
992     public function debugInfo()
993     {
994         return array(
995                 'Search rank' => $this->iSearchRank,
996                 'Country code' => $this->sCountryCode,
997                 'Name terms' => $this->aName,
998                 'Name terms (stop words)' => $this->aNameNonSearch,
999                 'Address terms' => $this->aAddress,
1000                 'Address terms (stop words)' => $this->aAddressNonSearch,
1001                 'Address terms (full words)' => $this->aFullNameAddress,
1002                 'Special search' => $this->iOperator,
1003                 'Class' => $this->sClass,
1004                 'Type' => $this->sType,
1005                 'House number' => $this->sHouseNumber,
1006                 'Postcode' => $this->sPostcode
1007                );
1008     }
1009
1010     public function dumpAsHtmlTableRow(&$aWordIDs)
1011     {
1012         $kf = function ($k) use (&$aWordIDs) {
1013             return $aWordIDs[$k];
1014         };
1015
1016         echo '<tr>';
1017         echo "<td>$this->iSearchRank</td>";
1018         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1019         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1020         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1021         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1022         echo '<td>'.$this->sCountryCode.'</td>';
1023         echo '<td>'.Operator::toString($this->iOperator).'</td>';
1024         echo '<td>'.$this->sClass.'</td>';
1025         echo '<td>'.$this->sType.'</td>';
1026         echo '<td>'.$this->sPostcode.'</td>';
1027         echo '<td>'.$this->sHouseNumber.'</td>';
1028
1029         echo '</tr>';
1030     }
1031 }