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