]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/Geocode.php
factor out query position
[nominatim.git] / lib-php / Geocode.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_LibDir.'/PlaceLookup.php');
6 require_once(CONST_LibDir.'/Phrase.php');
7 require_once(CONST_LibDir.'/ReverseGeocode.php');
8 require_once(CONST_LibDir.'/SearchDescription.php');
9 require_once(CONST_LibDir.'/SearchContext.php');
10 require_once(CONST_LibDir.'/SearchPosition.php');
11 require_once(CONST_LibDir.'/TokenList.php');
12 require_once(CONST_TokenizerDir.'/tokenizer.php');
13
14 class Geocode
15 {
16     protected $oDB;
17
18     protected $oPlaceLookup;
19     protected $oTokenizer;
20
21     protected $aLangPrefOrder = array();
22
23     protected $aExcludePlaceIDs = array();
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
48     public function __construct(&$oDB)
49     {
50         $this->oDB =& $oDB;
51         $this->oPlaceLookup = new PlaceLookup($this->oDB);
52         $this->oTokenizer = new \Nominatim\Tokenizer($this->oDB);
53     }
54
55     public function setLanguagePreference($aLangPref)
56     {
57         $this->aLangPrefOrder = $aLangPref;
58     }
59
60     public function getMoreUrlParams()
61     {
62         if ($this->aStructuredQuery) {
63             $aParams = $this->aStructuredQuery;
64         } else {
65             $aParams = array('q' => $this->sQuery);
66         }
67
68         $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
69
70         if ($this->aExcludePlaceIDs) {
71             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
72         }
73
74         if ($this->bBoundedSearch) {
75             $aParams['bounded'] = '1';
76         }
77
78         if ($this->aCountryCodes) {
79             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
80         }
81
82         if ($this->aViewBox) {
83             $aParams['viewbox'] = join(',', $this->aViewBox);
84         }
85
86         return $aParams;
87     }
88
89     public function setLimit($iLimit = 10)
90     {
91         if ($iLimit > 50) {
92             $iLimit = 50;
93         } elseif ($iLimit < 1) {
94             $iLimit = 1;
95         }
96
97         $this->iFinalLimit = $iLimit;
98         $this->iLimit = $iLimit + min($iLimit, 10);
99     }
100
101     public function setFeatureType($sFeatureType)
102     {
103         switch ($sFeatureType) {
104             case 'country':
105                 $this->setRankRange(4, 4);
106                 break;
107             case 'state':
108                 $this->setRankRange(8, 8);
109                 break;
110             case 'city':
111                 $this->setRankRange(14, 16);
112                 break;
113             case 'settlement':
114                 $this->setRankRange(8, 20);
115                 break;
116         }
117     }
118
119     public function setRankRange($iMin, $iMax)
120     {
121         $this->iMinAddressRank = $iMin;
122         $this->iMaxAddressRank = $iMax;
123     }
124
125     public function setViewbox($aViewbox)
126     {
127         $aBox = array_map('floatval', $aViewbox);
128
129         $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
130         $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
131         $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
132         $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
133
134         if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
135             || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
136         ) {
137             userError("Bad parameter 'viewbox'. Not a box.");
138         }
139     }
140
141     private function viewboxImportanceFactor($fX, $fY)
142     {
143         if (!$this->aViewBox) {
144             return 1;
145         }
146
147         $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
148         $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
149
150         $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
151         $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
152
153         if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
154             return 1;
155         }
156
157         if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
158             return 0.5;
159         }
160
161         return 0.25;
162     }
163
164     public function setQuery($sQueryString)
165     {
166         $this->sQuery = $sQueryString;
167         $this->aStructuredQuery = false;
168     }
169
170     public function getQueryString()
171     {
172         return $this->sQuery;
173     }
174
175
176     public function loadParamArray($oParams, $sForceGeometryType = null)
177     {
178         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
179
180         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
181         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
182
183         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
184
185         // List of excluded Place IDs - used for more acurate pageing
186         $sExcluded = $oParams->getStringList('exclude_place_ids');
187         if ($sExcluded) {
188             foreach ($sExcluded as $iExcludedPlaceID) {
189                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
190                 if ($iExcludedPlaceID) {
191                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
192                 }
193             }
194
195             if (isset($aExcludePlaceIDs)) {
196                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
197             }
198         }
199
200         // Only certain ranks of feature
201         $sFeatureType = $oParams->getString('featureType');
202         if (!$sFeatureType) {
203             $sFeatureType = $oParams->getString('featuretype');
204         }
205         if ($sFeatureType) {
206             $this->setFeatureType($sFeatureType);
207         }
208
209         // Country code list
210         $sCountries = $oParams->getStringList('countrycodes');
211         if ($sCountries) {
212             foreach ($sCountries as $sCountryCode) {
213                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
214                     $aCountries[] = strtolower($sCountryCode);
215                 }
216             }
217             if (isset($aCountries)) {
218                 $this->aCountryCodes = $aCountries;
219             }
220         }
221
222         $aViewbox = $oParams->getStringList('viewboxlbrt');
223         if ($aViewbox) {
224             if (count($aViewbox) != 4) {
225                 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
226             }
227             $this->setViewbox($aViewbox);
228         } else {
229             $aViewbox = $oParams->getStringList('viewbox');
230             if ($aViewbox) {
231                 if (count($aViewbox) != 4) {
232                     userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
233                 }
234                 $this->setViewBox($aViewbox);
235             } else {
236                 $aRoute = $oParams->getStringList('route');
237                 $fRouteWidth = $oParams->getFloat('routewidth');
238                 if ($aRoute && $fRouteWidth) {
239                     $this->aRoutePoints = $aRoute;
240                     $this->aRouteWidth = $fRouteWidth;
241                 }
242             }
243         }
244
245         $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
246         $this->oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', false));
247     }
248
249     public function setQueryFromParams($oParams)
250     {
251         // Search query
252         $sQuery = $oParams->getString('q');
253         if (!$sQuery) {
254             $this->setStructuredQuery(
255                 $oParams->getString('amenity'),
256                 $oParams->getString('street'),
257                 $oParams->getString('city'),
258                 $oParams->getString('county'),
259                 $oParams->getString('state'),
260                 $oParams->getString('country'),
261                 $oParams->getString('postalcode')
262             );
263         } else {
264             $this->setQuery($sQuery);
265         }
266     }
267
268     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
269     {
270         $sValue = trim($sValue);
271         if (!$sValue) {
272             return false;
273         }
274         $this->aStructuredQuery[$sKey] = $sValue;
275         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
276             $this->iMinAddressRank = $iNewMinAddressRank;
277             $this->iMaxAddressRank = $iNewMaxAddressRank;
278         }
279         if ($aItemListValues) {
280             $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
281         }
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         $aParams = $this->aStructuredQuery;
316
317         if (!$aParams || count($aParams) == 1) {
318             return false;
319         }
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)
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             $oPosition = new SearchPosition(
350                 $oPhrase->getPhraseType(),
351                 $iPhrase,
352                 count($aPhrases)
353             );
354
355             foreach ($oPhrase->getWordSets() as $aWordset) {
356                 $aWordsetSearches = $aSearches;
357
358                 // Add all words from this wordset
359                 foreach ($aWordset as $iToken => $sToken) {
360                     $aNewWordsetSearches = array();
361                     $oPosition->setTokenPosition($iToken, count($aWordset));
362
363                     foreach ($aWordsetSearches as $oCurrentSearch) {
364                         foreach ($oValidTokens->get($sToken) as $oSearchTerm) {
365                             $aNewSearches = $oCurrentSearch->extendWithSearchTerm(
366                                 $sToken,
367                                 $oSearchTerm,
368                                 $oPosition
369                             );
370
371                             foreach ($aNewSearches as $oSearch) {
372                                 if ($oSearch->getRank() < $this->iMaxRank) {
373                                     $aNewWordsetSearches[] = $oSearch;
374                                 }
375                             }
376                         }
377                     }
378                     // Sort and cut
379                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
380                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
381                 }
382
383                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
384                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
385
386                 $aSearchHash = array();
387                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
388                     $sHash = serialize($aSearch);
389                     if (isset($aSearchHash[$sHash])) {
390                         unset($aNewPhraseSearches[$iSearch]);
391                     } else {
392                         $aSearchHash[$sHash] = 1;
393                     }
394                 }
395
396                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
397             }
398
399             // Re-group the searches by their score, junk anything over 20 as just not worth trying
400             $aGroupedSearches = array();
401             foreach ($aNewPhraseSearches as $aSearch) {
402                 $iRank = $aSearch->getRank();
403                 if ($iRank < $this->iMaxRank) {
404                     if (!isset($aGroupedSearches[$iRank])) {
405                         $aGroupedSearches[$iRank] = array();
406                     }
407                     $aGroupedSearches[$iRank][] = $aSearch;
408                 }
409             }
410             ksort($aGroupedSearches);
411
412             $iSearchCount = 0;
413             $aSearches = array();
414             foreach ($aGroupedSearches as $aNewSearches) {
415                 $iSearchCount += count($aNewSearches);
416                 $aSearches = array_merge($aSearches, $aNewSearches);
417                 if ($iSearchCount > 50) {
418                     break;
419                 }
420             }
421         }
422
423         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
424         $aGroupedSearches = array();
425         foreach ($aSearches as $oSearch) {
426             if (!$oSearch->isValidSearch()) {
427                 continue;
428             }
429
430             $iRank = $oSearch->getRank();
431             if (!isset($aGroupedSearches[$iRank])) {
432                 $aGroupedSearches[$iRank] = array();
433             }
434             $aGroupedSearches[$iRank][] = $oSearch;
435         }
436         ksort($aGroupedSearches);
437
438         return $aGroupedSearches;
439     }
440
441     /* Perform the actual query lookup.
442
443         Returns an ordered list of results, each with the following fields:
444             osm_type: type of corresponding OSM object
445                         N - node
446                         W - way
447                         R - relation
448                         P - postcode (internally computed)
449             osm_id: id of corresponding OSM object
450             class: general object class (corresponds to tag key of primary OSM tag)
451             type: subclass of object (corresponds to tag value of primary OSM tag)
452             admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
453             rank_search: rank in search hierarchy
454                         (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
455             rank_address: rank in address hierarchy (determines orer in address)
456             place_id: internal key (may differ between different instances)
457             country_code: ISO country code
458             langaddress: localized full address
459             placename: localized name of object
460             ref: content of ref tag (if available)
461             lon: longitude
462             lat: latitude
463             importance: importance of place based on Wikipedia link count
464             addressimportance: cumulated importance of address elements
465             extra_place: type of place (for admin boundaries, if there is a place tag)
466             aBoundingBox: bounding Box
467             label: short description of the object class/type (English only)
468             name: full name (currently the same as langaddress)
469             foundorder: secondary ordering for places with same importance
470     */
471
472
473     public function lookup()
474     {
475         Debug::newFunction('Geocode::lookup');
476         if (!$this->sQuery && !$this->aStructuredQuery) {
477             return array();
478         }
479
480         Debug::printDebugArray('Geocode', $this);
481
482         $oCtx = new SearchContext();
483
484         if ($this->aRoutePoints) {
485             $oCtx->setViewboxFromRoute(
486                 $this->oDB,
487                 $this->aRoutePoints,
488                 $this->aRouteWidth,
489                 $this->bBoundedSearch
490             );
491         } elseif ($this->aViewBox) {
492             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
493         }
494         if ($this->aExcludePlaceIDs) {
495             $oCtx->setExcludeList($this->aExcludePlaceIDs);
496         }
497         if ($this->aCountryCodes) {
498             $oCtx->setCountryList($this->aCountryCodes);
499         }
500         $this->oTokenizer->setCountryRestriction($this->aCountryCodes);
501
502         Debug::newSection('Query Preprocessing');
503
504         $sQuery = $this->sQuery;
505         if (!preg_match('//u', $sQuery)) {
506             userError('Query string is not UTF-8 encoded.');
507         }
508
509         // Conflicts between US state abreviations and various words for 'the' in different languages
510         if (isset($this->aLangPrefOrder['name:en'])) {
511             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
512             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
513             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
514         }
515
516         // Do we have anything that looks like a lat/lon pair?
517         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
518
519         if ($sQuery || $this->aStructuredQuery) {
520             // Start with a single blank search
521             $aSearches = array(new SearchDescription($oCtx));
522
523             if ($sQuery) {
524                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
525             }
526
527             $sSpecialTerm = '';
528             if ($sQuery) {
529                 preg_match_all(
530                     '/\\[([\\w ]*)\\]/u',
531                     $sQuery,
532                     $aSpecialTermsRaw,
533                     PREG_SET_ORDER
534                 );
535                 if (!empty($aSpecialTermsRaw)) {
536                     Debug::printVar('Special terms', $aSpecialTermsRaw);
537                 }
538
539                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
540                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
541                     if (!$sSpecialTerm) {
542                         $sSpecialTerm = $aSpecialTerm[1];
543                     }
544                 }
545             }
546             if (!$sSpecialTerm && $this->aStructuredQuery
547                 && isset($this->aStructuredQuery['amenity'])) {
548                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
549                 unset($this->aStructuredQuery['amenity']);
550             }
551
552             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
553                 $aTokens = $this->oTokenizer->tokensForSpecialTerm($sSpecialTerm);
554
555                 if (!empty($aTokens)) {
556                     $aNewSearches = array();
557                     foreach ($aSearches as $oSearch) {
558                         foreach ($aTokens as $oToken) {
559                             $oNewSearch = clone $oSearch;
560                             $oNewSearch->setPoiSearch(
561                                 $oToken->iOperator,
562                                 $oToken->sClass,
563                                 $oToken->sType
564                             );
565                             $aNewSearches[] = $oNewSearch;
566                         }
567                     }
568                     $aSearches = $aNewSearches;
569                 }
570             }
571
572             // Split query into phrases
573             // Commas are used to reduce the search space by indicating where phrases split
574             $aPhrases = array();
575             if ($this->aStructuredQuery) {
576                 foreach ($this->aStructuredQuery as $iPhrase => $sPhrase) {
577                     $aPhrases[] = new Phrase($sPhrase, $iPhrase);
578                 }
579             } else {
580                 foreach (explode(',', $sQuery) as $sPhrase) {
581                     $aPhrases[] = new Phrase($sPhrase, '');
582                 }
583             }
584
585             Debug::printDebugArray('Search context', $oCtx);
586             Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
587
588             Debug::newSection('Tokenization');
589             $oValidTokens = $this->oTokenizer->extractTokensFromPhrases($aPhrases);
590
591             if ($oValidTokens->count() > 0) {
592                 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
593
594                 $aPhrases = array_filter($aPhrases, function ($oPhrase) {
595                     return $oPhrase->getWordSets() !== null;
596                 });
597
598                 // Any words that have failed completely?
599                 // TODO: suggestions
600
601                 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
602                 Debug::printDebugTable('Phrases', $aPhrases);
603
604                 Debug::newSection('Search candidates');
605
606                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
607
608                 if (!$this->aStructuredQuery) {
609                     // Reverse phrase array and also reverse the order of the wordsets in
610                     // the first and final phrase. Don't bother about phrases in the middle
611                     // because order in the address doesn't matter.
612                     $aPhrases = array_reverse($aPhrases);
613                     $aPhrases[0]->invertWordSets();
614                     if (count($aPhrases) > 1) {
615                         $aPhrases[count($aPhrases)-1]->invertWordSets();
616                     }
617                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
618
619                     foreach ($aGroupedSearches as $aSearches) {
620                         foreach ($aSearches as $aSearch) {
621                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
622                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
623                             }
624                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
625                         }
626                     }
627
628                     $aGroupedSearches = $aReverseGroupedSearches;
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                 $aResult['importance'] = max(0.001, $aResult['importance']);
847                 $aResult['importance'] *= $this->viewboxImportanceFactor(
848                     $aResult['lon'],
849                     $aResult['lat']
850                 );
851
852                 // secondary ordering (for results with same importance (the smaller the better):
853                 // - approximate importance of address parts
854                 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
855                     $aResult['foundorder'] = -$aResult['addressimportance']/10;
856                 } else {
857                     $aResult['foundorder'] = -$aResult['importance'];
858                 }
859                 // - number of exact matches from the query
860                 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
861                 // - importance of the class/type
862                 $iClassImportance = ClassTypes\getImportance($aResult);
863                 if (isset($iClassImportance)) {
864                     $aResult['foundorder'] += 0.0001 * $iClassImportance;
865                 } else {
866                     $aResult['foundorder'] += 0.01;
867                 }
868                 // - rank
869                 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
870
871                 // Adjust importance for the number of exact string matches in the result
872                 $iCountWords = 0;
873                 $sAddress = $aResult['langaddress'];
874                 foreach ($aRecheckWords as $i => $sWord) {
875                     if (stripos($sAddress, $sWord)!==false) {
876                         $iCountWords++;
877                         if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) {
878                             $iCountWords += 0.1;
879                         }
880                     }
881                 }
882
883                 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
884                 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
885             }
886             $aSearchResults[$iIdx] = $aResult;
887         }
888         uasort($aSearchResults, 'byImportance');
889         Debug::printVar('Pre-filter results', $aSearchResults);
890
891         $aOSMIDDone = array();
892         $aClassTypeNameDone = array();
893         $aToFilter = $aSearchResults;
894         $aSearchResults = array();
895
896         foreach ($aToFilter as $aResult) {
897             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
898             if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
899                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
900             ) {
901                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
902                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
903                 $aSearchResults[] = $aResult;
904             }
905
906             // Absolute limit on number of results
907             if (count($aSearchResults) >= $this->iFinalLimit) {
908                 break;
909             }
910         }
911
912         Debug::printVar('Post-filter results', $aSearchResults);
913         return $aSearchResults;
914     } // end lookup()
915
916     public function debugInfo()
917     {
918         return array(
919                 'Query' => $this->sQuery,
920                 'Structured query' => $this->aStructuredQuery,
921                 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
922                 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
923                 'Limit (for searches)' => $this->iLimit,
924                 'Limit (for results)'=> $this->iFinalLimit,
925                 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
926                 'Bounded search' => $this->bBoundedSearch,
927                 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
928                 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
929                 'Route width' => $this->aRouteWidth,
930                 'Max rank' => $this->iMaxRank,
931                 'Min address rank' => $this->iMinAddressRank,
932                 'Max address rank' => $this->iMaxAddressRank,
933                 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)
934                );
935     }
936 } // end class