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