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