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