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