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