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');
11 require_once(CONST_TokenizerDir.'/tokenizer.php');
17 protected $oPlaceLookup;
19 protected $aLangPrefOrder = array();
21 protected $aExcludePlaceIDs = array();
23 protected $iLimit = 20;
24 protected $iFinalLimit = 10;
25 protected $iOffset = 0;
26 protected $bFallback = false;
28 protected $aCountryCodes = false;
30 protected $bBoundedSearch = false;
31 protected $aViewBox = false;
32 protected $aRoutePoints = false;
33 protected $aRouteWidth = false;
35 protected $iMaxRank = 20;
36 protected $iMinAddressRank = 0;
37 protected $iMaxAddressRank = 30;
38 protected $aAddressRankList = array();
40 protected $sAllowedTypesSQLList = false;
42 protected $sQuery = false;
43 protected $aStructuredQuery = false;
45 protected $oNormalizer = null;
48 public function __construct(&$oDB)
51 $this->oPlaceLookup = new PlaceLookup($this->oDB);
52 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
55 private function normTerm($sTerm)
57 if ($this->oNormalizer === null) {
61 return $this->oNormalizer->transliterate($sTerm);
64 public function setLanguagePreference($aLangPref)
66 $this->aLangPrefOrder = $aLangPref;
69 public function getMoreUrlParams()
71 if ($this->aStructuredQuery) {
72 $aParams = $this->aStructuredQuery;
74 $aParams = array('q' => $this->sQuery);
77 $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
79 if ($this->aExcludePlaceIDs) {
80 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
83 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
85 if ($this->aCountryCodes) {
86 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
89 if ($this->aViewBox) {
90 $aParams['viewbox'] = join(',', $this->aViewBox);
96 public function setLimit($iLimit = 10)
98 if ($iLimit > 50) $iLimit = 50;
99 if ($iLimit < 1) $iLimit = 1;
101 $this->iFinalLimit = $iLimit;
102 $this->iLimit = $iLimit + min($iLimit, 10);
105 public function setFeatureType($sFeatureType)
107 switch ($sFeatureType) {
109 $this->setRankRange(4, 4);
112 $this->setRankRange(8, 8);
115 $this->setRankRange(14, 16);
118 $this->setRankRange(8, 20);
123 public function setRankRange($iMin, $iMax)
125 $this->iMinAddressRank = $iMin;
126 $this->iMaxAddressRank = $iMax;
129 public function setViewbox($aViewbox)
131 $aBox = array_map('floatval', $aViewbox);
133 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
134 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
135 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
136 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
138 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
139 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
141 userError("Bad parameter 'viewbox'. Not a box.");
145 private function viewboxImportanceFactor($fX, $fY)
147 if (!$this->aViewBox) {
151 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
152 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
154 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
155 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
157 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
161 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
168 public function setQuery($sQueryString)
170 $this->sQuery = $sQueryString;
171 $this->aStructuredQuery = false;
174 public function getQueryString()
176 return $this->sQuery;
180 public function loadParamArray($oParams, $sForceGeometryType = null)
182 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
184 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
185 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
187 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
189 // List of excluded Place IDs - used for more acurate pageing
190 $sExcluded = $oParams->getStringList('exclude_place_ids');
192 foreach ($sExcluded as $iExcludedPlaceID) {
193 $iExcludedPlaceID = (int)$iExcludedPlaceID;
194 if ($iExcludedPlaceID)
195 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
198 if (isset($aExcludePlaceIDs))
199 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
202 // Only certain ranks of feature
203 $sFeatureType = $oParams->getString('featureType');
204 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
205 if ($sFeatureType) $this->setFeatureType($sFeatureType);
208 $sCountries = $oParams->getStringList('countrycodes');
210 foreach ($sCountries as $sCountryCode) {
211 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
212 $aCountries[] = strtolower($sCountryCode);
215 if (isset($aCountries))
216 $this->aCountryCodes = $aCountries;
219 $aViewbox = $oParams->getStringList('viewboxlbrt');
221 if (count($aViewbox) != 4) {
222 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
224 $this->setViewbox($aViewbox);
226 $aViewbox = $oParams->getStringList('viewbox');
228 if (count($aViewbox) != 4) {
229 userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
231 $this->setViewBox($aViewbox);
233 $aRoute = $oParams->getStringList('route');
234 $fRouteWidth = $oParams->getFloat('routewidth');
235 if ($aRoute && $fRouteWidth) {
236 $this->aRoutePoints = $aRoute;
237 $this->aRouteWidth = $fRouteWidth;
242 $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
243 $this->oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', false));
246 public function setQueryFromParams($oParams)
249 $sQuery = $oParams->getString('q');
251 $this->setStructuredQuery(
252 $oParams->getString('amenity'),
253 $oParams->getString('street'),
254 $oParams->getString('city'),
255 $oParams->getString('county'),
256 $oParams->getString('state'),
257 $oParams->getString('country'),
258 $oParams->getString('postalcode')
261 $this->setQuery($sQuery);
265 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
267 $sValue = trim($sValue);
268 if (!$sValue) return false;
269 $this->aStructuredQuery[$sKey] = $sValue;
270 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
271 $this->iMinAddressRank = $iNewMinAddressRank;
272 $this->iMaxAddressRank = $iNewMaxAddressRank;
274 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
278 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
280 $this->sQuery = false;
283 $this->iMinAddressRank = 0;
284 $this->iMaxAddressRank = 30;
285 $this->aAddressRankList = array();
287 $this->aStructuredQuery = array();
288 $this->sAllowedTypesSQLList = false;
290 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
291 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
292 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
293 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
294 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
295 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
296 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
298 if (!empty($this->aStructuredQuery)) {
299 $this->sQuery = join(', ', $this->aStructuredQuery);
300 if ($this->iMaxAddressRank < 30) {
301 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
306 public function fallbackStructuredQuery()
308 if (!$this->aStructuredQuery) return false;
310 $aParams = $this->aStructuredQuery;
312 if (count($aParams) == 1) return false;
314 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
316 foreach ($aOrderToFallback as $sType) {
317 if (isset($aParams[$sType])) {
318 unset($aParams[$sType]);
319 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
327 public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens)
330 Calculate all searches using oValidTokens i.e.
331 'Wodsworth Road, Sheffield' =>
335 0 1 (wodsworth)(road)
338 Score how good the search is so they can be ordered
340 foreach ($aPhrases as $iPhrase => $oPhrase) {
341 $aNewPhraseSearches = array();
342 $sPhraseType = $oPhrase->getPhraseType();
344 foreach ($oPhrase->getWordSets() as $aWordset) {
345 $aWordsetSearches = $aSearches;
347 // Add all words from this wordset
348 foreach ($aWordset as $iToken => $sToken) {
349 //echo "<br><b>$sToken</b>";
350 $aNewWordsetSearches = array();
352 foreach ($aWordsetSearches as $oCurrentSearch) {
354 //var_dump($oCurrentSearch);
357 // Tokens with full name matches.
358 foreach ($oValidTokens->get(' '.$sToken) as $oSearchTerm) {
359 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
361 $oValidTokens->contains($sToken)
362 && strpos($sToken, ' ') === false,
364 $iToken == 0 && $iPhrase == 0,
366 $iToken + 1 == count($aWordset)
367 && $iPhrase + 1 == count($aPhrases)
370 foreach ($aNewSearches as $oSearch) {
371 if ($oSearch->getRank() < $this->iMaxRank) {
372 $aNewWordsetSearches[] = $oSearch;
376 // Look for partial matches.
377 // Note that there is no point in adding country terms here
378 // because country is omitted in the address.
379 if ($sPhraseType != 'country') {
380 // Allow searching for a word - but at extra cost
381 foreach ($oValidTokens->get($sToken) as $oSearchTerm) {
382 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
387 $oValidTokens->get(' '.$sToken)
390 foreach ($aNewSearches as $oSearch) {
391 if ($oSearch->getRank() < $this->iMaxRank) {
392 $aNewWordsetSearches[] = $oSearch;
399 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
400 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
402 //var_Dump('<hr>',count($aWordsetSearches)); exit;
404 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
405 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
407 $aSearchHash = array();
408 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
409 $sHash = serialize($aSearch);
410 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
411 else $aSearchHash[$sHash] = 1;
414 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
417 // Re-group the searches by their score, junk anything over 20 as just not worth trying
418 $aGroupedSearches = array();
419 foreach ($aNewPhraseSearches as $aSearch) {
420 $iRank = $aSearch->getRank();
421 if ($iRank < $this->iMaxRank) {
422 if (!isset($aGroupedSearches[$iRank])) {
423 $aGroupedSearches[$iRank] = array();
425 $aGroupedSearches[$iRank][] = $aSearch;
428 ksort($aGroupedSearches);
431 $aSearches = array();
432 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
433 $iSearchCount += count($aNewSearches);
434 $aSearches = array_merge($aSearches, $aNewSearches);
435 if ($iSearchCount > 50) break;
439 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
440 $aGroupedSearches = array();
441 foreach ($aSearches as $oSearch) {
442 if (!$oSearch->isValidSearch()) {
446 $iRank = $oSearch->getRank();
447 if (!isset($aGroupedSearches[$iRank])) {
448 $aGroupedSearches[$iRank] = array();
450 $aGroupedSearches[$iRank][] = $oSearch;
452 ksort($aGroupedSearches);
454 return $aGroupedSearches;
457 /* Perform the actual query lookup.
459 Returns an ordered list of results, each with the following fields:
460 osm_type: type of corresponding OSM object
464 P - postcode (internally computed)
465 osm_id: id of corresponding OSM object
466 class: general object class (corresponds to tag key of primary OSM tag)
467 type: subclass of object (corresponds to tag value of primary OSM tag)
468 admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
469 rank_search: rank in search hierarchy
470 (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
471 rank_address: rank in address hierarchy (determines orer in address)
472 place_id: internal key (may differ between different instances)
473 country_code: ISO country code
474 langaddress: localized full address
475 placename: localized name of object
476 ref: content of ref tag (if available)
479 importance: importance of place based on Wikipedia link count
480 addressimportance: cumulated importance of address elements
481 extra_place: type of place (for admin boundaries, if there is a place tag)
482 aBoundingBox: bounding Box
483 label: short description of the object class/type (English only)
484 name: full name (currently the same as langaddress)
485 foundorder: secondary ordering for places with same importance
489 public function lookup()
491 Debug::newFunction('Geocode::lookup');
492 if (!$this->sQuery && !$this->aStructuredQuery) return array();
494 Debug::printDebugArray('Geocode', $this);
496 $oCtx = new SearchContext();
498 if ($this->aRoutePoints) {
499 $oCtx->setViewboxFromRoute(
503 $this->bBoundedSearch
505 } elseif ($this->aViewBox) {
506 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
508 if ($this->aExcludePlaceIDs) {
509 $oCtx->setExcludeList($this->aExcludePlaceIDs);
511 if ($this->aCountryCodes) {
512 $oCtx->setCountryList($this->aCountryCodes);
515 Debug::newSection('Query Preprocessing');
517 $sNormQuery = $this->normTerm($this->sQuery);
518 Debug::printVar('Normalized query', $sNormQuery);
520 $sLanguagePrefArraySQL = $this->oDB->getArraySQL(
521 $this->oDB->getDBQuotedList($this->aLangPrefOrder)
524 $sQuery = $this->sQuery;
525 if (!preg_match('//u', $sQuery)) {
526 userError('Query string is not UTF-8 encoded.');
529 // Conflicts between US state abreviations and various words for 'the' in different languages
530 if (isset($this->aLangPrefOrder['name:en'])) {
531 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
532 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
533 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
536 // Do we have anything that looks like a lat/lon pair?
537 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
539 if ($sQuery || $this->aStructuredQuery) {
540 // Start with a single blank search
541 $aSearches = array(new SearchDescription($oCtx));
544 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
550 '/\\[([\\w ]*)\\]/u',
555 if (!empty($aSpecialTermsRaw)) {
556 Debug::printVar('Special terms', $aSpecialTermsRaw);
559 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
560 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
561 if (!$sSpecialTerm) {
562 $sSpecialTerm = $aSpecialTerm[1];
566 if (!$sSpecialTerm && $this->aStructuredQuery
567 && isset($this->aStructuredQuery['amenity'])) {
568 $sSpecialTerm = $this->aStructuredQuery['amenity'];
569 unset($this->aStructuredQuery['amenity']);
572 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
573 $sSpecialTerm = pg_escape_string($sSpecialTerm);
574 $sToken = $this->oDB->getOne(
575 'SELECT make_standard_name(:term)',
576 array(':term' => $sSpecialTerm),
577 'Cannot decode query. Wrong encoding?'
579 $sSQL = 'SELECT class, type FROM word ';
580 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
581 $sSQL .= ' AND class is not null AND class not in (\'place\')';
583 Debug::printSQL($sSQL);
584 $aSearchWords = $this->oDB->getAll($sSQL);
585 $aNewSearches = array();
586 foreach ($aSearches as $oSearch) {
587 foreach ($aSearchWords as $aSearchTerm) {
588 $oNewSearch = clone $oSearch;
589 $oNewSearch->setPoiSearch(
591 $aSearchTerm['class'],
594 $aNewSearches[] = $oNewSearch;
597 $aSearches = $aNewSearches;
600 // Split query into phrases
601 // Commas are used to reduce the search space by indicating where phrases split
602 if ($this->aStructuredQuery) {
603 $aInPhrases = $this->aStructuredQuery;
605 $aInPhrases = explode(',', $sQuery);
608 Debug::printDebugArray('Search context', $oCtx);
609 Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
610 Debug::printVar('Final query phrases', $aInPhrases);
612 // Convert each phrase to standard form
613 // Create a list of standard words
614 // Get all 'sets' of words
615 // Generate a complete list of all
616 Debug::newSection('Tokenization');
619 foreach ($aInPhrases as $iPhrase => $sPhrase) {
620 $sPhrase = $this->oDB->getOne(
621 'SELECT make_standard_name(:phrase)',
622 array(':phrase' => $sPhrase),
623 'Cannot normalize query string (is it a UTF-8 string?)'
625 if (trim($sPhrase)) {
626 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
627 $oPhrase->addTokens($aTokens);
628 $aPhrases[] = $oPhrase;
632 Debug::printVar('Tokens', $aTokens);
634 $oValidTokens = new TokenList();
636 if (!empty($aTokens)) {
637 $oValidTokens->addTokensFromDB(
640 $this->aCountryCodes,
645 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
647 // Try more interpretations for Tokens that could not be matched.
648 foreach ($aTokens as $sToken) {
649 if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
650 if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
651 // US ZIP+4 codes - merge in the 5-digit ZIP code
652 $oValidTokens->addToken(
654 new Token\Postcode(null, $aData[1], 'us')
656 } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
657 // Unknown single word token with a number.
658 // Assume it is a house number.
659 $oValidTokens->addToken(
661 new Token\HouseNumber(null, trim($sToken))
667 // Any words that have failed completely?
670 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
672 foreach ($aPhrases as $oPhrase) {
673 $oPhrase->computeWordSets($oValidTokens);
675 Debug::printDebugTable('Phrases', $aPhrases);
677 Debug::newSection('Search candidates');
679 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
681 if (!$this->aStructuredQuery) {
682 // Reverse phrase array and also reverse the order of the wordsets in
683 // the first and final phrase. Don't bother about phrases in the middle
684 // because order in the address doesn't matter.
685 $aPhrases = array_reverse($aPhrases);
686 $aPhrases[0]->invertWordSets();
687 if (count($aPhrases) > 1) {
688 $aPhrases[count($aPhrases)-1]->invertWordSets();
690 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
692 foreach ($aGroupedSearches as $aSearches) {
693 foreach ($aSearches as $aSearch) {
694 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
695 $aReverseGroupedSearches[$aSearch->getRank()] = array();
697 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
701 $aGroupedSearches = $aReverseGroupedSearches;
702 ksort($aGroupedSearches);
705 // Re-group the searches by their score, junk anything over 20 as just not worth trying
706 $aGroupedSearches = array();
707 foreach ($aSearches as $aSearch) {
708 if ($aSearch->getRank() < $this->iMaxRank) {
709 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
710 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
713 ksort($aGroupedSearches);
716 // Filter out duplicate searches
717 $aSearchHash = array();
718 foreach ($aGroupedSearches as $iGroup => $aSearches) {
719 foreach ($aSearches as $iSearch => $aSearch) {
720 $sHash = serialize($aSearch);
721 if (isset($aSearchHash[$sHash])) {
722 unset($aGroupedSearches[$iGroup][$iSearch]);
723 if (empty($aGroupedSearches[$iGroup])) unset($aGroupedSearches[$iGroup]);
725 $aSearchHash[$sHash] = 1;
730 Debug::printGroupedSearch(
732 $oValidTokens->debugTokenByWordIdList()
735 // Start the search process
738 $aNextResults = array();
739 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
741 $aResults = $aNextResults;
742 foreach ($aSearches as $oSearch) {
745 Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
746 Debug::printGroupedSearch(
747 array($iGroupedRank => array($oSearch)),
748 $oValidTokens->debugTokenByWordIdList()
751 $aNewResults = $oSearch->query(
753 $this->iMinAddressRank,
754 $this->iMaxAddressRank,
758 // The same result may appear in different rounds, only
759 // use the one with minimal rank.
760 foreach ($aNewResults as $iPlace => $oRes) {
761 if (!isset($aResults[$iPlace])
762 || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
763 $aResults[$iPlace] = $oRes;
767 if ($iQueryLoop > 20) break;
770 if (!empty($aResults)) {
771 $aSplitResults = Result::splitResults($aResults);
772 Debug::printVar('Split results', $aSplitResults);
774 && reset($aSplitResults['head'])->iResultRank > 0
775 && $iGroupedRank !== array_key_last($aGroupedSearches)) {
776 // Haven't found an exact match for the query yet.
777 // Therefore add result from the next group level.
778 $aNextResults = $aSplitResults['head'];
779 foreach ($aNextResults as $oRes) {
780 $oRes->iResultRank--;
782 foreach ($aSplitResults['tail'] as $oRes) {
783 $oRes->iResultRank--;
784 $aNextResults[$oRes->iId] = $oRes;
788 $aResults = $aSplitResults['head'];
792 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
793 // Need to verify passes rank limits before dropping out of the loop (yuk!)
794 // reduces the number of place ids, like a filter
795 // rank_address is 30 for interpolated housenumbers
796 $aFilterSql = array();
797 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
799 $sSQL = 'SELECT place_id FROM placex ';
800 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
802 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
803 $sSQL .= " OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
804 if ($this->aAddressRankList) {
805 $sSQL .= ' OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
808 $aFilterSql[] = $sSQL;
810 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
812 $sSQL = ' SELECT place_id FROM location_postcode lp ';
813 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
814 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
815 if ($this->aAddressRankList) {
816 $sSQL .= ' OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
819 $aFilterSql[] = $sSQL;
822 $aFilteredIDs = array();
824 $sSQL = join(' UNION ', $aFilterSql);
825 Debug::printSQL($sSQL);
826 $aFilteredIDs = $this->oDB->getCol($sSQL);
830 foreach ($aResults as $oResult) {
831 if (($this->iMaxAddressRank == 30 &&
832 ($oResult->iTable == Result::TABLE_OSMLINE
833 || $oResult->iTable == Result::TABLE_TIGER))
834 || in_array($oResult->iId, $aFilteredIDs)
836 $tempIDs[$oResult->iId] = $oResult;
839 $aResults = $tempIDs;
842 if (!empty($aResults)) break;
843 if ($iGroupLoop > 4) break;
844 if ($iQueryLoop > 30) break;
847 // Just interpret as a reverse geocode
848 $oReverse = new ReverseGeocode($this->oDB);
849 $oReverse->setZoom(18);
851 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
853 Debug::printVar('Reverse search', $oLookup);
856 $aResults = array($oLookup->iId => $oLookup);
861 if (empty($aResults)) {
862 if ($this->bFallback) {
863 if ($this->fallbackStructuredQuery()) {
864 return $this->lookup();
871 if ($this->aAddressRankList) {
872 $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
874 $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
875 $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
876 if ($oCtx->hasNearPoint()) {
877 $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
880 $aSearchResults = $this->oPlaceLookup->lookup($aResults);
882 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
883 foreach ($aRecheckWords as $i => $sWord) {
884 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
887 Debug::printVar('Recheck words', $aRecheckWords);
889 foreach ($aSearchResults as $iIdx => $aResult) {
890 $fRadius = ClassTypes\getDefRadius($aResult);
892 $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fRadius);
893 if ($aOutlineResult) {
894 $aResult = array_merge($aResult, $aOutlineResult);
897 // Is there an icon set for this type of result?
898 $sIcon = ClassTypes\getIconFile($aResult);
900 $aResult['icon'] = $sIcon;
903 $sLabel = ClassTypes\getLabel($aResult);
904 if (isset($sLabel)) {
905 $aResult['label'] = $sLabel;
907 $aResult['name'] = $aResult['langaddress'];
909 if ($oCtx->hasNearPoint()) {
910 $aResult['importance'] = 0.001;
911 $aResult['foundorder'] = $aResult['addressimportance'];
913 $aResult['importance'] = max(0.001, $aResult['importance']);
914 $aResult['importance'] *= $this->viewboxImportanceFactor(
919 // secondary ordering (for results with same importance (the smaller the better):
920 // - approximate importance of address parts
921 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
922 $aResult['foundorder'] = -$aResult['addressimportance']/10;
924 $aResult['foundorder'] = -$aResult['importance'];
926 // - number of exact matches from the query
927 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
928 // - importance of the class/type
929 $iClassImportance = ClassTypes\getImportance($aResult);
930 if (isset($iClassImportance)) {
931 $aResult['foundorder'] += 0.0001 * $iClassImportance;
933 $aResult['foundorder'] += 0.01;
936 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
938 // Adjust importance for the number of exact string matches in the result
940 $sAddress = $aResult['langaddress'];
941 foreach ($aRecheckWords as $i => $sWord) {
942 if (stripos($sAddress, $sWord)!==false) {
944 if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) $iCountWords += 0.1;
948 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
949 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
951 $aSearchResults[$iIdx] = $aResult;
953 uasort($aSearchResults, 'byImportance');
954 Debug::printVar('Pre-filter results', $aSearchResults);
956 $aOSMIDDone = array();
957 $aClassTypeNameDone = array();
958 $aToFilter = $aSearchResults;
959 $aSearchResults = array();
962 foreach ($aToFilter as $aResult) {
963 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
965 $fLat = $aResult['lat'];
966 $fLon = $aResult['lon'];
967 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
970 if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
971 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
973 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
974 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
975 $aSearchResults[] = $aResult;
978 // Absolute limit on number of results
979 if (count($aSearchResults) >= $this->iFinalLimit) break;
982 Debug::printVar('Post-filter results', $aSearchResults);
983 return $aSearchResults;
986 public function debugInfo()
989 'Query' => $this->sQuery,
990 'Structured query' => $this->aStructuredQuery,
991 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
992 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
993 'Limit (for searches)' => $this->iLimit,
994 'Limit (for results)'=> $this->iFinalLimit,
995 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
996 'Bounded search' => $this->bBoundedSearch,
997 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
998 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
999 'Route width' => $this->aRouteWidth,
1000 'Max rank' => $this->iMaxRank,
1001 'Min address rank' => $this->iMinAddressRank,
1002 'Max address rank' => $this->iMaxAddressRank,
1003 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)