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