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