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