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