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