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');
 
  15     protected $oPlaceLookup;
 
  17     protected $aLangPrefOrder = array();
 
  19     protected $bIncludeAddressDetails = false;
 
  21     protected $aExcludePlaceIDs = array();
 
  22     protected $bReverseInPlan = false;
 
  24     protected $iLimit = 20;
 
  25     protected $iFinalLimit = 10;
 
  26     protected $iOffset = 0;
 
  27     protected $bFallback = false;
 
  29     protected $aCountryCodes = false;
 
  31     protected $bBoundedSearch = false;
 
  32     protected $aViewBox = false;
 
  33     protected $aRoutePoints = false;
 
  34     protected $aRouteWidth = false;
 
  36     protected $iMaxRank = 20;
 
  37     protected $iMinAddressRank = 0;
 
  38     protected $iMaxAddressRank = 30;
 
  39     protected $aAddressRankList = array();
 
  41     protected $sAllowedTypesSQLList = false;
 
  43     protected $sQuery = false;
 
  44     protected $aStructuredQuery = false;
 
  46     protected $oNormalizer = null;
 
  49     public function __construct(&$oDB)
 
  52         $this->oPlaceLookup = new PlaceLookup($this->oDB);
 
  53         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
 
  56     private function normTerm($sTerm)
 
  58         if ($this->oNormalizer === null) {
 
  62         return $this->oNormalizer->transliterate($sTerm);
 
  65     public function setReverseInPlan($bReverse)
 
  67         $this->bReverseInPlan = $bReverse;
 
  70     public function setLanguagePreference($aLangPref)
 
  72         $this->aLangPrefOrder = $aLangPref;
 
  75     public function getMoreUrlParams()
 
  77         if ($this->aStructuredQuery) {
 
  78             $aParams = $this->aStructuredQuery;
 
  80             $aParams = array('q' => $this->sQuery);
 
  83         $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
 
  85         if ($this->aExcludePlaceIDs) {
 
  86             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
 
  89         if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
 
  90         if ($this->bBoundedSearch) $aParams['bounded'] = '1';
 
  92         if ($this->aCountryCodes) {
 
  93             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
 
  96         if ($this->aViewBox) {
 
  97             $aParams['viewbox'] = join(',', $this->aViewBox);
 
 103     public function setLimit($iLimit = 10)
 
 105         if ($iLimit > 50) $iLimit = 50;
 
 106         if ($iLimit < 1) $iLimit = 1;
 
 108         $this->iFinalLimit = $iLimit;
 
 109         $this->iLimit = $iLimit + min($iLimit, 10);
 
 112     public function setFeatureType($sFeatureType)
 
 114         switch ($sFeatureType) {
 
 116                 $this->setRankRange(4, 4);
 
 119                 $this->setRankRange(8, 8);
 
 122                 $this->setRankRange(14, 16);
 
 125                 $this->setRankRange(8, 20);
 
 130     public function setRankRange($iMin, $iMax)
 
 132         $this->iMinAddressRank = $iMin;
 
 133         $this->iMaxAddressRank = $iMax;
 
 136     public function setViewbox($aViewbox)
 
 138         $aBox = array_map('floatval', $aViewbox);
 
 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]));
 
 145         if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
 
 146             || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
 
 148             userError("Bad parameter 'viewbox'. Not a box.");
 
 152     private function viewboxImportanceFactor($fX, $fY)
 
 154         $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
 
 155         $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
 
 157         $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
 
 158         $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
 
 160         if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
 
 164         if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
 
 171     public function setQuery($sQueryString)
 
 173         $this->sQuery = $sQueryString;
 
 174         $this->aStructuredQuery = false;
 
 177     public function getQueryString()
 
 179         return $this->sQuery;
 
 183     public function loadParamArray($oParams, $sForceGeometryType = null)
 
 185         $this->bIncludeAddressDetails
 
 186          = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
 
 188         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
 
 190         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
 
 191         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
 
 193         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
 
 195         // List of excluded Place IDs - used for more acurate pageing
 
 196         $sExcluded = $oParams->getStringList('exclude_place_ids');
 
 198             foreach ($sExcluded as $iExcludedPlaceID) {
 
 199                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
 
 200                 if ($iExcludedPlaceID)
 
 201                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
 
 204             if (isset($aExcludePlaceIDs))
 
 205                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
 
 208         // Only certain ranks of feature
 
 209         $sFeatureType = $oParams->getString('featureType');
 
 210         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
 
 211         if ($sFeatureType) $this->setFeatureType($sFeatureType);
 
 214         $sCountries = $oParams->getStringList('countrycodes');
 
 216             foreach ($sCountries as $sCountryCode) {
 
 217                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
 
 218                     $aCountries[] = strtolower($sCountryCode);
 
 221             if (isset($aCountries))
 
 222                 $this->aCountryCodes = $aCountries;
 
 225         $aViewbox = $oParams->getStringList('viewboxlbrt');
 
 227             if (count($aViewbox) != 4) {
 
 228                 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
 
 230             $this->setViewbox($aViewbox);
 
 232             $aViewbox = $oParams->getStringList('viewbox');
 
 234                 if (count($aViewbox) != 4) {
 
 235                     userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
 
 237                 $this->setViewBox($aViewbox);
 
 239                 $aRoute = $oParams->getStringList('route');
 
 240                 $fRouteWidth = $oParams->getFloat('routewidth');
 
 241                 if ($aRoute && $fRouteWidth) {
 
 242                     $this->aRoutePoints = $aRoute;
 
 243                     $this->aRouteWidth = $fRouteWidth;
 
 248         $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
 
 249         $this->oPlaceLookup->setIncludeAddressDetails(false);
 
 250         $this->oPlaceLookup->setIncludePolygonAsPoints($oParams->getBool('polygon'));
 
 253     public function setQueryFromParams($oParams)
 
 256         $sQuery = $oParams->getString('q');
 
 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')
 
 267             $this->setReverseInPlan(false);
 
 269             $this->setQuery($sQuery);
 
 273     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
 
 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;
 
 282         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
 
 286     public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
 
 288         $this->sQuery = false;
 
 291         $this->iMinAddressRank = 0;
 
 292         $this->iMaxAddressRank = 30;
 
 293         $this->aAddressRankList = array();
 
 295         $this->aStructuredQuery = array();
 
 296         $this->sAllowedTypesSQLList = false;
 
 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);
 
 306         if (sizeof($this->aStructuredQuery) > 0) {
 
 307             $this->sQuery = join(', ', $this->aStructuredQuery);
 
 308             if ($this->iMaxAddressRank < 30) {
 
 309                 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
 
 314     public function fallbackStructuredQuery()
 
 316         if (!$this->aStructuredQuery) return false;
 
 318         $aParams = $this->aStructuredQuery;
 
 320         if (sizeof($aParams) == 1) return false;
 
 322         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
 
 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']);
 
 335     public function getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bIsStructured)
 
 338              Calculate all searches using aValidTokens i.e.
 
 339              'Wodsworth Road, Sheffield' =>
 
 343              0      1       (wodsworth)(road)
 
 346              Score how good the search is so they can be ordered
 
 350         foreach ($aPhrases as $iPhrase => $oPhrase) {
 
 351             $aNewPhraseSearches = array();
 
 352             $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
 
 354             foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
 
 355                 // Too many permutations - too expensive
 
 356                 if ($iWordSet > 120) break;
 
 358                 $aWordsetSearches = $aSearches;
 
 360                 // Add all words from this wordset
 
 361                 foreach ($aWordset as $iToken => $sToken) {
 
 362                     //echo "<br><b>$sToken</b>";
 
 363                     $aNewWordsetSearches = array();
 
 365                     foreach ($aWordsetSearches as $oCurrentSearch) {
 
 367                         //var_dump($oCurrentSearch);
 
 370                         // If the token is valid
 
 371                         if (isset($aValidTokens[' '.$sToken])) {
 
 372                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
 
 373                                 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
 
 375                                     isset($aValidTokens[$sToken])
 
 376                                       && strpos($sToken, ' ') === false,
 
 378                                     $iToken == 0 && $iPhrase == 0,
 
 380                                     $iToken + 1 == sizeof($aWordset)
 
 381                                       && $iPhrase + 1 == sizeof($aPhrases),
 
 385                                 foreach ($aNewSearches as $oSearch) {
 
 386                                     if ($oSearch->getRank() < $this->iMaxRank) {
 
 387                                         $aNewWordsetSearches[] = $oSearch;
 
 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(
 
 402                                     isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
 
 405                                 foreach ($aNewSearches as $oSearch) {
 
 406                                     if ($oSearch->getRank() < $this->iMaxRank) {
 
 407                                         $aNewWordsetSearches[] = $oSearch;
 
 414                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
 
 415                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
 
 417                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
 
 419                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
 
 420                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
 
 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;
 
 429                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
 
 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();
 
 440                     $aGroupedSearches[$iRank][] = $aSearch;
 
 443             ksort($aGroupedSearches);
 
 446             $aSearches = array();
 
 447             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
 
 448                 $iSearchCount += sizeof($aNewSearches);
 
 449                 $aSearches = array_merge($aSearches, $aNewSearches);
 
 450                 if ($iSearchCount > 50) break;
 
 453             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 456         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
 
 457         $aGroupedSearches = array();
 
 458         foreach ($aSearches as $oSearch) {
 
 459             if (!$oSearch->isValidSearch()) {
 
 463             $iRank = $oSearch->addToRank($iGlobalRank);
 
 464             if (!isset($aGroupedSearches[$iRank])) {
 
 465                 $aGroupedSearches[$iRank] = array();
 
 467             $aGroupedSearches[$iRank][] = $oSearch;
 
 469         ksort($aGroupedSearches);
 
 471         return $aGroupedSearches;
 
 474     /* Perform the actual query lookup.
 
 476         Returns an ordered list of results, each with the following fields:
 
 477             osm_type: type of corresponding OSM object
 
 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)
 
 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
 
 506     public function lookup()
 
 508         if (!$this->sQuery && !$this->aStructuredQuery) return array();
 
 510         $oCtx = new SearchContext();
 
 512         if ($this->aRoutePoints) {
 
 513             $oCtx->setViewboxFromRoute(
 
 517                 $this->bBoundedSearch
 
 519         } elseif ($this->aViewBox) {
 
 520             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
 
 522         if ($this->aExcludePlaceIDs) {
 
 523             $oCtx->setExcludeList($this->aExcludePlaceIDs);
 
 525         if ($this->aCountryCodes) {
 
 526             $oCtx->setCountryList($this->aCountryCodes);
 
 529         $sNormQuery = $this->normTerm($this->sQuery);
 
 530         $sLanguagePrefArraySQL = getArraySQL(
 
 531             array_map("getDBQuoted", $this->aLangPrefOrder)
 
 534         $sQuery = $this->sQuery;
 
 535         if (!preg_match('//u', $sQuery)) {
 
 536             userError("Query string is not UTF-8 encoded.");
 
 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);
 
 546         // Do we have anything that looks like a lat/lon pair?
 
 547         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
 
 550         if ($sQuery || $this->aStructuredQuery) {
 
 551             // Start with a single blank search
 
 552             $aSearches = array(new SearchDescription($oCtx));
 
 555                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
 
 561                     '/\\[([\\w ]*)\\]/u',
 
 566                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
 
 567                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
 
 568                     if (!$sSpecialTerm) {
 
 569                         $sSpecialTerm = $aSpecialTerm[1];
 
 573             if (!$sSpecialTerm && $this->aStructuredQuery
 
 574                 && isset($this->aStructuredQuery['amenity'])) {
 
 575                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
 
 576                 unset($this->aStructuredQuery['amenity']);
 
 579             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
 
 580                 $sSpecialTerm = pg_escape_string($sSpecialTerm);
 
 582                     $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
 
 583                     "Cannot decode query. Wrong encoding?"
 
 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(
 
 596                             $aSearchTerm['class'],
 
 599                         $aNewSearches[] = $oNewSearch;
 
 602                 $aSearches = $aNewSearches;
 
 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;
 
 611                 $aInPhrases = explode(',', $sQuery);
 
 612                 $bStructuredPhrases = false;
 
 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
 
 621             foreach ($aInPhrases as $iPhrase => $sPhrase) {
 
 623                     $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
 
 624                     "Cannot normalize query string (is it a UTF-8 string?)"
 
 626                 if (trim($sPhrase)) {
 
 627                     $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
 
 628                     $oPhrase->addTokens($aTokens);
 
 629                     $aPhrases[] = $oPhrase;
 
 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)).')';
 
 639                 if (CONST_Debug) var_Dump($sSQL);
 
 641                 $aValidTokens = array();
 
 642                 $aDatabaseWords = chksql(
 
 643                     $this->oDB->getAll($sSQL),
 
 644                     "Could not get word tokens."
 
 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)
 
 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) {
 
 664                     if (isset($aValidTokens[$aToken['word_token']])) {
 
 665                         $aValidTokens[$aToken['word_token']][] = $aToken;
 
 667                         $aValidTokens[$aToken['word_token']] = array($aToken);
 
 669                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
 
 671                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
 
 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;
 
 682                                         $aValidTokens[$sToken] = array($aToken);
 
 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));
 
 697                 // Any words that have failed completely?
 
 700                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bStructuredPhrases);
 
 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();
 
 711                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, false);
 
 713                     foreach ($aGroupedSearches as $aSearches) {
 
 714                         foreach ($aSearches as $aSearch) {
 
 715                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
 
 716                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
 
 718                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
 
 722                     $aGroupedSearches = $aReverseGroupedSearches;
 
 723                     ksort($aGroupedSearches);
 
 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;
 
 734                 ksort($aGroupedSearches);
 
 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]);
 
 746                         $aSearchHash[$sHash] = 1;
 
 751             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
 
 753             // Start the search process
 
 756             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
 
 758                 foreach ($aSearches as $oSearch) {
 
 762                         echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
 
 763                         _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
 
 766                     $aResults += $oSearch->query(
 
 768                         $aWordFrequencyScores,
 
 769                         $this->iMinAddressRank,
 
 770                         $this->iMaxAddressRank,
 
 774                     if ($iQueryLoop > 20) break;
 
 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);
 
 784                         $sSQL = 'SELECT place_id FROM placex ';
 
 785                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
 
 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'";
 
 791                         if ($this->aAddressRankList) {
 
 792                             $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
 
 795                         $aFilterSql[] = $sSQL;
 
 797                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
 
 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).")";
 
 806                         $aFilterSql[] = $sSQL;
 
 809                     $aFilteredIDs = array();
 
 811                         $sSQL = join(' UNION ', $aFilterSql);
 
 812                         if (CONST_Debug) var_dump($sSQL);
 
 813                         $aFilteredIDs = chksql($this->oDB->getCol($sSQL));
 
 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)
 
 824                             $tempIDs[$oResult->iId] = $oResult;
 
 827                     $aResults = $tempIDs;
 
 830                 if (sizeof($aResults)) break;
 
 831                 if ($iGroupLoop > 4) break;
 
 832                 if ($iQueryLoop > 30) break;
 
 835             // Just interpret as a reverse geocode
 
 836             $oReverse = new ReverseGeocode($this->oDB);
 
 837             $oReverse->setZoom(18);
 
 839             $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
 
 841             if (CONST_Debug) var_dump("Reverse search", $aLookup);
 
 844                 $aResults = array($oLookup->iId => $oLookup);
 
 849         if (!sizeof($aResults)) {
 
 850             if ($this->bFallback) {
 
 851                 if ($this->fallbackStructuredQuery()) {
 
 852                     return $this->lookup();
 
 859         if ($this->aAddressRankList) {
 
 860             $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
 
 862         $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
 
 863         $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
 
 864         if ($oCtx->hasNearPoint()) {
 
 865             $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
 
 868         $aSearchResults = $this->oPlaceLookup->lookup($aResults);
 
 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]);
 
 877             echo '<i>Recheck words:<\i>';
 
 878             var_dump($aRecheckWords);
 
 881         foreach ($aSearchResults as $iIdx => $aResult) {
 
 883             $fDiameter = getResultDiameter($aResult);
 
 885             $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
 
 886             if ($aOutlineResult) {
 
 887                 $aResult = array_merge($aResult, $aOutlineResult);
 
 890             if ($aResult['extra_place'] == 'city') {
 
 891                 $aResult['class'] = 'place';
 
 892                 $aResult['type'] = 'city';
 
 893                 $aResult['rank_search'] = 16;
 
 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']
 
 900                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
 
 903             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
 
 904                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
 
 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']
 
 910                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
 
 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']);
 
 921             $aResult['name'] = $aResult['langaddress'];
 
 923             if ($oCtx->hasNearPoint()) {
 
 924                 $aResult['importance'] = 0.001;
 
 925                 $aResult['foundorder'] = $aResult['addressimportance'];
 
 927                 // Adjust importance for the number of exact string matches in the result
 
 928                 $aResult['importance'] *= $this->viewboxImportanceFactor(
 
 932                 $aResult['importance'] = max(0.001, $aResult['importance']);
 
 934                 $sAddress = $aResult['langaddress'];
 
 935                 foreach ($aRecheckWords as $i => $sWord) {
 
 936                     if (stripos($sAddress, $sWord)!==false) {
 
 938                         if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
 
 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
 
 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']
 
 953                     $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
 
 955                     $aResult['foundorder'] += 0.01;
 
 958             if (CONST_Debug) var_dump($aResult);
 
 959             $aSearchResults[$iIdx] = $aResult;
 
 961         uasort($aSearchResults, 'byImportance');
 
 963         $aOSMIDDone = array();
 
 964         $aClassTypeNameDone = array();
 
 965         $aToFilter = $aSearchResults;
 
 966         $aSearchResults = array();
 
 968         if (CONST_Debug) var_dump($aToFilter);
 
 971         foreach ($aToFilter as $aResult) {
 
 972             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
 
 974                 $fLat = $aResult['lat'];
 
 975                 $fLon = $aResult['lon'];
 
 976                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
 
 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']]))
 
 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;
 
 987             // Absolute limit on number of results
 
 988             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
 
 991         if (CONST_Debug) var_dump($aSearchResults);
 
 992         return $aSearchResults;