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