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