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