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