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