]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
edited indices an setup file to grant select for table country_osm_grid
[nominatim.git] / lib / Geocode.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
6 require_once(CONST_BasePath.'/lib/Phrase.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
8 require_once(CONST_BasePath.'/lib/SearchDescription.php');
9 require_once(CONST_BasePath.'/lib/SearchContext.php');
10 require_once(CONST_BasePath.'/lib/TokenList.php');
11
12 class Geocode
13 {
14     protected $oDB;
15
16     protected $oPlaceLookup;
17
18     protected $aLangPrefOrder = array();
19
20     protected $bIncludeAddressDetails = false;
21
22     protected $aExcludePlaceIDs = array();
23     protected $bReverseInPlan = false;
24
25     protected $iLimit = 20;
26     protected $iFinalLimit = 10;
27     protected $iOffset = 0;
28     protected $bFallback = false;
29
30     protected $aCountryCodes = false;
31
32     protected $bBoundedSearch = false;
33     protected $aViewBox = false;
34     protected $aRoutePoints = false;
35     protected $aRouteWidth = false;
36
37     protected $iMaxRank = 20;
38     protected $iMinAddressRank = 0;
39     protected $iMaxAddressRank = 30;
40     protected $aAddressRankList = array();
41
42     protected $sAllowedTypesSQLList = false;
43
44     protected $sQuery = false;
45     protected $aStructuredQuery = false;
46
47     protected $oNormalizer = null;
48
49
50     public function __construct(&$oDB)
51     {
52         $this->oDB =& $oDB;
53         $this->oPlaceLookup = new PlaceLookup($this->oDB);
54         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
55     }
56
57     private function normTerm($sTerm)
58     {
59         if ($this->oNormalizer === null) {
60             return $sTerm;
61         }
62
63         return $this->oNormalizer->transliterate($sTerm);
64     }
65
66     public function setReverseInPlan($bReverse)
67     {
68         $this->bReverseInPlan = $bReverse;
69     }
70
71     public function setLanguagePreference($aLangPref)
72     {
73         $this->aLangPrefOrder = $aLangPref;
74     }
75
76     public function getMoreUrlParams()
77     {
78         if ($this->aStructuredQuery) {
79             $aParams = $this->aStructuredQuery;
80         } else {
81             $aParams = array('q' => $this->sQuery);
82         }
83
84         $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
85
86         if ($this->aExcludePlaceIDs) {
87             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
88         }
89
90         if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
91         if ($this->bBoundedSearch) $aParams['bounded'] = '1';
92
93         if ($this->aCountryCodes) {
94             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
95         }
96
97         if ($this->aViewBox) {
98             $aParams['viewbox'] = join(',', $this->aViewBox);
99         }
100
101         return $aParams;
102     }
103
104     public function setLimit($iLimit = 10)
105     {
106         if ($iLimit > 50) $iLimit = 50;
107         if ($iLimit < 1) $iLimit = 1;
108
109         $this->iFinalLimit = $iLimit;
110         $this->iLimit = $iLimit + min($iLimit, 10);
111     }
112
113     public function setFeatureType($sFeatureType)
114     {
115         switch ($sFeatureType) {
116             case 'country':
117                 $this->setRankRange(4, 4);
118                 break;
119             case 'state':
120                 $this->setRankRange(8, 8);
121                 break;
122             case 'city':
123                 $this->setRankRange(14, 16);
124                 break;
125             case 'settlement':
126                 $this->setRankRange(8, 20);
127                 break;
128         }
129     }
130
131     public function setRankRange($iMin, $iMax)
132     {
133         $this->iMinAddressRank = $iMin;
134         $this->iMaxAddressRank = $iMax;
135     }
136
137     public function setViewbox($aViewbox)
138     {
139         $aBox = array_map('floatval', $aViewbox);
140
141         $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
142         $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
143         $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
144         $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
145
146         if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
147             || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
148         ) {
149             userError("Bad parameter 'viewbox'. Not a box.");
150         }
151     }
152
153     private function viewboxImportanceFactor($fX, $fY)
154     {
155         $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
156         $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
157
158         $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
159         $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
160
161         if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
162             return 1;
163         }
164
165         if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
166             return 0.5;
167         }
168
169         return 0.25;
170     }
171
172     public function setQuery($sQueryString)
173     {
174         $this->sQuery = $sQueryString;
175         $this->aStructuredQuery = false;
176     }
177
178     public function getQueryString()
179     {
180         return $this->sQuery;
181     }
182
183
184     public function loadParamArray($oParams, $sForceGeometryType = null)
185     {
186         $this->bIncludeAddressDetails
187          = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
188
189         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
190
191         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
192         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
193
194         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
195
196         // List of excluded Place IDs - used for more acurate pageing
197         $sExcluded = $oParams->getStringList('exclude_place_ids');
198         if ($sExcluded) {
199             foreach ($sExcluded as $iExcludedPlaceID) {
200                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
201                 if ($iExcludedPlaceID)
202                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
203             }
204
205             if (isset($aExcludePlaceIDs))
206                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
207         }
208
209         // Only certain ranks of feature
210         $sFeatureType = $oParams->getString('featureType');
211         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
212         if ($sFeatureType) $this->setFeatureType($sFeatureType);
213
214         // Country code list
215         $sCountries = $oParams->getStringList('countrycodes');
216         if ($sCountries) {
217             foreach ($sCountries as $sCountryCode) {
218                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
219                     $aCountries[] = strtolower($sCountryCode);
220                 }
221             }
222             if (isset($aCountries))
223                 $this->aCountryCodes = $aCountries;
224         }
225
226         $aViewbox = $oParams->getStringList('viewboxlbrt');
227         if ($aViewbox) {
228             if (count($aViewbox) != 4) {
229                 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
230             }
231             $this->setViewbox($aViewbox);
232         } else {
233             $aViewbox = $oParams->getStringList('viewbox');
234             if ($aViewbox) {
235                 if (count($aViewbox) != 4) {
236                     userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
237                 }
238                 $this->setViewBox($aViewbox);
239             } else {
240                 $aRoute = $oParams->getStringList('route');
241                 $fRouteWidth = $oParams->getFloat('routewidth');
242                 if ($aRoute && $fRouteWidth) {
243                     $this->aRoutePoints = $aRoute;
244                     $this->aRouteWidth = $fRouteWidth;
245                 }
246             }
247         }
248
249         $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
250         $this->oPlaceLookup->setIncludeAddressDetails(false);
251         $this->oPlaceLookup->setIncludePolygonAsPoints($oParams->getBool('polygon'));
252     }
253
254     public function setQueryFromParams($oParams)
255     {
256         // Search query
257         $sQuery = $oParams->getString('q');
258         if (!$sQuery) {
259             $this->setStructuredQuery(
260                 $oParams->getString('amenity'),
261                 $oParams->getString('street'),
262                 $oParams->getString('city'),
263                 $oParams->getString('county'),
264                 $oParams->getString('state'),
265                 $oParams->getString('country'),
266                 $oParams->getString('postalcode')
267             );
268             $this->setReverseInPlan(false);
269         } else {
270             $this->setQuery($sQuery);
271         }
272     }
273
274     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
275     {
276         $sValue = trim($sValue);
277         if (!$sValue) return false;
278         $this->aStructuredQuery[$sKey] = $sValue;
279         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
280             $this->iMinAddressRank = $iNewMinAddressRank;
281             $this->iMaxAddressRank = $iNewMaxAddressRank;
282         }
283         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
284         return true;
285     }
286
287     public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
288     {
289         $this->sQuery = false;
290
291         // Reset
292         $this->iMinAddressRank = 0;
293         $this->iMaxAddressRank = 30;
294         $this->aAddressRankList = array();
295
296         $this->aStructuredQuery = array();
297         $this->sAllowedTypesSQLList = false;
298
299         $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
300         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
301         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
302         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
303         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
304         $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
305         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
306
307         if (!empty($this->aStructuredQuery)) {
308             $this->sQuery = join(', ', $this->aStructuredQuery);
309             if ($this->iMaxAddressRank < 30) {
310                 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
311             }
312         }
313     }
314
315     public function fallbackStructuredQuery()
316     {
317         if (!$this->aStructuredQuery) return false;
318
319         $aParams = $this->aStructuredQuery;
320
321         if (count($aParams) == 1) return false;
322
323         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
324
325         foreach ($aOrderToFallback as $sType) {
326             if (isset($aParams[$sType])) {
327                 unset($aParams[$sType]);
328                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
329                 return true;
330             }
331         }
332
333         return false;
334     }
335
336     public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens, $bIsStructured)
337     {
338         /*
339              Calculate all searches using oValidTokens i.e.
340              'Wodsworth Road, Sheffield' =>
341
342              Phrase Wordset
343              0      0       (wodsworth road)
344              0      1       (wodsworth)(road)
345              1      0       (sheffield)
346
347              Score how good the search is so they can be ordered
348          */
349         foreach ($aPhrases as $iPhrase => $oPhrase) {
350             $aNewPhraseSearches = array();
351             $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
352
353             foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
354                 // Too many permutations - too expensive
355                 if ($iWordSet > 120) break;
356
357                 $aWordsetSearches = $aSearches;
358
359                 // Add all words from this wordset
360                 foreach ($aWordset as $iToken => $sToken) {
361                     //echo "<br><b>$sToken</b>";
362                     $aNewWordsetSearches = array();
363
364                     foreach ($aWordsetSearches as $oCurrentSearch) {
365                         //echo "<i>";
366                         //var_dump($oCurrentSearch);
367                         //echo "</i>";
368
369                         // Tokens with full name matches.
370                         foreach ($oValidTokens->get(' '.$sToken) as $oSearchTerm) {
371                             $aNewSearches = $oCurrentSearch->extendWithFullTerm(
372                                 $oSearchTerm,
373                                 $oValidTokens->contains($sToken)
374                                   && strpos($sToken, ' ') === false,
375                                 $sPhraseType,
376                                 $iToken == 0 && $iPhrase == 0,
377                                 $iPhrase == 0,
378                                 $iToken + 1 == count($aWordset)
379                                   && $iPhrase + 1 == count($aPhrases)
380                             );
381
382                             foreach ($aNewSearches as $oSearch) {
383                                 if ($oSearch->getRank() < $this->iMaxRank) {
384                                     $aNewWordsetSearches[] = $oSearch;
385                                 }
386                             }
387                         }
388                         // Look for partial matches.
389                         // Note that there is no point in adding country terms here
390                         // because country is omitted in the address.
391                         if ($sPhraseType != 'country') {
392                             // Allow searching for a word - but at extra cost
393                             foreach ($oValidTokens->get($sToken) as $oSearchTerm) {
394                                 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
395                                     $sToken,
396                                     $oSearchTerm,
397                                     $bIsStructured,
398                                     $iPhrase,
399                                     $oValidTokens->get(' '.$sToken)
400                                 );
401
402                                 foreach ($aNewSearches as $oSearch) {
403                                     if ($oSearch->getRank() < $this->iMaxRank) {
404                                         $aNewWordsetSearches[] = $oSearch;
405                                     }
406                                 }
407                             }
408                         }
409                     }
410                     // Sort and cut
411                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
412                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
413                 }
414                 //var_Dump('<hr>',count($aWordsetSearches)); exit;
415
416                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
417                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
418
419                 $aSearchHash = array();
420                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
421                     $sHash = serialize($aSearch);
422                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
423                     else $aSearchHash[$sHash] = 1;
424                 }
425
426                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
427             }
428
429             // Re-group the searches by their score, junk anything over 20 as just not worth trying
430             $aGroupedSearches = array();
431             foreach ($aNewPhraseSearches as $aSearch) {
432                 $iRank = $aSearch->getRank();
433                 if ($iRank < $this->iMaxRank) {
434                     if (!isset($aGroupedSearches[$iRank])) {
435                         $aGroupedSearches[$iRank] = array();
436                     }
437                     $aGroupedSearches[$iRank][] = $aSearch;
438                 }
439             }
440             ksort($aGroupedSearches);
441
442             $iSearchCount = 0;
443             $aSearches = array();
444             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
445                 $iSearchCount += count($aNewSearches);
446                 $aSearches = array_merge($aSearches, $aNewSearches);
447                 if ($iSearchCount > 50) break;
448             }
449         }
450
451         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
452         $aGroupedSearches = array();
453         foreach ($aSearches as $oSearch) {
454             if (!$oSearch->isValidSearch()) {
455                 continue;
456             }
457
458             $iRank = $oSearch->getRank();
459             if (!isset($aGroupedSearches[$iRank])) {
460                 $aGroupedSearches[$iRank] = array();
461             }
462             $aGroupedSearches[$iRank][] = $oSearch;
463         }
464         ksort($aGroupedSearches);
465
466         return $aGroupedSearches;
467     }
468
469     /* Perform the actual query lookup.
470
471         Returns an ordered list of results, each with the following fields:
472             osm_type: type of corresponding OSM object
473                         N - node
474                         W - way
475                         R - relation
476                         P - postcode (internally computed)
477             osm_id: id of corresponding OSM object
478             class: general object class (corresponds to tag key of primary OSM tag)
479             type: subclass of object (corresponds to tag value of primary OSM tag)
480             admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
481             rank_search: rank in search hierarchy
482                         (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
483             rank_address: rank in address hierarchy (determines orer in address)
484             place_id: internal key (may differ between different instances)
485             country_code: ISO country code
486             langaddress: localized full address
487             placename: localized name of object
488             ref: content of ref tag (if available)
489             lon: longitude
490             lat: latitude
491             importance: importance of place based on Wikipedia link count
492             addressimportance: cumulated importance of address elements
493             extra_place: type of place (for admin boundaries, if there is a place tag)
494             aBoundingBox: bounding Box
495             label: short description of the object class/type (English only)
496             name: full name (currently the same as langaddress)
497             foundorder: secondary ordering for places with same importance
498     */
499
500
501     public function lookup()
502     {
503         Debug::newFunction('Geocode::lookup');
504         if (!$this->sQuery && !$this->aStructuredQuery) return array();
505
506         Debug::printDebugArray('Geocode', $this);
507
508         $oCtx = new SearchContext();
509
510         if ($this->aRoutePoints) {
511             $oCtx->setViewboxFromRoute(
512                 $this->oDB,
513                 $this->aRoutePoints,
514                 $this->aRouteWidth,
515                 $this->bBoundedSearch
516             );
517         } elseif ($this->aViewBox) {
518             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
519         }
520         if ($this->aExcludePlaceIDs) {
521             $oCtx->setExcludeList($this->aExcludePlaceIDs);
522         }
523         if ($this->aCountryCodes) {
524             $oCtx->setCountryList($this->aCountryCodes);
525         }
526
527         Debug::newSection('Query Preprocessing');
528
529         $sNormQuery = $this->normTerm($this->sQuery);
530         Debug::printVar('Normalized query', $sNormQuery);
531
532         $sLanguagePrefArraySQL = getArraySQL(
533             array_map('getDBQuoted', $this->aLangPrefOrder)
534         );
535
536         $sQuery = $this->sQuery;
537         if (!preg_match('//u', $sQuery)) {
538             userError('Query string is not UTF-8 encoded.');
539         }
540
541         // Conflicts between US state abreviations and various words for 'the' in different languages
542         if (isset($this->aLangPrefOrder['name:en'])) {
543             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
544             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
545             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
546         }
547
548         // Do we have anything that looks like a lat/lon pair?
549         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
550
551         $aResults = array();
552         if ($sQuery || $this->aStructuredQuery) {
553             // Start with a single blank search
554             $aSearches = array(new SearchDescription($oCtx));
555
556             if ($sQuery) {
557                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
558             }
559
560             $sSpecialTerm = '';
561             if ($sQuery) {
562                 preg_match_all(
563                     '/\\[([\\w ]*)\\]/u',
564                     $sQuery,
565                     $aSpecialTermsRaw,
566                     PREG_SET_ORDER
567                 );
568                 if (!empty($aSpecialTermsRaw)) {
569                     Debug::printVar('Special terms', $aSpecialTermsRaw);
570                 }
571
572                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
573                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
574                     if (!$sSpecialTerm) {
575                         $sSpecialTerm = $aSpecialTerm[1];
576                     }
577                 }
578             }
579             if (!$sSpecialTerm && $this->aStructuredQuery
580                 && isset($this->aStructuredQuery['amenity'])) {
581                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
582                 unset($this->aStructuredQuery['amenity']);
583             }
584
585             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
586                 $sSpecialTerm = pg_escape_string($sSpecialTerm);
587                 $sToken = chksql(
588                     $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
589                     'Cannot decode query. Wrong encoding?'
590                 );
591                 $sSQL = 'SELECT class, type FROM word ';
592                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
593                 $sSQL .= '   AND class is not null AND class not in (\'place\')';
594
595                 Debug::printSQL($sSQL);
596                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
597                 $aNewSearches = array();
598                 foreach ($aSearches as $oSearch) {
599                     foreach ($aSearchWords as $aSearchTerm) {
600                         $oNewSearch = clone $oSearch;
601                         $oNewSearch->setPoiSearch(
602                             Operator::TYPE,
603                             $aSearchTerm['class'],
604                             $aSearchTerm['type']
605                         );
606                         $aNewSearches[] = $oNewSearch;
607                     }
608                 }
609                 $aSearches = $aNewSearches;
610             }
611
612             // Split query into phrases
613             // Commas are used to reduce the search space by indicating where phrases split
614             if ($this->aStructuredQuery) {
615                 $aInPhrases = $this->aStructuredQuery;
616                 $bStructuredPhrases = true;
617             } else {
618                 $aInPhrases = explode(',', $sQuery);
619                 $bStructuredPhrases = false;
620             }
621
622             Debug::printDebugArray('Search context', $oCtx);
623             Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
624             Debug::printVar('Final query phrases', $aInPhrases);
625
626             // Convert each phrase to standard form
627             // Create a list of standard words
628             // Get all 'sets' of words
629             // Generate a complete list of all
630             Debug::newSection('Tokenization');
631             $aTokens = array();
632             $aPhrases = array();
633             foreach ($aInPhrases as $iPhrase => $sPhrase) {
634                 $sPhrase = chksql(
635                     $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
636                     'Cannot normalize query string (is it a UTF-8 string?)'
637                 );
638                 if (trim($sPhrase)) {
639                     $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
640                     $oPhrase->addTokens($aTokens);
641                     $aPhrases[] = $oPhrase;
642                 }
643             }
644
645             Debug::printDebugTable('Phrases', $aPhrases);
646             Debug::printVar('Tokens', $aTokens);
647
648             $oValidTokens = new TokenList();
649
650             if (!empty($aTokens)) {
651                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
652                 $sSQL .= ' FROM word ';
653                 $sSQL .= ' WHERE word_token in ('.join(',', array_map('getDBQuoted', $aTokens)).')';
654
655                 Debug::printSQL($sSQL);
656
657                 $oValidTokens->addTokensFromDB(
658                     $this->oDB,
659                     $aTokens,
660                     $this->aCountryCodes,
661                     $sNormQuery,
662                     $this->oNormalizer
663                 );
664
665                 // Try more interpretations for Tokens that could not be matched.
666                 foreach ($aTokens as $sToken) {
667                     if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
668                         if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
669                             // US ZIP+4 codes - merge in the 5-digit ZIP code
670                             $oValidTokens->addToken(
671                                 $sToken,
672                                 new Token\Postcode(null, $aData[1], 'us')
673                             );
674                         } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
675                             // Unknown single word token with a number.
676                             // Assume it is a house number.
677                             $oValidTokens->addToken(
678                                 $sToken,
679                                 new Token\HouseNumber(null, trim($sToken))
680                             );
681                         }
682                     }
683                 }
684
685                 // Any words that have failed completely?
686                 // TODO: suggestions
687
688                 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
689
690                 Debug::newSection('Search candidates');
691
692                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens, $bStructuredPhrases);
693
694                 if ($this->bReverseInPlan) {
695                     // Reverse phrase array and also reverse the order of the wordsets in
696                     // the first and final phrase. Don't bother about phrases in the middle
697                     // because order in the address doesn't matter.
698                     $aPhrases = array_reverse($aPhrases);
699                     $aPhrases[0]->invertWordSets();
700                     if (count($aPhrases) > 1) {
701                         $aPhrases[count($aPhrases)-1]->invertWordSets();
702                     }
703                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens, false);
704
705                     foreach ($aGroupedSearches as $aSearches) {
706                         foreach ($aSearches as $aSearch) {
707                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
708                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
709                             }
710                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
711                         }
712                     }
713
714                     $aGroupedSearches = $aReverseGroupedSearches;
715                     ksort($aGroupedSearches);
716                 }
717             } else {
718                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
719                 $aGroupedSearches = array();
720                 foreach ($aSearches as $aSearch) {
721                     if ($aSearch->getRank() < $this->iMaxRank) {
722                         if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
723                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
724                     }
725                 }
726                 ksort($aGroupedSearches);
727             }
728
729             // Filter out duplicate searches
730             $aSearchHash = array();
731             foreach ($aGroupedSearches as $iGroup => $aSearches) {
732                 foreach ($aSearches as $iSearch => $aSearch) {
733                     $sHash = serialize($aSearch);
734                     if (isset($aSearchHash[$sHash])) {
735                         unset($aGroupedSearches[$iGroup][$iSearch]);
736                         if (empty($aGroupedSearches[$iGroup])) unset($aGroupedSearches[$iGroup]);
737                     } else {
738                         $aSearchHash[$sHash] = 1;
739                     }
740                 }
741             }
742
743             Debug::printGroupedSearch(
744                 $aGroupedSearches,
745                 $oValidTokens->debugTokenByWordIdList()
746             );
747
748             // Start the search process
749             $iGroupLoop = 0;
750             $iQueryLoop = 0;
751             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
752                 $iGroupLoop++;
753                 foreach ($aSearches as $oSearch) {
754                     $iQueryLoop++;
755
756                     Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
757                     Debug::printGroupedSearch(
758                         array($iGroupedRank => array($oSearch)),
759                         $oValidTokens->debugTokenByWordIdList()
760                     );
761
762                     $aResults += $oSearch->query(
763                         $this->oDB,
764                         $this->iMinAddressRank,
765                         $this->iMaxAddressRank,
766                         $this->iLimit
767                     );
768
769                     if ($iQueryLoop > 20) break;
770                 }
771
772                 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
773                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
774                     // reduces the number of place ids, like a filter
775                     // rank_address is 30 for interpolated housenumbers
776                     $aFilterSql = array();
777                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
778                     if ($sPlaceIds) {
779                         $sSQL = 'SELECT place_id FROM placex ';
780                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
781                         $sSQL .= '  AND (';
782                         $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
783                         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
784                             $sSQL .= "     OR (extratags->'place') = 'city'";
785                         }
786                         if ($this->aAddressRankList) {
787                             $sSQL .= '     OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
788                         }
789                         $sSQL .= ')';
790                         $aFilterSql[] = $sSQL;
791                     }
792                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
793                     if ($sPlaceIds) {
794                         $sSQL = ' SELECT place_id FROM location_postcode lp ';
795                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
796                         $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
797                         if ($this->aAddressRankList) {
798                             $sSQL .= '     OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
799                         }
800                         $sSQL .= ') ';
801                         $aFilterSql[] = $sSQL;
802                     }
803
804                     $aFilteredIDs = array();
805                     if ($aFilterSql) {
806                         $sSQL = join(' UNION ', $aFilterSql);
807                         Debug::printSQL($sSQL);
808                         $aFilteredIDs = chksql($this->oDB->getCol($sSQL));
809                     }
810
811                     $tempIDs = array();
812                     foreach ($aResults as $oResult) {
813                         if (($this->iMaxAddressRank == 30 &&
814                              ($oResult->iTable == Result::TABLE_OSMLINE
815                               || $oResult->iTable == Result::TABLE_AUX
816                               || $oResult->iTable == Result::TABLE_TIGER))
817                             || in_array($oResult->iId, $aFilteredIDs)
818                         ) {
819                             $tempIDs[$oResult->iId] = $oResult;
820                         }
821                     }
822                     $aResults = $tempIDs;
823                 }
824
825                 if (!empty($aResults)) break;
826                 if ($iGroupLoop > 4) break;
827                 if ($iQueryLoop > 30) break;
828             }
829         } else {
830             // Just interpret as a reverse geocode
831             $oReverse = new ReverseGeocode($this->oDB);
832             $oReverse->setZoom(18);
833
834             $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
835
836             Debug::printVar('Reverse search', $oLookup);
837
838             if ($oLookup) {
839                 $aResults = array($oLookup->iId => $oLookup);
840             }
841         }
842
843         // No results? Done
844         if (empty($aResults)) {
845             if ($this->bFallback) {
846                 if ($this->fallbackStructuredQuery()) {
847                     return $this->lookup();
848                 }
849             }
850
851             return array();
852         }
853
854         if ($this->aAddressRankList) {
855             $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
856         }
857         $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
858         $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
859         if ($oCtx->hasNearPoint()) {
860             $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
861         }
862
863         $aSearchResults = $this->oPlaceLookup->lookup($aResults);
864
865         $aClassType = getClassTypesWithImportance();
866         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
867         foreach ($aRecheckWords as $i => $sWord) {
868             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
869         }
870
871         Debug::printVar('Recheck words', $aRecheckWords);
872
873         foreach ($aSearchResults as $iIdx => $aResult) {
874             // Default
875             $fDiameter = getResultDiameter($aResult);
876
877             $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
878             if ($aOutlineResult) {
879                 $aResult = array_merge($aResult, $aOutlineResult);
880             }
881
882             if ($aResult['extra_place'] == 'city') {
883                 $aResult['class'] = 'place';
884                 $aResult['type'] = 'city';
885                 $aResult['rank_search'] = 16;
886             }
887
888             // Is there an icon set for this type of result?
889             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
890                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
891             ) {
892                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
893             }
894
895             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
896                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
897             ) {
898                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
899             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
900                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
901             ) {
902                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
903             }
904             // if tag '&addressdetails=1' is set in query
905             if ($this->bIncludeAddressDetails) {
906                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
907                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResults[$aResult['place_id']]->iHouseNumber);
908                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
909                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
910                 }
911             }
912
913             $aResult['name'] = $aResult['langaddress'];
914
915             if ($oCtx->hasNearPoint()) {
916                 $aResult['importance'] = 0.001;
917                 $aResult['foundorder'] = $aResult['addressimportance'];
918             } else {
919                 $aResult['importance'] = max(0.001, $aResult['importance']);
920                 $aResult['importance'] *= $this->viewboxImportanceFactor(
921                     $aResult['lon'],
922                     $aResult['lat']
923                 );
924                 // Adjust importance for the number of exact string matches in the result
925                 $iCountWords = 0;
926                 $sAddress = $aResult['langaddress'];
927                 foreach ($aRecheckWords as $i => $sWord) {
928                     if (stripos($sAddress, $sWord)!==false) {
929                         $iCountWords++;
930                         if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) $iCountWords += 0.1;
931                     }
932                 }
933
934                 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1); // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
935
936                 // secondary ordering (for results with same importance (the smaller the better):
937                 // - approximate importance of address parts
938                 $aResult['foundorder'] = -$aResult['addressimportance']/10;
939                 // - number of exact matches from the query
940                 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
941                 // - importance of the class/type
942                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
943                     && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
944                 ) {
945                     $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
946                 } else {
947                     $aResult['foundorder'] += 0.01;
948                 }
949             }
950             $aSearchResults[$iIdx] = $aResult;
951         }
952         uasort($aSearchResults, 'byImportance');
953         Debug::printVar('Pre-filter results', $aSearchResults);
954
955         $aOSMIDDone = array();
956         $aClassTypeNameDone = array();
957         $aToFilter = $aSearchResults;
958         $aSearchResults = array();
959
960         $bFirst = true;
961         foreach ($aToFilter as $aResult) {
962             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
963             if ($bFirst) {
964                 $fLat = $aResult['lat'];
965                 $fLon = $aResult['lon'];
966                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
967                 $bFirst = false;
968             }
969             if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
970                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
971             ) {
972                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
973                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
974                 $aSearchResults[] = $aResult;
975             }
976
977             // Absolute limit on number of results
978             if (count($aSearchResults) >= $this->iFinalLimit) break;
979         }
980
981         Debug::printVar('Post-filter results', $aSearchResults);
982         return $aSearchResults;
983     } // end lookup()
984
985     public function debugInfo()
986     {
987         return array(
988                 'Query' => $this->sQuery,
989                 'Structured query' => $this->aStructuredQuery,
990                 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
991                 'Include address' => $this->bIncludeAddressDetails,
992                 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
993                 'Try reversed query'=> $this->bReverseInPlan,
994                 'Limit (for searches)' => $this->iLimit,
995                 'Limit (for results)'=> $this->iFinalLimit,
996                 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
997                 'Bounded search' => $this->bBoundedSearch,
998                 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
999                 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
1000                 'Route width' => $this->aRouteWidth,
1001                 'Max rank' => $this->iMaxRank,
1002                 'Min address rank' => $this->iMinAddressRank,
1003                 'Max address rank' => $this->iMaxAddressRank,
1004                 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)
1005                );
1006     }
1007 } // end class