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