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