]> git.openstreetmap.org Git - nominatim.git/blob - lib/SearchDescription.php
also give higher penalty to partial name terms
[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      * 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)) {
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                 $oSearch = clone $this;
293                 $oSearch->iSearchRank++;
294                 $oSearch->aName = array($iWordID => $iWordID);
295                 $aNewSearches[] = $oSearch;
296             }
297         }
298
299         return $aNewSearches;
300     }
301
302     /**
303      * Derive new searches by adding a partial term to the existing search.
304      *
305      * @param mixed[] $aSearchTerm        Description of the token.
306      * @param bool    $bStructuredPhrases True if the search is structured.
307      * @param integer $iPhrase            Number of the phrase the token is in.
308      * @param array[] $aFullTokens        List of full term tokens with the
309      *                                    same name.
310      *
311      * @return SearchDescription[] List of derived search descriptions.
312      */
313     public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
314     {
315         // Only allow name terms.
316         if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
317             return array();
318         }
319
320         $aNewSearches = array();
321         $iWordID = $aSearchTerm['word_id'];
322
323         if ((!$bStructuredPhrases || $iPhrase > 0)
324             && sizeof($this->aName)
325             && strpos($aSearchTerm['word_token'], ' ') === false
326         ) {
327             if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
328                 $oSearch = clone $this;
329                 $oSearch->iSearchRank += 2;
330                 $oSearch->aAddress[$iWordID] = $iWordID;
331                 $aNewSearches[] = $oSearch;
332             } else {
333                 $oSearch = clone $this;
334                 $oSearch->iSearchRank++;
335                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
336                 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
337                     $oSearch->iSearchRank += 2;
338                 }
339                 if (sizeof($aFullTokens)) {
340                     $oSearch->iSearchRank++;
341                 }
342                 $aNewSearches[] = $oSearch;
343
344                 // revert to the token version?
345                 foreach ($aFullTokens as $aSearchTermToken) {
346                     if (empty($aSearchTermToken['country_code'])
347                         && empty($aSearchTermToken['lat'])
348                         && empty($aSearchTermToken['class'])
349                     ) {
350                         $oSearch = clone $this;
351                         $oSearch->iSearchRank++;
352                         $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
353                         $aNewSearches[] = $oSearch;
354                     }
355                 }
356             }
357         }
358
359         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
360             && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
361         ) {
362             $oSearch = clone $this;
363             $oSearch->iSearchRank += 2;
364             if (!sizeof($this->aName)) {
365                 $oSearch->iSearchRank += 1;
366             }
367             if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
368                 $oSearch->iSearchRank += 2;
369             }
370             if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
371                 $oSearch->aName[$iWordID] = $iWordID;
372             } else {
373                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
374             }
375             $oSearch->iNamePhrase = $iPhrase;
376             $aNewSearches[] = $oSearch;
377         }
378
379         return $aNewSearches;
380     }
381
382     /////////// Query functions
383
384
385     /**
386      * Query database for places that match this search.
387      *
388      * @param object  $oDB                  Database connection to use.
389      * @param mixed[] $aWordFrequencyScores Number of times tokens appears
390      *                                      overall in a planet database.
391      * @param integer $iMinRank             Minimum address rank to restrict
392      *                                      search to.
393      * @param integer $iMaxRank             Maximum address rank to restrict
394      *                                      search to.
395      * @param integer $iLimit               Maximum number of results.
396      *
397      * @return mixed[] An array with two fields: IDs contains the list of
398      *                 matching place IDs and houseNumber the houseNumber
399      *                 if appicable or -1 if not.
400      */
401     public function query(&$oDB, &$aWordFrequencyScores, $iMinRank, $iMaxRank, $iLimit)
402     {
403         $aResults = array();
404         $iHousenumber = -1;
405
406         if ($this->sCountryCode
407             && !sizeof($this->aName)
408             && !$this->iOperator
409             && !$this->sClass
410             && !$this->oContext->hasNearPoint()
411         ) {
412             // Just looking for a country - look it up
413             if (4 >= $iMinRank && 4 <= $iMaxRank) {
414                 $aResults = $this->queryCountry($oDB);
415             }
416         } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
417             // Neither name nor address? Then we must be
418             // looking for a POI in a geographic area.
419             if ($this->oContext->isBoundedSearch()) {
420                 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
421             }
422         } elseif ($this->iOperator == Operator::POSTCODE) {
423             // looking for postcode
424             $aResults = $this->queryPostcode($oDB, $iLimit);
425         } else {
426             // Ordinary search:
427             // First search for places according to name and address.
428             $aResults = $this->queryNamedPlace(
429                 $oDB,
430                 $aWordFrequencyScores,
431                 $iMinRank,
432                 $iMaxRank,
433                 $iLimit
434             );
435
436             //now search for housenumber, if housenumber provided
437             if ($this->sHouseNumber && sizeof($aResults)) {
438                 $aNamedPlaceIDs = $aResults;
439                 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs, $iLimit);
440
441                 if (!sizeof($aResults) && $this->looksLikeFullAddress()) {
442                     $aResults = $aNamedPlaceIDs;
443                 }
444             }
445
446             // finally get POIs if requested
447             if ($this->sClass && sizeof($aResults)) {
448                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
449             }
450         }
451
452         if (CONST_Debug) {
453             echo '<br><b>Place IDs:</b> ';
454             var_dump(array_keys($aResults));
455         }
456
457         if (sizeof($aResults) && $this->sPostcode) {
458             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
459             if ($sPlaceIds) {
460                 $sSQL = 'SELECT place_id FROM placex';
461                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
462                 $sSQL .= " AND postcode = '".$this->sPostcode."'";
463                 if (CONST_Debug) var_dump($sSQL);
464                 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
465                 if ($aFilteredPlaceIDs) {
466                     $aNewResults = array();
467                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
468                         $aNewResults[$iPlaceId] = $aResults[$iPlaceId];
469                     }
470                     $aResults = $aNewResults;
471                     if (CONST_Debug) {
472                         echo '<br><b>Place IDs after postcode filtering:</b> ';
473                         var_dump(array_keys($aResults));
474                     }
475                 }
476             }
477         }
478
479         return $aResults;
480     }
481
482
483     private function queryCountry(&$oDB)
484     {
485         $sSQL = 'SELECT place_id FROM placex ';
486         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
487         $sSQL .= ' AND rank_search = 4';
488         if ($this->oContext->bViewboxBounded) {
489             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
490         }
491         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
492
493         if (CONST_Debug) var_dump($sSQL);
494
495         $aResults = array();
496         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
497             $aResults[$iPlaceId] = new Result($iPlaceId);
498         }
499
500         return $aResults;
501     }
502
503     private function queryNearbyPoi(&$oDB, $iLimit)
504     {
505         if (!$this->sClass) {
506             return array();
507         }
508
509         $aDBResults = array();
510         $sPoiTable = $this->poiTable();
511
512         $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
513         if (chksql($oDB->getOne($sSQL))) {
514             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
515             if ($this->oContext->sqlCountryList) {
516                 $sSQL .= ' JOIN placex USING (place_id)';
517             }
518             if ($this->oContext->hasNearPoint()) {
519                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
520             } elseif ($this->oContext->bViewboxBounded) {
521                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
522             }
523             if ($this->oContext->sqlCountryList) {
524                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
525             }
526             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
527             if ($this->oContext->sqlViewboxCentre) {
528                 $sSQL .= ' ORDER BY ST_Distance(';
529                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
530             } elseif ($this->oContext->hasNearPoint()) {
531                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
532             }
533             $sSQL .= " limit $iLimit";
534             if (CONST_Debug) var_dump($sSQL);
535             $aDBResults = chksql($oDB->getCol($sSQL));
536         }
537
538         if ($this->oContext->hasNearPoint()) {
539             $sSQL = 'SELECT place_id FROM placex WHERE ';
540             $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
541             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
542             $sSQL .= ' AND linked_place_id is null';
543             if ($this->oContext->sqlCountryList) {
544                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
545             }
546             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
547             $sSQL .= " LIMIT $iLimit";
548             if (CONST_Debug) var_dump($sSQL);
549             $aDBResults = chksql($oDB->getCol($sSQL));
550         }
551
552         $aResults = array();
553         foreach ($aDBResults as $iPlaceId) {
554             $aResults[$iPlaceId] = new Result($iPlaceId);
555         }
556
557         return $aResults;
558     }
559
560     private function queryPostcode(&$oDB, $iLimit)
561     {
562         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
563
564         if (sizeof($this->aAddress)) {
565             $sSQL .= ', search_name s ';
566             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
567             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
568             $sSQL .= '      @> '.getArraySQL($this->aAddress).' AND ';
569         } else {
570             $sSQL .= 'WHERE ';
571         }
572
573         $sSQL .= "p.postcode = '".reset($this->aName)."'";
574         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
575         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
576         $sSQL .= " LIMIT $iLimit";
577
578         if (CONST_Debug) var_dump($sSQL);
579
580         $aResults = array();
581         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
582             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
583         }
584
585         return $aResults;
586     }
587
588     private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
589     {
590         $aTerms = array();
591         $aOrder = array();
592
593         if ($this->sHouseNumber && sizeof($this->aAddress)) {
594             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
595             $aOrder[] = ' (';
596             $aOrder[0] .= 'EXISTS(';
597             $aOrder[0] .= '  SELECT place_id';
598             $aOrder[0] .= '  FROM placex';
599             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
600             $aOrder[0] .= "    AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
601             $aOrder[0] .= '  LIMIT 1';
602             $aOrder[0] .= ') ';
603             // also housenumbers from interpolation lines table are needed
604             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
605                 $iHouseNumber = intval($this->sHouseNumber);
606                 $aOrder[0] .= 'OR EXISTS(';
607                 $aOrder[0] .= '  SELECT place_id ';
608                 $aOrder[0] .= '  FROM location_property_osmline ';
609                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
610                 $aOrder[0] .= '    AND startnumber is not NULL';
611                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
612                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
613                 $aOrder[0] .= '  LIMIT 1';
614                 $aOrder[0] .= ')';
615             }
616             $aOrder[0] .= ') DESC';
617         }
618
619         if (sizeof($this->aName)) {
620             $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
621         }
622         if (sizeof($this->aAddress)) {
623             // For infrequent name terms disable index usage for address
624             if (CONST_Search_NameOnlySearchFrequencyThreshold
625                 && sizeof($this->aName) == 1
626                 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
627                      < CONST_Search_NameOnlySearchFrequencyThreshold
628             ) {
629                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
630             } else {
631                 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
632             }
633         }
634
635         $sCountryTerm = $this->countryCodeSQL('country_code');
636         if ($sCountryTerm) {
637             $aTerms[] = $sCountryTerm;
638         }
639
640         if ($this->sHouseNumber) {
641             $aTerms[] = 'address_rank between 16 and 27';
642         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
643             if ($iMinAddressRank > 0) {
644                 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
645             }
646             if ($iMaxAddressRank < 30) {
647                 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
648             }
649         }
650
651         if ($this->oContext->hasNearPoint()) {
652             $aTerms[] = $this->oContext->withinSQL('centroid');
653             $aOrder[] = $this->oContext->distanceSQL('centroid');
654         } elseif ($this->sPostcode) {
655             if (!sizeof($this->aAddress)) {
656                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
657             } else {
658                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
659             }
660         }
661
662         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
663         if ($sExcludeSQL) {
664             $aTerms[] = $sExcludeSQL;
665         }
666
667         if ($this->oContext->bViewboxBounded) {
668             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
669         }
670
671         if ($this->oContext->hasNearPoint()) {
672             $aOrder[] = $this->oContext->distanceSQL('centroid');
673         }
674
675         if ($this->sHouseNumber) {
676             $sImportanceSQL = '- abs(26 - address_rank) + 3';
677         } else {
678             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
679         }
680         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
681         $aOrder[] = "$sImportanceSQL DESC";
682
683         if (sizeof($this->aFullNameAddress)) {
684             $sExactMatchSQL = ' ( ';
685             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
686             $sExactMatchSQL .= '  SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
687             $sExactMatchSQL .= '    INTERSECT ';
688             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
689             $sExactMatchSQL .= ' ) s';
690             $sExactMatchSQL .= ') as exactmatch';
691             $aOrder[] = 'exactmatch DESC';
692         } else {
693             $sExactMatchSQL = '0::int as exactmatch';
694         }
695
696         if ($this->sHouseNumber || $this->sClass) {
697             $iLimit = 20;
698         }
699
700         $aResults = array();
701
702         if (sizeof($aTerms)) {
703             $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
704             $sSQL .= ' FROM search_name';
705             $sSQL .= ' WHERE '.join(' and ', $aTerms);
706             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
707             $sSQL .= ' LIMIT '.$iLimit;
708
709             if (CONST_Debug) var_dump($sSQL);
710
711             $aDBResults = chksql(
712                 $oDB->getAll($sSQL),
713                 'Could not get places for search terms.'
714             );
715
716             foreach ($aDBResults as $aResult) {
717                 $oResult = new Result($aResult['place_id']);
718                 $oResult->iExactMatches = $aResult['exactmatch'];
719                 $aResults[$aResult['place_id']] = $oResult;
720             }
721         }
722
723         return $aResults;
724     }
725
726     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
727     {
728         $aResults = array();
729         $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
730
731         if (!$sPlaceIDs) {
732             return $aResults;
733         }
734
735         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
736         $sSQL = 'SELECT place_id FROM placex ';
737         $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
738         $sSQL .= "  AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
739         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
740         $sSQL .= " LIMIT $iLimit";
741
742         if (CONST_Debug) var_dump($sSQL);
743
744         // XXX should inherit the exactMatches from its parent
745         foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
746             $aResults[$iPlaceId] = new Result($iPlaceId);
747         }
748
749         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
750         $iHousenumber = intval($this->sHouseNumber);
751         if ($bIsIntHouseNumber && !sizeof($aResults)) {
752             // if nothing found, search in the interpolation line table
753             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
754             $sSQL .= ' WHERE startnumber is not NULL';
755             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
756             if ($iHousenumber % 2 == 0) {
757                 // If housenumber is even, look for housenumber in streets
758                 // with interpolationtype even or all.
759                 $sSQL .= "interpolationtype='even'";
760             } else {
761                 // Else look for housenumber with interpolationtype odd or all.
762                 $sSQL .= "interpolationtype='odd'";
763             }
764             $sSQL .= " or interpolationtype='all') and ";
765             $sSQL .= $iHousenumber.'>=startnumber and ';
766             $sSQL .= $iHousenumber.'<=endnumber';
767             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
768             $sSQL .= " limit $iLimit";
769
770             if (CONST_Debug) var_dump($sSQL);
771
772             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
773                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
774                 $oResult->iHouseNumber = $iHousenumber;
775                 $aResults[$iPlaceId] = $oResult;
776             }
777         }
778
779         // If nothing found try the aux fallback table
780         if (CONST_Use_Aux_Location_data && !sizeof($aResults)) {
781             $sSQL = 'SELECT place_id FROM location_property_aux';
782             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
783             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
784             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
785             $sSQL .= " limit $iLimit";
786
787             if (CONST_Debug) var_dump($sSQL);
788
789             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
790                 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
791             }
792         }
793
794         // If nothing found then search in Tiger data (location_property_tiger)
795         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && !sizeof($aResults)) {
796             $sSQL = 'SELECT place_id FROM location_property_tiger';
797             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
798             if ($iHousenumber % 2 == 0) {
799                 $sSQL .= "interpolationtype='even'";
800             } else {
801                 $sSQL .= "interpolationtype='odd'";
802             }
803             $sSQL .= " or interpolationtype='all') and ";
804             $sSQL .= $iHousenumber.'>=startnumber and ';
805             $sSQL .= $iHousenumber.'<=endnumber';
806             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
807             $sSQL .= " limit $iLimit";
808
809             if (CONST_Debug) var_dump($sSQL);
810
811             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
812                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
813                 $oResult->iHouseNumber = $iHousenumber;
814                 $aResults[$iPlaceId] = $oResult;
815             }
816         }
817
818         return $aResults;
819     }
820
821
822     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
823     {
824         $aResults = array();
825         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
826
827         if (!$sPlaceIDs) {
828             return $aResults;
829         }
830
831         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
832             // If they were searching for a named class (i.e. 'Kings Head pub')
833             // then we might have an extra match
834             $sSQL = 'SELECT place_id FROM placex ';
835             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
836             $sSQL .= "   AND class='".$this->sClass."' ";
837             $sSQL .= "   AND type='".$this->sType."'";
838             $sSQL .= '   AND linked_place_id is null';
839             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
840             $sSQL .= ' ORDER BY rank_search ASC ';
841             $sSQL .= " LIMIT $iLimit";
842
843             if (CONST_Debug) var_dump($sSQL);
844
845             foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
846                 $aResults[$iPlaceId] = new Result($iPlaceId);
847             }
848         }
849
850         // NEAR and IN are handled the same
851         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
852             $sClassTable = $this->poiTable();
853             $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
854             $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
855
856             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
857             if (CONST_Debug) var_dump($sSQL);
858             $iMaxRank = (int)chksql($oDB->getOne($sSQL));
859
860             // For state / country level searches the normal radius search doesn't work very well
861             $sPlaceGeom = false;
862             if ($iMaxRank < 9 && $bCacheTable) {
863                 // Try and get a polygon to search in instead
864                 $sSQL = 'SELECT geometry FROM placex';
865                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
866                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
867                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
868                 $sSQL .= ' ORDER BY rank_search ASC ';
869                 $sSQL .= ' LIMIT 1';
870                 if (CONST_Debug) var_dump($sSQL);
871                 $sPlaceGeom = chksql($oDB->getOne($sSQL));
872             }
873
874             if ($sPlaceGeom) {
875                 $sPlaceIDs = false;
876             } else {
877                 $iMaxRank += 5;
878                 $sSQL = 'SELECT place_id FROM placex';
879                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
880                 if (CONST_Debug) var_dump($sSQL);
881                 $aPlaceIDs = chksql($oDB->getCol($sSQL));
882                 $sPlaceIDs = join(',', $aPlaceIDs);
883             }
884
885             if ($sPlaceIDs || $sPlaceGeom) {
886                 $fRange = 0.01;
887                 if ($bCacheTable) {
888                     // More efficient - can make the range bigger
889                     $fRange = 0.05;
890
891                     $sOrderBySQL = '';
892                     if ($this->oContext->hasNearPoint()) {
893                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
894                     } elseif ($sPlaceIDs) {
895                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
896                     } elseif ($sPlaceGeom) {
897                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
898                     }
899
900                     $sSQL = 'SELECT distinct i.place_id';
901                     if ($sOrderBySQL) {
902                         $sSQL .= ', i.order_term';
903                     }
904                     $sSQL .= ' from (SELECT l.place_id';
905                     if ($sOrderBySQL) {
906                         $sSQL .= ','.$sOrderBySQL.' as order_term';
907                     }
908                     $sSQL .= ' from '.$sClassTable.' as l';
909
910                     if ($sPlaceIDs) {
911                         $sSQL .= ',placex as f WHERE ';
912                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
913                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
914                     } elseif ($sPlaceGeom) {
915                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
916                     }
917
918                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
919                     $sSQL .= 'limit 300) i ';
920                     if ($sOrderBySQL) {
921                         $sSQL .= 'order by order_term asc';
922                     }
923                     $sSQL .= " limit $iLimit";
924
925                     if (CONST_Debug) var_dump($sSQL);
926
927                     foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
928                         $aResults[$iPlaceId] = new Result($iPlaceId);
929                     }
930                 } else {
931                     if ($this->oContext->hasNearPoint()) {
932                         $fRange = $this->oContext->nearRadius();
933                     }
934
935                     $sOrderBySQL = '';
936                     if ($this->oContext->hasNearPoint()) {
937                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
938                     } else {
939                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
940                     }
941
942                     $sSQL = 'SELECT distinct l.place_id';
943                     if ($sOrderBySQL) {
944                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
945                     }
946                     $sSQL .= ' FROM placex as l, placex as f';
947                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
948                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
949                     $sSQL .= "  AND l.class='".$this->sClass."'";
950                     $sSQL .= "  AND l.type='".$this->sType."'";
951                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
952                     if ($sOrderBySQL) {
953                         $sSQL .= 'ORDER BY orderterm ASC';
954                     }
955                     $sSQL .= " limit $iLimit";
956
957                     if (CONST_Debug) var_dump($sSQL);
958
959                     foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
960                         $aResults[$iPlaceId] = new Result($iPlaceId);
961                     }
962                 }
963             }
964         }
965
966         return $aResults;
967     }
968
969     private function poiTable()
970     {
971         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
972     }
973
974     private function countryCodeSQL($sVar)
975     {
976         if ($this->sCountryCode) {
977             return $sVar.' = \''.$this->sCountryCode."'";
978         }
979         if ($this->oContext->sqlCountryList) {
980             return $sVar.' in '.$this->oContext->sqlCountryList;
981         }
982
983         return '';
984     }
985
986     /////////// Sort functions
987
988
989     public static function bySearchRank($a, $b)
990     {
991         if ($a->iSearchRank == $b->iSearchRank) {
992             return $a->iOperator + strlen($a->sHouseNumber)
993                      - $b->iOperator - strlen($b->sHouseNumber);
994         }
995
996         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
997     }
998
999     //////////// Debugging functions
1000
1001
1002     public function dumpAsHtmlTableRow(&$aWordIDs)
1003     {
1004         $kf = function ($k) use (&$aWordIDs) {
1005             return $aWordIDs[$k];
1006         };
1007
1008         echo '<tr>';
1009         echo "<td>$this->iSearchRank</td>";
1010         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1011         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1012         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1013         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1014         echo '<td>'.$this->sCountryCode.'</td>';
1015         echo '<td>'.Operator::toString($this->iOperator).'</td>';
1016         echo '<td>'.$this->sClass.'</td>';
1017         echo '<td>'.$this->sType.'</td>';
1018         echo '<td>'.$this->sPostcode.'</td>';
1019         echo '<td>'.$this->sHouseNumber.'</td>';
1020
1021         echo '</tr>';
1022     }
1023 }