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