]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/Geocode.php
factor out check if a token fits current search
[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                             if ($oSearchTerm->isExtendable($oCurrentSearch, $oPosition)) {
366                                 $aNewSearches = $oSearchTerm->extendSearch(
367                                     $oCurrentSearch,
368                                     $oPosition
369                                 );
370
371                                 foreach ($aNewSearches as $oSearch) {
372                                     if ($oSearch->getRank() < $this->iMaxRank) {
373                                         $aNewWordsetSearches[] = $oSearch;
374                                     }
375                                 }
376                             }
377                         }
378                     }
379                     // Sort and cut
380                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
381                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
382                 }
383
384                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
385                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
386
387                 $aSearchHash = array();
388                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
389                     $sHash = serialize($aSearch);
390                     if (isset($aSearchHash[$sHash])) {
391                         unset($aNewPhraseSearches[$iSearch]);
392                     } else {
393                         $aSearchHash[$sHash] = 1;
394                     }
395                 }
396
397                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
398             }
399
400             // Re-group the searches by their score, junk anything over 20 as just not worth trying
401             $aGroupedSearches = array();
402             foreach ($aNewPhraseSearches as $aSearch) {
403                 $iRank = $aSearch->getRank();
404                 if ($iRank < $this->iMaxRank) {
405                     if (!isset($aGroupedSearches[$iRank])) {
406                         $aGroupedSearches[$iRank] = array();
407                     }
408                     $aGroupedSearches[$iRank][] = $aSearch;
409                 }
410             }
411             ksort($aGroupedSearches);
412
413             $iSearchCount = 0;
414             $aSearches = array();
415             foreach ($aGroupedSearches as $aNewSearches) {
416                 $iSearchCount += count($aNewSearches);
417                 $aSearches = array_merge($aSearches, $aNewSearches);
418                 if ($iSearchCount > 50) {
419                     break;
420                 }
421             }
422         }
423
424         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
425         $aGroupedSearches = array();
426         foreach ($aSearches as $oSearch) {
427             if (!$oSearch->isValidSearch()) {
428                 continue;
429             }
430
431             $iRank = $oSearch->getRank();
432             if (!isset($aGroupedSearches[$iRank])) {
433                 $aGroupedSearches[$iRank] = array();
434             }
435             $aGroupedSearches[$iRank][] = $oSearch;
436         }
437         ksort($aGroupedSearches);
438
439         return $aGroupedSearches;
440     }
441
442     /* Perform the actual query lookup.
443
444         Returns an ordered list of results, each with the following fields:
445             osm_type: type of corresponding OSM object
446                         N - node
447                         W - way
448                         R - relation
449                         P - postcode (internally computed)
450             osm_id: id of corresponding OSM object
451             class: general object class (corresponds to tag key of primary OSM tag)
452             type: subclass of object (corresponds to tag value of primary OSM tag)
453             admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
454             rank_search: rank in search hierarchy
455                         (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
456             rank_address: rank in address hierarchy (determines orer in address)
457             place_id: internal key (may differ between different instances)
458             country_code: ISO country code
459             langaddress: localized full address
460             placename: localized name of object
461             ref: content of ref tag (if available)
462             lon: longitude
463             lat: latitude
464             importance: importance of place based on Wikipedia link count
465             addressimportance: cumulated importance of address elements
466             extra_place: type of place (for admin boundaries, if there is a place tag)
467             aBoundingBox: bounding Box
468             label: short description of the object class/type (English only)
469             name: full name (currently the same as langaddress)
470             foundorder: secondary ordering for places with same importance
471     */
472
473
474     public function lookup()
475     {
476         Debug::newFunction('Geocode::lookup');
477         if (!$this->sQuery && !$this->aStructuredQuery) {
478             return array();
479         }
480
481         Debug::printDebugArray('Geocode', $this);
482
483         $oCtx = new SearchContext();
484
485         if ($this->aRoutePoints) {
486             $oCtx->setViewboxFromRoute(
487                 $this->oDB,
488                 $this->aRoutePoints,
489                 $this->aRouteWidth,
490                 $this->bBoundedSearch
491             );
492         } elseif ($this->aViewBox) {
493             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
494         }
495         if ($this->aExcludePlaceIDs) {
496             $oCtx->setExcludeList($this->aExcludePlaceIDs);
497         }
498         if ($this->aCountryCodes) {
499             $oCtx->setCountryList($this->aCountryCodes);
500         }
501         $this->oTokenizer->setCountryRestriction($this->aCountryCodes);
502
503         Debug::newSection('Query Preprocessing');
504
505         $sQuery = $this->sQuery;
506         if (!preg_match('//u', $sQuery)) {
507             userError('Query string is not UTF-8 encoded.');
508         }
509
510         // Conflicts between US state abreviations and various words for 'the' in different languages
511         if (isset($this->aLangPrefOrder['name:en'])) {
512             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
513             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
514             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
515         }
516
517         // Do we have anything that looks like a lat/lon pair?
518         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
519
520         if ($sQuery || $this->aStructuredQuery) {
521             // Start with a single blank search
522             $aSearches = array(new SearchDescription($oCtx));
523
524             if ($sQuery) {
525                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
526             }
527
528             $sSpecialTerm = '';
529             if ($sQuery) {
530                 preg_match_all(
531                     '/\\[([\\w ]*)\\]/u',
532                     $sQuery,
533                     $aSpecialTermsRaw,
534                     PREG_SET_ORDER
535                 );
536                 if (!empty($aSpecialTermsRaw)) {
537                     Debug::printVar('Special terms', $aSpecialTermsRaw);
538                 }
539
540                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
541                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
542                     if (!$sSpecialTerm) {
543                         $sSpecialTerm = $aSpecialTerm[1];
544                     }
545                 }
546             }
547             if (!$sSpecialTerm && $this->aStructuredQuery
548                 && isset($this->aStructuredQuery['amenity'])) {
549                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
550                 unset($this->aStructuredQuery['amenity']);
551             }
552
553             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
554                 $aTokens = $this->oTokenizer->tokensForSpecialTerm($sSpecialTerm);
555
556                 if (!empty($aTokens)) {
557                     $aNewSearches = array();
558                     foreach ($aSearches as $oSearch) {
559                         foreach ($aTokens as $oToken) {
560                             $oNewSearch = clone $oSearch;
561                             $oNewSearch->setPoiSearch(
562                                 $oToken->iOperator,
563                                 $oToken->sClass,
564                                 $oToken->sType
565                             );
566                             $aNewSearches[] = $oNewSearch;
567                         }
568                     }
569                     $aSearches = $aNewSearches;
570                 }
571             }
572
573             // Split query into phrases
574             // Commas are used to reduce the search space by indicating where phrases split
575             $aPhrases = array();
576             if ($this->aStructuredQuery) {
577                 foreach ($this->aStructuredQuery as $iPhrase => $sPhrase) {
578                     $aPhrases[] = new Phrase($sPhrase, $iPhrase);
579                 }
580             } else {
581                 foreach (explode(',', $sQuery) as $sPhrase) {
582                     $aPhrases[] = new Phrase($sPhrase, '');
583                 }
584             }
585
586             Debug::printDebugArray('Search context', $oCtx);
587             Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
588
589             Debug::newSection('Tokenization');
590             $oValidTokens = $this->oTokenizer->extractTokensFromPhrases($aPhrases);
591
592             if ($oValidTokens->count() > 0) {
593                 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
594
595                 $aPhrases = array_filter($aPhrases, function ($oPhrase) {
596                     return $oPhrase->getWordSets() !== null;
597                 });
598
599                 // Any words that have failed completely?
600                 // TODO: suggestions
601
602                 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
603                 Debug::printDebugTable('Phrases', $aPhrases);
604
605                 Debug::newSection('Search candidates');
606
607                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
608
609                 if (!$this->aStructuredQuery) {
610                     // Reverse phrase array and also reverse the order of the wordsets in
611                     // the first and final phrase. Don't bother about phrases in the middle
612                     // because order in the address doesn't matter.
613                     $aPhrases = array_reverse($aPhrases);
614                     $aPhrases[0]->invertWordSets();
615                     if (count($aPhrases) > 1) {
616                         $aPhrases[count($aPhrases)-1]->invertWordSets();
617                     }
618                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
619
620                     foreach ($aGroupedSearches as $aSearches) {
621                         foreach ($aSearches as $aSearch) {
622                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
623                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
624                             }
625                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
626                         }
627                     }
628
629                     $aGroupedSearches = $aReverseGroupedSearches;
630                     ksort($aGroupedSearches);
631                 }
632             } else {
633                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
634                 $aGroupedSearches = array();
635                 foreach ($aSearches as $aSearch) {
636                     if ($aSearch->getRank() < $this->iMaxRank) {
637                         if (!isset($aGroupedSearches[$aSearch->getRank()])) {
638                             $aGroupedSearches[$aSearch->getRank()] = array();
639                         }
640                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
641                     }
642                 }
643                 ksort($aGroupedSearches);
644             }
645
646             // Filter out duplicate searches
647             $aSearchHash = array();
648             foreach ($aGroupedSearches as $iGroup => $aSearches) {
649                 foreach ($aSearches as $iSearch => $aSearch) {
650                     $sHash = serialize($aSearch);
651                     if (isset($aSearchHash[$sHash])) {
652                         unset($aGroupedSearches[$iGroup][$iSearch]);
653                         if (empty($aGroupedSearches[$iGroup])) {
654                             unset($aGroupedSearches[$iGroup]);
655                         }
656                     } else {
657                         $aSearchHash[$sHash] = 1;
658                     }
659                 }
660             }
661
662             Debug::printGroupedSearch(
663                 $aGroupedSearches,
664                 $oValidTokens->debugTokenByWordIdList()
665             );
666
667             // Start the search process
668             $iGroupLoop = 0;
669             $iQueryLoop = 0;
670             $aNextResults = array();
671             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
672                 $iGroupLoop++;
673                 $aResults = $aNextResults;
674                 foreach ($aSearches as $oSearch) {
675                     $iQueryLoop++;
676
677                     Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
678                     Debug::printGroupedSearch(
679                         array($iGroupedRank => array($oSearch)),
680                         $oValidTokens->debugTokenByWordIdList()
681                     );
682
683                     $aNewResults = $oSearch->query(
684                         $this->oDB,
685                         $this->iMinAddressRank,
686                         $this->iMaxAddressRank,
687                         $this->iLimit
688                     );
689
690                     // The same result may appear in different rounds, only
691                     // use the one with minimal rank.
692                     foreach ($aNewResults as $iPlace => $oRes) {
693                         if (!isset($aResults[$iPlace])
694                             || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
695                             $aResults[$iPlace] = $oRes;
696                         }
697                     }
698
699                     if ($iQueryLoop > 20) {
700                         break;
701                     }
702                 }
703
704                 if (!empty($aResults)) {
705                     $aSplitResults = Result::splitResults($aResults);
706                     Debug::printVar('Split results', $aSplitResults);
707                     if ($iGroupLoop <= 4
708                         && reset($aSplitResults['head'])->iResultRank > 0
709                         && $iGroupedRank !== array_key_last($aGroupedSearches)) {
710                         // Haven't found an exact match for the query yet.
711                         // Therefore add result from the next group level.
712                         $aNextResults = $aSplitResults['head'];
713                         foreach ($aNextResults as $oRes) {
714                             $oRes->iResultRank--;
715                         }
716                         foreach ($aSplitResults['tail'] as $oRes) {
717                             $oRes->iResultRank--;
718                             $aNextResults[$oRes->iId] = $oRes;
719                         }
720                         $aResults = array();
721                     } else {
722                         $aResults = $aSplitResults['head'];
723                     }
724                 }
725
726                 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
727                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
728                     // reduces the number of place ids, like a filter
729                     // rank_address is 30 for interpolated housenumbers
730                     $aFilterSql = array();
731                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
732                     if ($sPlaceIds) {
733                         $sSQL = 'SELECT place_id FROM placex ';
734                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
735                         $sSQL .= '  AND (';
736                         $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
737                         $sSQL .= "         OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
738                         if ($this->aAddressRankList) {
739                             $sSQL .= '     OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
740                         }
741                         $sSQL .= ')';
742                         $aFilterSql[] = $sSQL;
743                     }
744                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
745                     if ($sPlaceIds) {
746                         $sSQL = ' SELECT place_id FROM location_postcode lp ';
747                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
748                         $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
749                         if ($this->aAddressRankList) {
750                             $sSQL .= '     OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
751                         }
752                         $sSQL .= ') ';
753                         $aFilterSql[] = $sSQL;
754                     }
755
756                     $aFilteredIDs = array();
757                     if ($aFilterSql) {
758                         $sSQL = join(' UNION ', $aFilterSql);
759                         Debug::printSQL($sSQL);
760                         $aFilteredIDs = $this->oDB->getCol($sSQL);
761                     }
762
763                     $tempIDs = array();
764                     foreach ($aResults as $oResult) {
765                         if (($this->iMaxAddressRank == 30 &&
766                              ($oResult->iTable == Result::TABLE_OSMLINE
767                               || $oResult->iTable == Result::TABLE_TIGER))
768                             || in_array($oResult->iId, $aFilteredIDs)
769                         ) {
770                             $tempIDs[$oResult->iId] = $oResult;
771                         }
772                     }
773                     $aResults = $tempIDs;
774                 }
775
776                 if (!empty($aResults) || $iGroupLoop > 4 || $iQueryLoop > 30) {
777                     break;
778                 }
779             }
780         } else {
781             // Just interpret as a reverse geocode
782             $oReverse = new ReverseGeocode($this->oDB);
783             $oReverse->setZoom(18);
784
785             $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
786
787             Debug::printVar('Reverse search', $oLookup);
788
789             if ($oLookup) {
790                 $aResults = array($oLookup->iId => $oLookup);
791             }
792         }
793
794         // No results? Done
795         if (empty($aResults)) {
796             if ($this->bFallback && $this->fallbackStructuredQuery()) {
797                 return $this->lookup();
798             }
799
800             return array();
801         }
802
803         if ($this->aAddressRankList) {
804             $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
805         }
806         $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
807         $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
808         if ($oCtx->hasNearPoint()) {
809             $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
810         }
811
812         $aSearchResults = $this->oPlaceLookup->lookup($aResults);
813
814         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
815         foreach ($aRecheckWords as $i => $sWord) {
816             if (!preg_match('/[\pL\pN]/', $sWord)) {
817                 unset($aRecheckWords[$i]);
818             }
819         }
820
821         Debug::printVar('Recheck words', $aRecheckWords);
822
823         foreach ($aSearchResults as $iIdx => $aResult) {
824             $fRadius = ClassTypes\getDefRadius($aResult);
825
826             $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fRadius);
827             if ($aOutlineResult) {
828                 $aResult = array_merge($aResult, $aOutlineResult);
829             }
830
831             // Is there an icon set for this type of result?
832             $sIcon = ClassTypes\getIconFile($aResult);
833             if (isset($sIcon)) {
834                 $aResult['icon'] = $sIcon;
835             }
836
837             $sLabel = ClassTypes\getLabel($aResult);
838             if (isset($sLabel)) {
839                 $aResult['label'] = $sLabel;
840             }
841             $aResult['name'] = $aResult['langaddress'];
842
843             if ($oCtx->hasNearPoint()) {
844                 $aResult['importance'] = 0.001;
845                 $aResult['foundorder'] = $aResult['addressimportance'];
846             } else {
847                 $aResult['importance'] = max(0.001, $aResult['importance']);
848                 $aResult['importance'] *= $this->viewboxImportanceFactor(
849                     $aResult['lon'],
850                     $aResult['lat']
851                 );
852
853                 // secondary ordering (for results with same importance (the smaller the better):
854                 // - approximate importance of address parts
855                 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
856                     $aResult['foundorder'] = -$aResult['addressimportance']/10;
857                 } else {
858                     $aResult['foundorder'] = -$aResult['importance'];
859                 }
860                 // - number of exact matches from the query
861                 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
862                 // - importance of the class/type
863                 $iClassImportance = ClassTypes\getImportance($aResult);
864                 if (isset($iClassImportance)) {
865                     $aResult['foundorder'] += 0.0001 * $iClassImportance;
866                 } else {
867                     $aResult['foundorder'] += 0.01;
868                 }
869                 // - rank
870                 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
871
872                 // Adjust importance for the number of exact string matches in the result
873                 $iCountWords = 0;
874                 $sAddress = $aResult['langaddress'];
875                 foreach ($aRecheckWords as $i => $sWord) {
876                     if (stripos($sAddress, $sWord)!==false) {
877                         $iCountWords++;
878                         if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) {
879                             $iCountWords += 0.1;
880                         }
881                     }
882                 }
883
884                 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
885                 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
886             }
887             $aSearchResults[$iIdx] = $aResult;
888         }
889         uasort($aSearchResults, 'byImportance');
890         Debug::printVar('Pre-filter results', $aSearchResults);
891
892         $aOSMIDDone = array();
893         $aClassTypeNameDone = array();
894         $aToFilter = $aSearchResults;
895         $aSearchResults = array();
896
897         foreach ($aToFilter as $aResult) {
898             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
899             if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
900                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
901             ) {
902                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
903                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
904                 $aSearchResults[] = $aResult;
905             }
906
907             // Absolute limit on number of results
908             if (count($aSearchResults) >= $this->iFinalLimit) {
909                 break;
910             }
911         }
912
913         Debug::printVar('Post-filter results', $aSearchResults);
914         return $aSearchResults;
915     } // end lookup()
916
917     public function debugInfo()
918     {
919         return array(
920                 'Query' => $this->sQuery,
921                 'Structured query' => $this->aStructuredQuery,
922                 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
923                 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
924                 'Limit (for searches)' => $this->iLimit,
925                 'Limit (for results)'=> $this->iFinalLimit,
926                 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
927                 'Bounded search' => $this->bBoundedSearch,
928                 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
929                 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
930                 'Route width' => $this->aRouteWidth,
931                 'Max rank' => $this->iMaxRank,
932                 'Min address rank' => $this->iMinAddressRank,
933                 'Max address rank' => $this->iMaxAddressRank,
934                 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)
935                );
936     }
937 } // end class