5 require_once(CONST_LibDir.'/PlaceLookup.php');
 
   6 require_once(CONST_LibDir.'/Phrase.php');
 
   7 require_once(CONST_LibDir.'/ReverseGeocode.php');
 
   8 require_once(CONST_LibDir.'/SearchDescription.php');
 
   9 require_once(CONST_LibDir.'/SearchContext.php');
 
  10 require_once(CONST_LibDir.'/TokenList.php');
 
  16     protected $oPlaceLookup;
 
  18     protected $aLangPrefOrder = array();
 
  20     protected $aExcludePlaceIDs = array();
 
  22     protected $iLimit = 20;
 
  23     protected $iFinalLimit = 10;
 
  24     protected $iOffset = 0;
 
  25     protected $bFallback = false;
 
  27     protected $aCountryCodes = false;
 
  29     protected $bBoundedSearch = false;
 
  30     protected $aViewBox = false;
 
  31     protected $aRoutePoints = false;
 
  32     protected $aRouteWidth = false;
 
  34     protected $iMaxRank = 20;
 
  35     protected $iMinAddressRank = 0;
 
  36     protected $iMaxAddressRank = 30;
 
  37     protected $aAddressRankList = array();
 
  39     protected $sAllowedTypesSQLList = false;
 
  41     protected $sQuery = false;
 
  42     protected $aStructuredQuery = false;
 
  44     protected $oNormalizer = null;
 
  47     public function __construct(&$oDB)
 
  50         $this->oPlaceLookup = new PlaceLookup($this->oDB);
 
  51         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
 
  54     private function normTerm($sTerm)
 
  56         if ($this->oNormalizer === null) {
 
  60         return $this->oNormalizer->transliterate($sTerm);
 
  63     public function setLanguagePreference($aLangPref)
 
  65         $this->aLangPrefOrder = $aLangPref;
 
  68     public function getMoreUrlParams()
 
  70         if ($this->aStructuredQuery) {
 
  71             $aParams = $this->aStructuredQuery;
 
  73             $aParams = array('q' => $this->sQuery);
 
  76         $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
 
  78         if ($this->aExcludePlaceIDs) {
 
  79             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
 
  82         if ($this->bBoundedSearch) $aParams['bounded'] = '1';
 
  84         if ($this->aCountryCodes) {
 
  85             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
 
  88         if ($this->aViewBox) {
 
  89             $aParams['viewbox'] = join(',', $this->aViewBox);
 
  95     public function setLimit($iLimit = 10)
 
  97         if ($iLimit > 50) $iLimit = 50;
 
  98         if ($iLimit < 1) $iLimit = 1;
 
 100         $this->iFinalLimit = $iLimit;
 
 101         $this->iLimit = $iLimit + min($iLimit, 10);
 
 104     public function setFeatureType($sFeatureType)
 
 106         switch ($sFeatureType) {
 
 108                 $this->setRankRange(4, 4);
 
 111                 $this->setRankRange(8, 8);
 
 114                 $this->setRankRange(14, 16);
 
 117                 $this->setRankRange(8, 20);
 
 122     public function setRankRange($iMin, $iMax)
 
 124         $this->iMinAddressRank = $iMin;
 
 125         $this->iMaxAddressRank = $iMax;
 
 128     public function setViewbox($aViewbox)
 
 130         $aBox = array_map('floatval', $aViewbox);
 
 132         $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
 
 133         $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
 
 134         $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
 
 135         $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
 
 137         if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
 
 138             || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
 
 140             userError("Bad parameter 'viewbox'. Not a box.");
 
 144     private function viewboxImportanceFactor($fX, $fY)
 
 146         if (!$this->aViewBox) {
 
 150         $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
 
 151         $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
 
 153         $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
 
 154         $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
 
 156         if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
 
 160         if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
 
 167     public function setQuery($sQueryString)
 
 169         $this->sQuery = $sQueryString;
 
 170         $this->aStructuredQuery = false;
 
 173     public function getQueryString()
 
 175         return $this->sQuery;
 
 179     public function loadParamArray($oParams, $sForceGeometryType = null)
 
 181         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
 
 183         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
 
 184         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
 
 186         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
 
 188         // List of excluded Place IDs - used for more acurate pageing
 
 189         $sExcluded = $oParams->getStringList('exclude_place_ids');
 
 191             foreach ($sExcluded as $iExcludedPlaceID) {
 
 192                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
 193                 if ($iExcludedPlaceID)
 
 194                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
 197             if (isset($aExcludePlaceIDs))
 
 198                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
 
 201         // Only certain ranks of feature
 
 202         $sFeatureType = $oParams->getString('featureType');
 
 203         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
 
 204         if ($sFeatureType) $this->setFeatureType($sFeatureType);
 
 207         $sCountries = $oParams->getStringList('countrycodes');
 
 209             foreach ($sCountries as $sCountryCode) {
 
 210                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
 
 211                     $aCountries[] = strtolower($sCountryCode);
 
 214             if (isset($aCountries))
 
 215                 $this->aCountryCodes = $aCountries;
 
 218         $aViewbox = $oParams->getStringList('viewboxlbrt');
 
 220             if (count($aViewbox) != 4) {
 
 221                 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
 
 223             $this->setViewbox($aViewbox);
 
 225             $aViewbox = $oParams->getStringList('viewbox');
 
 227                 if (count($aViewbox) != 4) {
 
 228                     userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
 
 230                 $this->setViewBox($aViewbox);
 
 232                 $aRoute = $oParams->getStringList('route');
 
 233                 $fRouteWidth = $oParams->getFloat('routewidth');
 
 234                 if ($aRoute && $fRouteWidth) {
 
 235                     $this->aRoutePoints = $aRoute;
 
 236                     $this->aRouteWidth = $fRouteWidth;
 
 241         $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
 
 242         $this->oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', false));
 
 245     public function setQueryFromParams($oParams)
 
 248         $sQuery = $oParams->getString('q');
 
 250             $this->setStructuredQuery(
 
 251                 $oParams->getString('amenity'),
 
 252                 $oParams->getString('street'),
 
 253                 $oParams->getString('city'),
 
 254                 $oParams->getString('county'),
 
 255                 $oParams->getString('state'),
 
 256                 $oParams->getString('country'),
 
 257                 $oParams->getString('postalcode')
 
 260             $this->setQuery($sQuery);
 
 264     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
 
 266         $sValue = trim($sValue);
 
 267         if (!$sValue) return false;
 
 268         $this->aStructuredQuery[$sKey] = $sValue;
 
 269         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
 
 270             $this->iMinAddressRank = $iNewMinAddressRank;
 
 271             $this->iMaxAddressRank = $iNewMaxAddressRank;
 
 273         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
 
 277     public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
 
 279         $this->sQuery = false;
 
 282         $this->iMinAddressRank = 0;
 
 283         $this->iMaxAddressRank = 30;
 
 284         $this->aAddressRankList = array();
 
 286         $this->aStructuredQuery = array();
 
 287         $this->sAllowedTypesSQLList = false;
 
 289         $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
 
 290         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
 
 291         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
 
 292         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
 
 293         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
 
 294         $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
 
 295         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
 
 297         if (!empty($this->aStructuredQuery)) {
 
 298             $this->sQuery = join(', ', $this->aStructuredQuery);
 
 299             if ($this->iMaxAddressRank < 30) {
 
 300                 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
 
 305     public function fallbackStructuredQuery()
 
 307         if (!$this->aStructuredQuery) return false;
 
 309         $aParams = $this->aStructuredQuery;
 
 311         if (count($aParams) == 1) return false;
 
 313         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
 
 315         foreach ($aOrderToFallback as $sType) {
 
 316             if (isset($aParams[$sType])) {
 
 317                 unset($aParams[$sType]);
 
 318                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
 
 326     public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens)
 
 329              Calculate all searches using oValidTokens i.e.
 
 330              'Wodsworth Road, Sheffield' =>
 
 334              0      1       (wodsworth)(road)
 
 337              Score how good the search is so they can be ordered
 
 339         foreach ($aPhrases as $iPhrase => $oPhrase) {
 
 340             $aNewPhraseSearches = array();
 
 341             $sPhraseType = $oPhrase->getPhraseType();
 
 343             foreach ($oPhrase->getWordSets() as $aWordset) {
 
 344                 $aWordsetSearches = $aSearches;
 
 346                 // Add all words from this wordset
 
 347                 foreach ($aWordset as $iToken => $sToken) {
 
 348                     //echo "<br><b>$sToken</b>";
 
 349                     $aNewWordsetSearches = array();
 
 351                     foreach ($aWordsetSearches as $oCurrentSearch) {
 
 353                         //var_dump($oCurrentSearch);
 
 356                         // Tokens with full name matches.
 
 357                         foreach ($oValidTokens->get(' '.$sToken) as $oSearchTerm) {
 
 358                             $aNewSearches = $oCurrentSearch->extendWithFullTerm(
 
 360                                 $oValidTokens->contains($sToken)
 
 361                                   && strpos($sToken, ' ') === false,
 
 363                                 $iToken == 0 && $iPhrase == 0,
 
 365                                 $iToken + 1 == count($aWordset)
 
 366                                   && $iPhrase + 1 == count($aPhrases)
 
 369                             foreach ($aNewSearches as $oSearch) {
 
 370                                 if ($oSearch->getRank() < $this->iMaxRank) {
 
 371                                     $aNewWordsetSearches[] = $oSearch;
 
 375                         // Look for partial matches.
 
 376                         // Note that there is no point in adding country terms here
 
 377                         // because country is omitted in the address.
 
 378                         if ($sPhraseType != 'country') {
 
 379                             // Allow searching for a word - but at extra cost
 
 380                             foreach ($oValidTokens->get($sToken) as $oSearchTerm) {
 
 381                                 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
 
 386                                     $oValidTokens->get(' '.$sToken)
 
 389                                 foreach ($aNewSearches as $oSearch) {
 
 390                                     if ($oSearch->getRank() < $this->iMaxRank) {
 
 391                                         $aNewWordsetSearches[] = $oSearch;
 
 398                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
 
 399                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 401                 //var_Dump('<hr>',count($aWordsetSearches)); exit;
 
 403                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 404                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
 
 406                 $aSearchHash = array();
 
 407                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
 
 408                     $sHash = serialize($aSearch);
 
 409                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
 
 410                     else $aSearchHash[$sHash] = 1;
 
 413                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 416             // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 417             $aGroupedSearches = array();
 
 418             foreach ($aNewPhraseSearches as $aSearch) {
 
 419                 $iRank = $aSearch->getRank();
 
 420                 if ($iRank < $this->iMaxRank) {
 
 421                     if (!isset($aGroupedSearches[$iRank])) {
 
 422                         $aGroupedSearches[$iRank] = array();
 
 424                     $aGroupedSearches[$iRank][] = $aSearch;
 
 427             ksort($aGroupedSearches);
 
 430             $aSearches = array();
 
 431             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
 
 432                 $iSearchCount += count($aNewSearches);
 
 433                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 434                 if ($iSearchCount > 50) break;
 
 438         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
 
 439         $aGroupedSearches = array();
 
 440         foreach ($aSearches as $oSearch) {
 
 441             if (!$oSearch->isValidSearch()) {
 
 445             $iRank = $oSearch->getRank();
 
 446             if (!isset($aGroupedSearches[$iRank])) {
 
 447                 $aGroupedSearches[$iRank] = array();
 
 449             $aGroupedSearches[$iRank][] = $oSearch;
 
 451         ksort($aGroupedSearches);
 
 453         return $aGroupedSearches;
 
 456     /* Perform the actual query lookup.
 
 458         Returns an ordered list of results, each with the following fields:
 
 459             osm_type: type of corresponding OSM object
 
 463                         P - postcode (internally computed)
 
 464             osm_id: id of corresponding OSM object
 
 465             class: general object class (corresponds to tag key of primary OSM tag)
 
 466             type: subclass of object (corresponds to tag value of primary OSM tag)
 
 467             admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
 
 468             rank_search: rank in search hierarchy
 
 469                         (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
 
 470             rank_address: rank in address hierarchy (determines orer in address)
 
 471             place_id: internal key (may differ between different instances)
 
 472             country_code: ISO country code
 
 473             langaddress: localized full address
 
 474             placename: localized name of object
 
 475             ref: content of ref tag (if available)
 
 478             importance: importance of place based on Wikipedia link count
 
 479             addressimportance: cumulated importance of address elements
 
 480             extra_place: type of place (for admin boundaries, if there is a place tag)
 
 481             aBoundingBox: bounding Box
 
 482             label: short description of the object class/type (English only)
 
 483             name: full name (currently the same as langaddress)
 
 484             foundorder: secondary ordering for places with same importance
 
 488     public function lookup()
 
 490         Debug::newFunction('Geocode::lookup');
 
 491         if (!$this->sQuery && !$this->aStructuredQuery) return array();
 
 493         Debug::printDebugArray('Geocode', $this);
 
 495         $oCtx = new SearchContext();
 
 497         if ($this->aRoutePoints) {
 
 498             $oCtx->setViewboxFromRoute(
 
 502                 $this->bBoundedSearch
 
 504         } elseif ($this->aViewBox) {
 
 505             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
 
 507         if ($this->aExcludePlaceIDs) {
 
 508             $oCtx->setExcludeList($this->aExcludePlaceIDs);
 
 510         if ($this->aCountryCodes) {
 
 511             $oCtx->setCountryList($this->aCountryCodes);
 
 514         Debug::newSection('Query Preprocessing');
 
 516         $sNormQuery = $this->normTerm($this->sQuery);
 
 517         Debug::printVar('Normalized query', $sNormQuery);
 
 519         $sLanguagePrefArraySQL = $this->oDB->getArraySQL(
 
 520             $this->oDB->getDBQuotedList($this->aLangPrefOrder)
 
 523         $sQuery = $this->sQuery;
 
 524         if (!preg_match('//u', $sQuery)) {
 
 525             userError('Query string is not UTF-8 encoded.');
 
 528         // Conflicts between US state abreviations and various words for 'the' in different languages
 
 529         if (isset($this->aLangPrefOrder['name:en'])) {
 
 530             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
 
 531             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
 
 532             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
 
 535         // Do we have anything that looks like a lat/lon pair?
 
 536         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
 
 538         if ($sQuery || $this->aStructuredQuery) {
 
 539             // Start with a single blank search
 
 540             $aSearches = array(new SearchDescription($oCtx));
 
 543                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
 
 549                     '/\\[([\\w ]*)\\]/u',
 
 554                 if (!empty($aSpecialTermsRaw)) {
 
 555                     Debug::printVar('Special terms', $aSpecialTermsRaw);
 
 558                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
 
 559                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 560                     if (!$sSpecialTerm) {
 
 561                         $sSpecialTerm = $aSpecialTerm[1];
 
 565             if (!$sSpecialTerm && $this->aStructuredQuery
 
 566                 && isset($this->aStructuredQuery['amenity'])) {
 
 567                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
 
 568                 unset($this->aStructuredQuery['amenity']);
 
 571             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
 
 572                 $sSpecialTerm = pg_escape_string($sSpecialTerm);
 
 573                 $sToken = $this->oDB->getOne(
 
 574                     'SELECT make_standard_name(:term)',
 
 575                     array(':term' => $sSpecialTerm),
 
 576                     'Cannot decode query. Wrong encoding?'
 
 578                 $sSQL = 'SELECT class, type FROM word ';
 
 579                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
 
 580                 $sSQL .= '   AND class is not null AND class not in (\'place\')';
 
 582                 Debug::printSQL($sSQL);
 
 583                 $aSearchWords = $this->oDB->getAll($sSQL);
 
 584                 $aNewSearches = array();
 
 585                 foreach ($aSearches as $oSearch) {
 
 586                     foreach ($aSearchWords as $aSearchTerm) {
 
 587                         $oNewSearch = clone $oSearch;
 
 588                         $oNewSearch->setPoiSearch(
 
 590                             $aSearchTerm['class'],
 
 593                         $aNewSearches[] = $oNewSearch;
 
 596                 $aSearches = $aNewSearches;
 
 599             // Split query into phrases
 
 600             // Commas are used to reduce the search space by indicating where phrases split
 
 601             if ($this->aStructuredQuery) {
 
 602                 $aInPhrases = $this->aStructuredQuery;
 
 604                 $aInPhrases = explode(',', $sQuery);
 
 607             Debug::printDebugArray('Search context', $oCtx);
 
 608             Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
 
 609             Debug::printVar('Final query phrases', $aInPhrases);
 
 611             // Convert each phrase to standard form
 
 612             // Create a list of standard words
 
 613             // Get all 'sets' of words
 
 614             // Generate a complete list of all
 
 615             Debug::newSection('Tokenization');
 
 618             foreach ($aInPhrases as $iPhrase => $sPhrase) {
 
 619                 $sPhrase = $this->oDB->getOne(
 
 620                     'SELECT make_standard_name(:phrase)',
 
 621                     array(':phrase' => $sPhrase),
 
 622                     'Cannot normalize query string (is it a UTF-8 string?)'
 
 624                 if (trim($sPhrase)) {
 
 625                     $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
 
 626                     $oPhrase->addTokens($aTokens);
 
 627                     $aPhrases[] = $oPhrase;
 
 631             Debug::printVar('Tokens', $aTokens);
 
 633             $oValidTokens = new TokenList();
 
 635             if (!empty($aTokens)) {
 
 636                 $oValidTokens->addTokensFromDB(
 
 639                     $this->aCountryCodes,
 
 644                 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
 
 646                 // Try more interpretations for Tokens that could not be matched.
 
 647                 foreach ($aTokens as $sToken) {
 
 648                     if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
 
 649                         if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
 
 650                             // US ZIP+4 codes - merge in the 5-digit ZIP code
 
 651                             $oValidTokens->addToken(
 
 653                                 new Token\Postcode(null, $aData[1], 'us')
 
 655                         } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
 
 656                             // Unknown single word token with a number.
 
 657                             // Assume it is a house number.
 
 658                             $oValidTokens->addToken(
 
 660                                 new Token\HouseNumber(null, trim($sToken))
 
 666                 // Any words that have failed completely?
 
 669                 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
 
 671                 foreach ($aPhrases as $oPhrase) {
 
 672                     $oPhrase->computeWordSets($oValidTokens);
 
 674                 Debug::printDebugTable('Phrases', $aPhrases);
 
 676                 Debug::newSection('Search candidates');
 
 678                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
 
 680                 if (!$this->aStructuredQuery) {
 
 681                     // Reverse phrase array and also reverse the order of the wordsets in
 
 682                     // the first and final phrase. Don't bother about phrases in the middle
 
 683                     // because order in the address doesn't matter.
 
 684                     $aPhrases = array_reverse($aPhrases);
 
 685                     $aPhrases[0]->invertWordSets();
 
 686                     if (count($aPhrases) > 1) {
 
 687                         $aPhrases[count($aPhrases)-1]->invertWordSets();
 
 689                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
 
 691                     foreach ($aGroupedSearches as $aSearches) {
 
 692                         foreach ($aSearches as $aSearch) {
 
 693                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
 
 694                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
 
 696                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
 
 700                     $aGroupedSearches = $aReverseGroupedSearches;
 
 701                     ksort($aGroupedSearches);
 
 704                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
 
 705                 $aGroupedSearches = array();
 
 706                 foreach ($aSearches as $aSearch) {
 
 707                     if ($aSearch->getRank() < $this->iMaxRank) {
 
 708                         if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
 
 709                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
 
 712                 ksort($aGroupedSearches);
 
 715             // Filter out duplicate searches
 
 716             $aSearchHash = array();
 
 717             foreach ($aGroupedSearches as $iGroup => $aSearches) {
 
 718                 foreach ($aSearches as $iSearch => $aSearch) {
 
 719                     $sHash = serialize($aSearch);
 
 720                     if (isset($aSearchHash[$sHash])) {
 
 721                         unset($aGroupedSearches[$iGroup][$iSearch]);
 
 722                         if (empty($aGroupedSearches[$iGroup])) unset($aGroupedSearches[$iGroup]);
 
 724                         $aSearchHash[$sHash] = 1;
 
 729             Debug::printGroupedSearch(
 
 731                 $oValidTokens->debugTokenByWordIdList()
 
 734             // Start the search process
 
 737             $aNextResults = array();
 
 738             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
 
 740                 $aResults = $aNextResults;
 
 741                 foreach ($aSearches as $oSearch) {
 
 744                     Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
 
 745                     Debug::printGroupedSearch(
 
 746                         array($iGroupedRank => array($oSearch)),
 
 747                         $oValidTokens->debugTokenByWordIdList()
 
 750                     $aNewResults = $oSearch->query(
 
 752                         $this->iMinAddressRank,
 
 753                         $this->iMaxAddressRank,
 
 757                     // The same result may appear in different rounds, only
 
 758                     // use the one with minimal rank.
 
 759                     foreach ($aNewResults as $iPlace => $oRes) {
 
 760                         if (!isset($aResults[$iPlace])
 
 761                             || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
 
 762                             $aResults[$iPlace] = $oRes;
 
 766                     if ($iQueryLoop > 20) break;
 
 769                 if (!empty($aResults)) {
 
 770                     $aSplitResults = Result::splitResults($aResults);
 
 771                     Debug::printVar('Split results', $aSplitResults);
 
 773                         && reset($aSplitResults['head'])->iResultRank > 0
 
 774                         && $iGroupedRank !== array_key_last($aGroupedSearches)) {
 
 775                         // Haven't found an exact match for the query yet.
 
 776                         // Therefore add result from the next group level.
 
 777                         $aNextResults = $aSplitResults['head'];
 
 778                         foreach ($aNextResults as $oRes) {
 
 779                             $oRes->iResultRank--;
 
 781                         foreach ($aSplitResults['tail'] as $oRes) {
 
 782                             $oRes->iResultRank--;
 
 783                             $aNextResults[$oRes->iId] = $oRes;
 
 787                         $aResults = $aSplitResults['head'];
 
 791                 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
 
 792                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
 
 793                     // reduces the number of place ids, like a filter
 
 794                     // rank_address is 30 for interpolated housenumbers
 
 795                     $aFilterSql = array();
 
 796                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
 
 798                         $sSQL = 'SELECT place_id FROM placex ';
 
 799                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
 
 801                         $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 802                         $sSQL .= "         OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 803                         if ($this->aAddressRankList) {
 
 804                             $sSQL .= '     OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
 
 807                         $aFilterSql[] = $sSQL;
 
 809                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
 
 811                         $sSQL = ' SELECT place_id FROM location_postcode lp ';
 
 812                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
 
 813                         $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
 
 814                         if ($this->aAddressRankList) {
 
 815                             $sSQL .= '     OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
 
 818                         $aFilterSql[] = $sSQL;
 
 821                     $aFilteredIDs = array();
 
 823                         $sSQL = join(' UNION ', $aFilterSql);
 
 824                         Debug::printSQL($sSQL);
 
 825                         $aFilteredIDs = $this->oDB->getCol($sSQL);
 
 829                     foreach ($aResults as $oResult) {
 
 830                         if (($this->iMaxAddressRank == 30 &&
 
 831                              ($oResult->iTable == Result::TABLE_OSMLINE
 
 832                               || $oResult->iTable == Result::TABLE_TIGER))
 
 833                             || in_array($oResult->iId, $aFilteredIDs)
 
 835                             $tempIDs[$oResult->iId] = $oResult;
 
 838                     $aResults = $tempIDs;
 
 841                 if (!empty($aResults)) break;
 
 842                 if ($iGroupLoop > 4) break;
 
 843                 if ($iQueryLoop > 30) break;
 
 846             // Just interpret as a reverse geocode
 
 847             $oReverse = new ReverseGeocode($this->oDB);
 
 848             $oReverse->setZoom(18);
 
 850             $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
 
 852             Debug::printVar('Reverse search', $oLookup);
 
 855                 $aResults = array($oLookup->iId => $oLookup);
 
 860         if (empty($aResults)) {
 
 861             if ($this->bFallback) {
 
 862                 if ($this->fallbackStructuredQuery()) {
 
 863                     return $this->lookup();
 
 870         if ($this->aAddressRankList) {
 
 871             $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
 
 873         $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
 
 874         $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
 
 875         if ($oCtx->hasNearPoint()) {
 
 876             $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
 
 879         $aSearchResults = $this->oPlaceLookup->lookup($aResults);
 
 881         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
 
 882         foreach ($aRecheckWords as $i => $sWord) {
 
 883             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
 
 886         Debug::printVar('Recheck words', $aRecheckWords);
 
 888         foreach ($aSearchResults as $iIdx => $aResult) {
 
 889             $fRadius = ClassTypes\getDefRadius($aResult);
 
 891             $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fRadius);
 
 892             if ($aOutlineResult) {
 
 893                 $aResult = array_merge($aResult, $aOutlineResult);
 
 896             // Is there an icon set for this type of result?
 
 897             $sIcon = ClassTypes\getIconFile($aResult);
 
 899                 $aResult['icon'] = $sIcon;
 
 902             $sLabel = ClassTypes\getLabel($aResult);
 
 903             if (isset($sLabel)) {
 
 904                 $aResult['label'] = $sLabel;
 
 906             $aResult['name'] = $aResult['langaddress'];
 
 908             if ($oCtx->hasNearPoint()) {
 
 909                 $aResult['importance'] = 0.001;
 
 910                 $aResult['foundorder'] = $aResult['addressimportance'];
 
 912                 $aResult['importance'] = max(0.001, $aResult['importance']);
 
 913                 $aResult['importance'] *= $this->viewboxImportanceFactor(
 
 918                 // secondary ordering (for results with same importance (the smaller the better):
 
 919                 // - approximate importance of address parts
 
 920                 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
 
 921                     $aResult['foundorder'] = -$aResult['addressimportance']/10;
 
 923                     $aResult['foundorder'] = -$aResult['importance'];
 
 925                 // - number of exact matches from the query
 
 926                 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
 
 927                 // - importance of the class/type
 
 928                 $iClassImportance = ClassTypes\getImportance($aResult);
 
 929                 if (isset($iClassImportance)) {
 
 930                     $aResult['foundorder'] += 0.0001 * $iClassImportance;
 
 932                     $aResult['foundorder'] += 0.01;
 
 935                 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
 
 937                 // Adjust importance for the number of exact string matches in the result
 
 939                 $sAddress = $aResult['langaddress'];
 
 940                 foreach ($aRecheckWords as $i => $sWord) {
 
 941                     if (stripos($sAddress, $sWord)!==false) {
 
 943                         if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) $iCountWords += 0.1;
 
 947                 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
 
 948                 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
 
 950             $aSearchResults[$iIdx] = $aResult;
 
 952         uasort($aSearchResults, 'byImportance');
 
 953         Debug::printVar('Pre-filter results', $aSearchResults);
 
 955         $aOSMIDDone = array();
 
 956         $aClassTypeNameDone = array();
 
 957         $aToFilter = $aSearchResults;
 
 958         $aSearchResults = array();
 
 961         foreach ($aToFilter as $aResult) {
 
 962             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
 964                 $fLat = $aResult['lat'];
 
 965                 $fLon = $aResult['lon'];
 
 966                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
 969             if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
 
 970                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
 
 972                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
 
 973                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
 
 974                 $aSearchResults[] = $aResult;
 
 977             // Absolute limit on number of results
 
 978             if (count($aSearchResults) >= $this->iFinalLimit) break;
 
 981         Debug::printVar('Post-filter results', $aSearchResults);
 
 982         return $aSearchResults;
 
 985     public function debugInfo()
 
 988                 'Query' => $this->sQuery,
 
 989                 'Structured query' => $this->aStructuredQuery,
 
 990                 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
 
 991                 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
 
 992                 'Limit (for searches)' => $this->iLimit,
 
 993                 'Limit (for results)'=> $this->iFinalLimit,
 
 994                 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
 
 995                 'Bounded search' => $this->bBoundedSearch,
 
 996                 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
 
 997                 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
 
 998                 'Route width' => $this->aRouteWidth,
 
 999                 'Max rank' => $this->iMaxRank,
 
1000                 'Min address rank' => $this->iMinAddressRank,
 
1001                 'Max address rank' => $this->iMaxAddressRank,
 
1002                 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)