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