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;
18 protected $oTokenizer;
20 protected $aLangPrefOrder = array();
22 protected $aExcludePlaceIDs = array();
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;
47 public function __construct(&$oDB)
50 $this->oPlaceLookup = new PlaceLookup($this->oDB);
51 $this->oTokenizer = new \Nominatim\Tokenizer($this->oDB);
54 public function setLanguagePreference($aLangPref)
56 $this->aLangPrefOrder = $aLangPref;
59 public function getMoreUrlParams()
61 if ($this->aStructuredQuery) {
62 $aParams = $this->aStructuredQuery;
64 $aParams = array('q' => $this->sQuery);
67 $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
69 if ($this->aExcludePlaceIDs) {
70 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
73 if ($this->bBoundedSearch) {
74 $aParams['bounded'] = '1';
77 if ($this->aCountryCodes) {
78 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
81 if ($this->aViewBox) {
82 $aParams['viewbox'] = join(',', $this->aViewBox);
88 public function setLimit($iLimit = 10)
92 } elseif ($iLimit < 1) {
96 $this->iFinalLimit = $iLimit;
97 $this->iLimit = $iLimit + min($iLimit, 10);
100 public function setFeatureType($sFeatureType)
102 switch ($sFeatureType) {
104 $this->setRankRange(4, 4);
107 $this->setRankRange(8, 8);
110 $this->setRankRange(14, 16);
113 $this->setRankRange(8, 20);
118 public function setRankRange($iMin, $iMax)
120 $this->iMinAddressRank = $iMin;
121 $this->iMaxAddressRank = $iMax;
124 public function setViewbox($aViewbox)
126 $aBox = array_map('floatval', $aViewbox);
128 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
129 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
130 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
131 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
133 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
134 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
136 userError("Bad parameter 'viewbox'. Not a box.");
140 private function viewboxImportanceFactor($fX, $fY)
142 if (!$this->aViewBox) {
146 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
147 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
149 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
150 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
152 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
156 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
163 public function setQuery($sQueryString)
165 $this->sQuery = $sQueryString;
166 $this->aStructuredQuery = false;
169 public function getQueryString()
171 return $this->sQuery;
175 public function loadParamArray($oParams, $sForceGeometryType = null)
177 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
179 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
180 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
182 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
184 // List of excluded Place IDs - used for more acurate pageing
185 $sExcluded = $oParams->getStringList('exclude_place_ids');
187 foreach ($sExcluded as $iExcludedPlaceID) {
188 $iExcludedPlaceID = (int)$iExcludedPlaceID;
189 if ($iExcludedPlaceID) {
190 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
194 if (isset($aExcludePlaceIDs)) {
195 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
199 // Only certain ranks of feature
200 $sFeatureType = $oParams->getString('featureType');
201 if (!$sFeatureType) {
202 $sFeatureType = $oParams->getString('featuretype');
205 $this->setFeatureType($sFeatureType);
209 $sCountries = $oParams->getStringList('countrycodes');
211 foreach ($sCountries as $sCountryCode) {
212 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
213 $aCountries[] = strtolower($sCountryCode);
216 if (isset($aCountries)) {
217 $this->aCountryCodes = $aCountries;
221 $aViewbox = $oParams->getStringList('viewboxlbrt');
223 if (count($aViewbox) != 4) {
224 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
226 $this->setViewbox($aViewbox);
228 $aViewbox = $oParams->getStringList('viewbox');
230 if (count($aViewbox) != 4) {
231 userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
233 $this->setViewBox($aViewbox);
235 $aRoute = $oParams->getStringList('route');
236 $fRouteWidth = $oParams->getFloat('routewidth');
237 if ($aRoute && $fRouteWidth) {
238 $this->aRoutePoints = $aRoute;
239 $this->aRouteWidth = $fRouteWidth;
244 $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
245 $this->oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', false));
248 public function setQueryFromParams($oParams)
251 $sQuery = $oParams->getString('q');
253 $this->setStructuredQuery(
254 $oParams->getString('amenity'),
255 $oParams->getString('street'),
256 $oParams->getString('city'),
257 $oParams->getString('county'),
258 $oParams->getString('state'),
259 $oParams->getString('country'),
260 $oParams->getString('postalcode')
263 $this->setQuery($sQuery);
267 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
269 $sValue = trim($sValue);
273 $this->aStructuredQuery[$sKey] = $sValue;
274 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
275 $this->iMinAddressRank = $iNewMinAddressRank;
276 $this->iMaxAddressRank = $iNewMaxAddressRank;
278 if ($aItemListValues) {
279 $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
284 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
286 $this->sQuery = false;
289 $this->iMinAddressRank = 0;
290 $this->iMaxAddressRank = 30;
291 $this->aAddressRankList = array();
293 $this->aStructuredQuery = array();
294 $this->sAllowedTypesSQLList = false;
296 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
297 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
298 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
299 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
300 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
301 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
302 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
304 if (!empty($this->aStructuredQuery)) {
305 $this->sQuery = join(', ', $this->aStructuredQuery);
306 if ($this->iMaxAddressRank < 30) {
307 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
312 public function fallbackStructuredQuery()
314 $aParams = $this->aStructuredQuery;
316 if (!$aParams || count($aParams) == 1) {
320 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
322 foreach ($aOrderToFallback as $sType) {
323 if (isset($aParams[$sType])) {
324 unset($aParams[$sType]);
325 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
333 public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens)
336 Calculate all searches using oValidTokens i.e.
337 'Wodsworth Road, Sheffield' =>
341 0 1 (wodsworth)(road)
344 Score how good the search is so they can be ordered
346 foreach ($aPhrases as $iPhrase => $oPhrase) {
347 $aNewPhraseSearches = array();
348 $sPhraseType = $oPhrase->getPhraseType();
350 foreach ($oPhrase->getWordSets() as $aWordset) {
351 $aWordsetSearches = $aSearches;
353 // Add all words from this wordset
354 foreach ($aWordset as $iToken => $sToken) {
355 $aNewWordsetSearches = array();
357 foreach ($aWordsetSearches as $oCurrentSearch) {
358 // Tokens with full name matches.
359 foreach ($oValidTokens->get(' '.$sToken) as $oSearchTerm) {
360 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
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);
402 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
403 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
405 $aSearchHash = array();
406 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
407 $sHash = serialize($aSearch);
408 if (isset($aSearchHash[$sHash])) {
409 unset($aNewPhraseSearches[$iSearch]);
411 $aSearchHash[$sHash] = 1;
415 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
418 // Re-group the searches by their score, junk anything over 20 as just not worth trying
419 $aGroupedSearches = array();
420 foreach ($aNewPhraseSearches as $aSearch) {
421 $iRank = $aSearch->getRank();
422 if ($iRank < $this->iMaxRank) {
423 if (!isset($aGroupedSearches[$iRank])) {
424 $aGroupedSearches[$iRank] = array();
426 $aGroupedSearches[$iRank][] = $aSearch;
429 ksort($aGroupedSearches);
432 $aSearches = array();
433 foreach ($aGroupedSearches as $aNewSearches) {
434 $iSearchCount += count($aNewSearches);
435 $aSearches = array_merge($aSearches, $aNewSearches);
436 if ($iSearchCount > 50) {
442 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
443 $aGroupedSearches = array();
444 foreach ($aSearches as $oSearch) {
445 if (!$oSearch->isValidSearch()) {
449 $iRank = $oSearch->getRank();
450 if (!isset($aGroupedSearches[$iRank])) {
451 $aGroupedSearches[$iRank] = array();
453 $aGroupedSearches[$iRank][] = $oSearch;
455 ksort($aGroupedSearches);
457 return $aGroupedSearches;
460 /* Perform the actual query lookup.
462 Returns an ordered list of results, each with the following fields:
463 osm_type: type of corresponding OSM object
467 P - postcode (internally computed)
468 osm_id: id of corresponding OSM object
469 class: general object class (corresponds to tag key of primary OSM tag)
470 type: subclass of object (corresponds to tag value of primary OSM tag)
471 admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
472 rank_search: rank in search hierarchy
473 (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
474 rank_address: rank in address hierarchy (determines orer in address)
475 place_id: internal key (may differ between different instances)
476 country_code: ISO country code
477 langaddress: localized full address
478 placename: localized name of object
479 ref: content of ref tag (if available)
482 importance: importance of place based on Wikipedia link count
483 addressimportance: cumulated importance of address elements
484 extra_place: type of place (for admin boundaries, if there is a place tag)
485 aBoundingBox: bounding Box
486 label: short description of the object class/type (English only)
487 name: full name (currently the same as langaddress)
488 foundorder: secondary ordering for places with same importance
492 public function lookup()
494 Debug::newFunction('Geocode::lookup');
495 if (!$this->sQuery && !$this->aStructuredQuery) {
499 Debug::printDebugArray('Geocode', $this);
501 $oCtx = new SearchContext();
503 if ($this->aRoutePoints) {
504 $oCtx->setViewboxFromRoute(
508 $this->bBoundedSearch
510 } elseif ($this->aViewBox) {
511 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
513 if ($this->aExcludePlaceIDs) {
514 $oCtx->setExcludeList($this->aExcludePlaceIDs);
516 if ($this->aCountryCodes) {
517 $oCtx->setCountryList($this->aCountryCodes);
519 $this->oTokenizer->setCountryRestriction($this->aCountryCodes);
521 Debug::newSection('Query Preprocessing');
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 $aTokens = $this->oTokenizer->tokensForSpecialTerm($sSpecialTerm);
574 if (!empty($aTokens)) {
575 $aNewSearches = array();
576 foreach ($aSearches as $oSearch) {
577 foreach ($aTokens as $oToken) {
578 $oNewSearch = clone $oSearch;
579 $oNewSearch->setPoiSearch(
584 $aNewSearches[] = $oNewSearch;
587 $aSearches = $aNewSearches;
591 // Split query into phrases
592 // Commas are used to reduce the search space by indicating where phrases split
594 if ($this->aStructuredQuery) {
595 foreach ($this->aStructuredQuery as $iPhrase => $sPhrase) {
596 $aPhrases[] = new Phrase($sPhrase, $iPhrase);
599 foreach (explode(',', $sQuery) as $sPhrase) {
600 $aPhrases[] = new Phrase($sPhrase, '');
604 Debug::printDebugArray('Search context', $oCtx);
605 Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
607 Debug::newSection('Tokenization');
608 $oValidTokens = $this->oTokenizer->extractTokensFromPhrases($aPhrases);
610 if ($oValidTokens->count() > 0) {
611 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
613 $aPhrases = array_filter($aPhrases, function ($oPhrase) {
614 return $oPhrase->getWordSets() !== null;
617 // Any words that have failed completely?
620 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
621 Debug::printDebugTable('Phrases', $aPhrases);
623 Debug::newSection('Search candidates');
625 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
627 if (!$this->aStructuredQuery) {
628 // Reverse phrase array and also reverse the order of the wordsets in
629 // the first and final phrase. Don't bother about phrases in the middle
630 // because order in the address doesn't matter.
631 $aPhrases = array_reverse($aPhrases);
632 $aPhrases[0]->invertWordSets();
633 if (count($aPhrases) > 1) {
634 $aPhrases[count($aPhrases)-1]->invertWordSets();
636 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
638 foreach ($aGroupedSearches as $aSearches) {
639 foreach ($aSearches as $aSearch) {
640 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
641 $aReverseGroupedSearches[$aSearch->getRank()] = array();
643 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
647 $aGroupedSearches = $aReverseGroupedSearches;
648 ksort($aGroupedSearches);
651 // Re-group the searches by their score, junk anything over 20 as just not worth trying
652 $aGroupedSearches = array();
653 foreach ($aSearches as $aSearch) {
654 if ($aSearch->getRank() < $this->iMaxRank) {
655 if (!isset($aGroupedSearches[$aSearch->getRank()])) {
656 $aGroupedSearches[$aSearch->getRank()] = array();
658 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
661 ksort($aGroupedSearches);
664 // Filter out duplicate searches
665 $aSearchHash = array();
666 foreach ($aGroupedSearches as $iGroup => $aSearches) {
667 foreach ($aSearches as $iSearch => $aSearch) {
668 $sHash = serialize($aSearch);
669 if (isset($aSearchHash[$sHash])) {
670 unset($aGroupedSearches[$iGroup][$iSearch]);
671 if (empty($aGroupedSearches[$iGroup])) {
672 unset($aGroupedSearches[$iGroup]);
675 $aSearchHash[$sHash] = 1;
680 Debug::printGroupedSearch(
682 $oValidTokens->debugTokenByWordIdList()
685 // Start the search process
688 $aNextResults = array();
689 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
691 $aResults = $aNextResults;
692 foreach ($aSearches as $oSearch) {
695 Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
696 Debug::printGroupedSearch(
697 array($iGroupedRank => array($oSearch)),
698 $oValidTokens->debugTokenByWordIdList()
701 $aNewResults = $oSearch->query(
703 $this->iMinAddressRank,
704 $this->iMaxAddressRank,
708 // The same result may appear in different rounds, only
709 // use the one with minimal rank.
710 foreach ($aNewResults as $iPlace => $oRes) {
711 if (!isset($aResults[$iPlace])
712 || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
713 $aResults[$iPlace] = $oRes;
717 if ($iQueryLoop > 20) {
722 if (!empty($aResults)) {
723 $aSplitResults = Result::splitResults($aResults);
724 Debug::printVar('Split results', $aSplitResults);
726 && reset($aSplitResults['head'])->iResultRank > 0
727 && $iGroupedRank !== array_key_last($aGroupedSearches)) {
728 // Haven't found an exact match for the query yet.
729 // Therefore add result from the next group level.
730 $aNextResults = $aSplitResults['head'];
731 foreach ($aNextResults as $oRes) {
732 $oRes->iResultRank--;
734 foreach ($aSplitResults['tail'] as $oRes) {
735 $oRes->iResultRank--;
736 $aNextResults[$oRes->iId] = $oRes;
740 $aResults = $aSplitResults['head'];
744 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
745 // Need to verify passes rank limits before dropping out of the loop (yuk!)
746 // reduces the number of place ids, like a filter
747 // rank_address is 30 for interpolated housenumbers
748 $aFilterSql = array();
749 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
751 $sSQL = 'SELECT place_id FROM placex ';
752 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
754 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
755 $sSQL .= " OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
756 if ($this->aAddressRankList) {
757 $sSQL .= ' OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
760 $aFilterSql[] = $sSQL;
762 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
764 $sSQL = ' SELECT place_id FROM location_postcode lp ';
765 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
766 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
767 if ($this->aAddressRankList) {
768 $sSQL .= ' OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
771 $aFilterSql[] = $sSQL;
774 $aFilteredIDs = array();
776 $sSQL = join(' UNION ', $aFilterSql);
777 Debug::printSQL($sSQL);
778 $aFilteredIDs = $this->oDB->getCol($sSQL);
782 foreach ($aResults as $oResult) {
783 if (($this->iMaxAddressRank == 30 &&
784 ($oResult->iTable == Result::TABLE_OSMLINE
785 || $oResult->iTable == Result::TABLE_TIGER))
786 || in_array($oResult->iId, $aFilteredIDs)
788 $tempIDs[$oResult->iId] = $oResult;
791 $aResults = $tempIDs;
794 if (!empty($aResults) || $iGroupLoop > 4 || $iQueryLoop > 30) {
799 // Just interpret as a reverse geocode
800 $oReverse = new ReverseGeocode($this->oDB);
801 $oReverse->setZoom(18);
803 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
805 Debug::printVar('Reverse search', $oLookup);
808 $aResults = array($oLookup->iId => $oLookup);
813 if (empty($aResults)) {
814 if ($this->bFallback && $this->fallbackStructuredQuery()) {
815 return $this->lookup();
821 if ($this->aAddressRankList) {
822 $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
824 $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
825 $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
826 if ($oCtx->hasNearPoint()) {
827 $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
830 $aSearchResults = $this->oPlaceLookup->lookup($aResults);
832 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
833 foreach ($aRecheckWords as $i => $sWord) {
834 if (!preg_match('/[\pL\pN]/', $sWord)) {
835 unset($aRecheckWords[$i]);
839 Debug::printVar('Recheck words', $aRecheckWords);
841 foreach ($aSearchResults as $iIdx => $aResult) {
842 $fRadius = ClassTypes\getDefRadius($aResult);
844 $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fRadius);
845 if ($aOutlineResult) {
846 $aResult = array_merge($aResult, $aOutlineResult);
849 // Is there an icon set for this type of result?
850 $sIcon = ClassTypes\getIconFile($aResult);
852 $aResult['icon'] = $sIcon;
855 $sLabel = ClassTypes\getLabel($aResult);
856 if (isset($sLabel)) {
857 $aResult['label'] = $sLabel;
859 $aResult['name'] = $aResult['langaddress'];
861 if ($oCtx->hasNearPoint()) {
862 $aResult['importance'] = 0.001;
863 $aResult['foundorder'] = $aResult['addressimportance'];
865 $aResult['importance'] = max(0.001, $aResult['importance']);
866 $aResult['importance'] *= $this->viewboxImportanceFactor(
871 // secondary ordering (for results with same importance (the smaller the better):
872 // - approximate importance of address parts
873 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
874 $aResult['foundorder'] = -$aResult['addressimportance']/10;
876 $aResult['foundorder'] = -$aResult['importance'];
878 // - number of exact matches from the query
879 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
880 // - importance of the class/type
881 $iClassImportance = ClassTypes\getImportance($aResult);
882 if (isset($iClassImportance)) {
883 $aResult['foundorder'] += 0.0001 * $iClassImportance;
885 $aResult['foundorder'] += 0.01;
888 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
890 // Adjust importance for the number of exact string matches in the result
892 $sAddress = $aResult['langaddress'];
893 foreach ($aRecheckWords as $i => $sWord) {
894 if (stripos($sAddress, $sWord)!==false) {
896 if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) {
902 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
903 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
905 $aSearchResults[$iIdx] = $aResult;
907 uasort($aSearchResults, 'byImportance');
908 Debug::printVar('Pre-filter results', $aSearchResults);
910 $aOSMIDDone = array();
911 $aClassTypeNameDone = array();
912 $aToFilter = $aSearchResults;
913 $aSearchResults = array();
915 foreach ($aToFilter as $aResult) {
916 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
917 if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
918 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
920 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
921 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
922 $aSearchResults[] = $aResult;
925 // Absolute limit on number of results
926 if (count($aSearchResults) >= $this->iFinalLimit) {
931 Debug::printVar('Post-filter results', $aSearchResults);
932 return $aSearchResults;
935 public function debugInfo()
938 'Query' => $this->sQuery,
939 'Structured query' => $this->aStructuredQuery,
940 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
941 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
942 'Limit (for searches)' => $this->iLimit,
943 'Limit (for results)'=> $this->iFinalLimit,
944 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
945 'Bounded search' => $this->bBoundedSearch,
946 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
947 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
948 'Route width' => $this->aRouteWidth,
949 'Max rank' => $this->iMaxRank,
950 'Min address rank' => $this->iMinAddressRank,
951 'Max address rank' => $this->iMaxAddressRank,
952 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)