]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/Geocode.php
Merge pull request #2256 from lonvia/remove-reverseinplan-option
[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)
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 = $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                                     (bool) $sPhraseType,
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             } else {
604                 $aInPhrases = explode(',', $sQuery);
605             }
606
607             Debug::printDebugArray('Search context', $oCtx);
608             Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
609             Debug::printVar('Final query phrases', $aInPhrases);
610
611             // Convert each phrase to standard form
612             // Create a list of standard words
613             // Get all 'sets' of words
614             // Generate a complete list of all
615             Debug::newSection('Tokenization');
616             $aTokens = array();
617             $aPhrases = array();
618             foreach ($aInPhrases as $iPhrase => $sPhrase) {
619                 $sPhrase = $this->oDB->getOne(
620                     'SELECT make_standard_name(:phrase)',
621                     array(':phrase' => $sPhrase),
622                     'Cannot normalize query string (is it a UTF-8 string?)'
623                 );
624                 if (trim($sPhrase)) {
625                     $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
626                     $oPhrase->addTokens($aTokens);
627                     $aPhrases[] = $oPhrase;
628                 }
629             }
630
631             Debug::printVar('Tokens', $aTokens);
632
633             $oValidTokens = new TokenList();
634
635             if (!empty($aTokens)) {
636                 $oValidTokens->addTokensFromDB(
637                     $this->oDB,
638                     $aTokens,
639                     $this->aCountryCodes,
640                     $sNormQuery,
641                     $this->oNormalizer
642                 );
643
644                 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
645
646                 // Try more interpretations for Tokens that could not be matched.
647                 foreach ($aTokens as $sToken) {
648                     if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
649                         if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
650                             // US ZIP+4 codes - merge in the 5-digit ZIP code
651                             $oValidTokens->addToken(
652                                 $sToken,
653                                 new Token\Postcode(null, $aData[1], 'us')
654                             );
655                         } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
656                             // Unknown single word token with a number.
657                             // Assume it is a house number.
658                             $oValidTokens->addToken(
659                                 $sToken,
660                                 new Token\HouseNumber(null, trim($sToken))
661                             );
662                         }
663                     }
664                 }
665
666                 // Any words that have failed completely?
667                 // TODO: suggestions
668
669                 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
670
671                 foreach ($aPhrases as $oPhrase) {
672                     $oPhrase->computeWordSets($oValidTokens);
673                 }
674                 Debug::printDebugTable('Phrases', $aPhrases);
675
676                 Debug::newSection('Search candidates');
677
678                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
679
680                 if (!$this->aStructuredQuery) {
681                     // Reverse phrase array and also reverse the order of the wordsets in
682                     // the first and final phrase. Don't bother about phrases in the middle
683                     // because order in the address doesn't matter.
684                     $aPhrases = array_reverse($aPhrases);
685                     $aPhrases[0]->invertWordSets();
686                     if (count($aPhrases) > 1) {
687                         $aPhrases[count($aPhrases)-1]->invertWordSets();
688                     }
689                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
690
691                     foreach ($aGroupedSearches as $aSearches) {
692                         foreach ($aSearches as $aSearch) {
693                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
694                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
695                             }
696                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
697                         }
698                     }
699
700                     $aGroupedSearches = $aReverseGroupedSearches;
701                     ksort($aGroupedSearches);
702                 }
703             } else {
704                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
705                 $aGroupedSearches = array();
706                 foreach ($aSearches as $aSearch) {
707                     if ($aSearch->getRank() < $this->iMaxRank) {
708                         if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
709                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
710                     }
711                 }
712                 ksort($aGroupedSearches);
713             }
714
715             // Filter out duplicate searches
716             $aSearchHash = array();
717             foreach ($aGroupedSearches as $iGroup => $aSearches) {
718                 foreach ($aSearches as $iSearch => $aSearch) {
719                     $sHash = serialize($aSearch);
720                     if (isset($aSearchHash[$sHash])) {
721                         unset($aGroupedSearches[$iGroup][$iSearch]);
722                         if (empty($aGroupedSearches[$iGroup])) unset($aGroupedSearches[$iGroup]);
723                     } else {
724                         $aSearchHash[$sHash] = 1;
725                     }
726                 }
727             }
728
729             Debug::printGroupedSearch(
730                 $aGroupedSearches,
731                 $oValidTokens->debugTokenByWordIdList()
732             );
733
734             // Start the search process
735             $iGroupLoop = 0;
736             $iQueryLoop = 0;
737             $aNextResults = array();
738             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
739                 $iGroupLoop++;
740                 $aResults = $aNextResults;
741                 foreach ($aSearches as $oSearch) {
742                     $iQueryLoop++;
743
744                     Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
745                     Debug::printGroupedSearch(
746                         array($iGroupedRank => array($oSearch)),
747                         $oValidTokens->debugTokenByWordIdList()
748                     );
749
750                     $aNewResults = $oSearch->query(
751                         $this->oDB,
752                         $this->iMinAddressRank,
753                         $this->iMaxAddressRank,
754                         $this->iLimit
755                     );
756
757                     // The same result may appear in different rounds, only
758                     // use the one with minimal rank.
759                     foreach ($aNewResults as $iPlace => $oRes) {
760                         if (!isset($aResults[$iPlace])
761                             || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
762                             $aResults[$iPlace] = $oRes;
763                         }
764                     }
765
766                     if ($iQueryLoop > 20) break;
767                 }
768
769                 if (!empty($aResults)) {
770                     $aSplitResults = Result::splitResults($aResults);
771                     Debug::printVar('Split results', $aSplitResults);
772                     if ($iGroupLoop <= 4
773                         && reset($aSplitResults['head'])->iResultRank > 0
774                         && $iGroupedRank !== array_key_last($aGroupedSearches)) {
775                         // Haven't found an exact match for the query yet.
776                         // Therefore add result from the next group level.
777                         $aNextResults = $aSplitResults['head'];
778                         foreach ($aNextResults as $oRes) {
779                             $oRes->iResultRank--;
780                         }
781                         foreach ($aSplitResults['tail'] as $oRes) {
782                             $oRes->iResultRank--;
783                             $aNextResults[$oRes->iId] = $oRes;
784                         }
785                         $aResults = array();
786                     } else {
787                         $aResults = $aSplitResults['head'];
788                     }
789                 }
790
791                 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
792                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
793                     // reduces the number of place ids, like a filter
794                     // rank_address is 30 for interpolated housenumbers
795                     $aFilterSql = array();
796                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
797                     if ($sPlaceIds) {
798                         $sSQL = 'SELECT place_id FROM placex ';
799                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
800                         $sSQL .= '  AND (';
801                         $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
802                         $sSQL .= "         OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
803                         if ($this->aAddressRankList) {
804                             $sSQL .= '     OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
805                         }
806                         $sSQL .= ')';
807                         $aFilterSql[] = $sSQL;
808                     }
809                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
810                     if ($sPlaceIds) {
811                         $sSQL = ' SELECT place_id FROM location_postcode lp ';
812                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
813                         $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
814                         if ($this->aAddressRankList) {
815                             $sSQL .= '     OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
816                         }
817                         $sSQL .= ') ';
818                         $aFilterSql[] = $sSQL;
819                     }
820
821                     $aFilteredIDs = array();
822                     if ($aFilterSql) {
823                         $sSQL = join(' UNION ', $aFilterSql);
824                         Debug::printSQL($sSQL);
825                         $aFilteredIDs = $this->oDB->getCol($sSQL);
826                     }
827
828                     $tempIDs = array();
829                     foreach ($aResults as $oResult) {
830                         if (($this->iMaxAddressRank == 30 &&
831                              ($oResult->iTable == Result::TABLE_OSMLINE
832                               || $oResult->iTable == Result::TABLE_AUX
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