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