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.'/SearchPosition.php');
11 require_once(CONST_LibDir.'/TokenList.php');
12 require_once(CONST_TokenizerDir.'/tokenizer.php');
18 protected $oPlaceLookup;
19 protected $oTokenizer;
21 protected $aLangPrefOrder = array();
23 protected $aExcludePlaceIDs = array();
25 protected $iLimit = 20;
26 protected $iFinalLimit = 10;
27 protected $iOffset = 0;
28 protected $bFallback = false;
30 protected $aCountryCodes = false;
32 protected $bBoundedSearch = false;
33 protected $aViewBox = false;
34 protected $aRoutePoints = false;
35 protected $aRouteWidth = false;
37 protected $iMaxRank = 20;
38 protected $iMinAddressRank = 0;
39 protected $iMaxAddressRank = 30;
40 protected $aAddressRankList = array();
42 protected $sAllowedTypesSQLList = false;
44 protected $sQuery = false;
45 protected $aStructuredQuery = false;
48 public function __construct(&$oDB)
51 $this->oPlaceLookup = new PlaceLookup($this->oDB);
52 $this->oTokenizer = new \Nominatim\Tokenizer($this->oDB);
55 public function setLanguagePreference($aLangPref)
57 $this->aLangPrefOrder = $aLangPref;
60 public function getMoreUrlParams()
62 if ($this->aStructuredQuery) {
63 $aParams = $this->aStructuredQuery;
65 $aParams = array('q' => $this->sQuery);
68 $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
70 if ($this->aExcludePlaceIDs) {
71 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
74 if ($this->bBoundedSearch) {
75 $aParams['bounded'] = '1';
78 if ($this->aCountryCodes) {
79 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
82 if ($this->aViewBox) {
83 $aParams['viewbox'] = join(',', $this->aViewBox);
89 public function setLimit($iLimit = 10)
93 } elseif ($iLimit < 1) {
97 $this->iFinalLimit = $iLimit;
98 $this->iLimit = $iLimit + min($iLimit, 10);
101 public function setFeatureType($sFeatureType)
103 switch ($sFeatureType) {
105 $this->setRankRange(4, 4);
108 $this->setRankRange(8, 8);
111 $this->setRankRange(14, 16);
114 $this->setRankRange(8, 20);
119 public function setRankRange($iMin, $iMax)
121 $this->iMinAddressRank = $iMin;
122 $this->iMaxAddressRank = $iMax;
125 public function setViewbox($aViewbox)
127 $aBox = array_map('floatval', $aViewbox);
129 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
130 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
131 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
132 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
134 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
135 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
137 userError("Bad parameter 'viewbox'. Not a box.");
141 private function viewboxImportanceFactor($fX, $fY)
143 if (!$this->aViewBox) {
147 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
148 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
150 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
151 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
153 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
157 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
164 public function setQuery($sQueryString)
166 $this->sQuery = $sQueryString;
167 $this->aStructuredQuery = false;
170 public function getQueryString()
172 return $this->sQuery;
176 public function loadParamArray($oParams, $sForceGeometryType = null)
178 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
180 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
181 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
183 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
185 // List of excluded Place IDs - used for more acurate pageing
186 $sExcluded = $oParams->getStringList('exclude_place_ids');
188 foreach ($sExcluded as $iExcludedPlaceID) {
189 $iExcludedPlaceID = (int)$iExcludedPlaceID;
190 if ($iExcludedPlaceID) {
191 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
195 if (isset($aExcludePlaceIDs)) {
196 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
200 // Only certain ranks of feature
201 $sFeatureType = $oParams->getString('featureType');
202 if (!$sFeatureType) {
203 $sFeatureType = $oParams->getString('featuretype');
206 $this->setFeatureType($sFeatureType);
210 $sCountries = $oParams->getStringList('countrycodes');
212 foreach ($sCountries as $sCountryCode) {
213 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
214 $aCountries[] = strtolower($sCountryCode);
217 if (isset($aCountries)) {
218 $this->aCountryCodes = $aCountries;
222 $aViewbox = $oParams->getStringList('viewboxlbrt');
224 if (count($aViewbox) != 4) {
225 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
227 $this->setViewbox($aViewbox);
229 $aViewbox = $oParams->getStringList('viewbox');
231 if (count($aViewbox) != 4) {
232 userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
234 $this->setViewBox($aViewbox);
236 $aRoute = $oParams->getStringList('route');
237 $fRouteWidth = $oParams->getFloat('routewidth');
238 if ($aRoute && $fRouteWidth) {
239 $this->aRoutePoints = $aRoute;
240 $this->aRouteWidth = $fRouteWidth;
245 $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
246 $this->oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', false));
249 public function setQueryFromParams($oParams)
252 $sQuery = $oParams->getString('q');
254 $this->setStructuredQuery(
255 $oParams->getString('amenity'),
256 $oParams->getString('street'),
257 $oParams->getString('city'),
258 $oParams->getString('county'),
259 $oParams->getString('state'),
260 $oParams->getString('country'),
261 $oParams->getString('postalcode')
264 $this->setQuery($sQuery);
268 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
270 $sValue = trim($sValue);
274 $this->aStructuredQuery[$sKey] = $sValue;
275 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
276 $this->iMinAddressRank = $iNewMinAddressRank;
277 $this->iMaxAddressRank = $iNewMaxAddressRank;
279 if ($aItemListValues) {
280 $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
285 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
287 $this->sQuery = false;
290 $this->iMinAddressRank = 0;
291 $this->iMaxAddressRank = 30;
292 $this->aAddressRankList = array();
294 $this->aStructuredQuery = array();
295 $this->sAllowedTypesSQLList = false;
297 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
298 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
299 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
300 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
301 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
302 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
303 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
305 if (!empty($this->aStructuredQuery)) {
306 $this->sQuery = join(', ', $this->aStructuredQuery);
307 if ($this->iMaxAddressRank < 30) {
308 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
313 public function fallbackStructuredQuery()
315 $aParams = $this->aStructuredQuery;
317 if (!$aParams || count($aParams) == 1) {
321 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
323 foreach ($aOrderToFallback as $sType) {
324 if (isset($aParams[$sType])) {
325 unset($aParams[$sType]);
326 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
334 public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens)
337 Calculate all searches using oValidTokens i.e.
338 'Wodsworth Road, Sheffield' =>
342 0 1 (wodsworth)(road)
345 Score how good the search is so they can be ordered
347 foreach ($aPhrases as $iPhrase => $oPhrase) {
348 $aNewPhraseSearches = array();
349 $oPosition = new SearchPosition(
350 $oPhrase->getPhraseType(),
355 foreach ($oPhrase->getWordSets() as $aWordset) {
356 $aWordsetSearches = $aSearches;
358 // Add all words from this wordset
359 foreach ($aWordset as $iToken => $sToken) {
360 $aNewWordsetSearches = array();
361 $oPosition->setTokenPosition($iToken, count($aWordset));
363 foreach ($aWordsetSearches as $oCurrentSearch) {
364 foreach ($oValidTokens->get($sToken) as $oSearchTerm) {
365 $aNewSearches = $oSearchTerm->extendSearch(
370 foreach ($aNewSearches as $oSearch) {
371 if ($oSearch->getRank() < $this->iMaxRank) {
372 $aNewWordsetSearches[] = $oSearch;
378 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
379 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
382 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
383 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
385 $aSearchHash = array();
386 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
387 $sHash = serialize($aSearch);
388 if (isset($aSearchHash[$sHash])) {
389 unset($aNewPhraseSearches[$iSearch]);
391 $aSearchHash[$sHash] = 1;
395 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
398 // Re-group the searches by their score, junk anything over 20 as just not worth trying
399 $aGroupedSearches = array();
400 foreach ($aNewPhraseSearches as $aSearch) {
401 $iRank = $aSearch->getRank();
402 if ($iRank < $this->iMaxRank) {
403 if (!isset($aGroupedSearches[$iRank])) {
404 $aGroupedSearches[$iRank] = array();
406 $aGroupedSearches[$iRank][] = $aSearch;
409 ksort($aGroupedSearches);
412 $aSearches = array();
413 foreach ($aGroupedSearches as $aNewSearches) {
414 $iSearchCount += count($aNewSearches);
415 $aSearches = array_merge($aSearches, $aNewSearches);
416 if ($iSearchCount > 50) {
422 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
423 $aGroupedSearches = array();
424 foreach ($aSearches as $oSearch) {
425 if (!$oSearch->isValidSearch()) {
429 $iRank = $oSearch->getRank();
430 if (!isset($aGroupedSearches[$iRank])) {
431 $aGroupedSearches[$iRank] = array();
433 $aGroupedSearches[$iRank][] = $oSearch;
435 ksort($aGroupedSearches);
437 return $aGroupedSearches;
440 /* Perform the actual query lookup.
442 Returns an ordered list of results, each with the following fields:
443 osm_type: type of corresponding OSM object
447 P - postcode (internally computed)
448 osm_id: id of corresponding OSM object
449 class: general object class (corresponds to tag key of primary OSM tag)
450 type: subclass of object (corresponds to tag value of primary OSM tag)
451 admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
452 rank_search: rank in search hierarchy
453 (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
454 rank_address: rank in address hierarchy (determines orer in address)
455 place_id: internal key (may differ between different instances)
456 country_code: ISO country code
457 langaddress: localized full address
458 placename: localized name of object
459 ref: content of ref tag (if available)
462 importance: importance of place based on Wikipedia link count
463 addressimportance: cumulated importance of address elements
464 extra_place: type of place (for admin boundaries, if there is a place tag)
465 aBoundingBox: bounding Box
466 label: short description of the object class/type (English only)
467 name: full name (currently the same as langaddress)
468 foundorder: secondary ordering for places with same importance
472 public function lookup()
474 Debug::newFunction('Geocode::lookup');
475 if (!$this->sQuery && !$this->aStructuredQuery) {
479 Debug::printDebugArray('Geocode', $this);
481 $oCtx = new SearchContext();
483 if ($this->aRoutePoints) {
484 $oCtx->setViewboxFromRoute(
488 $this->bBoundedSearch
490 } elseif ($this->aViewBox) {
491 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
493 if ($this->aExcludePlaceIDs) {
494 $oCtx->setExcludeList($this->aExcludePlaceIDs);
496 if ($this->aCountryCodes) {
497 $oCtx->setCountryList($this->aCountryCodes);
499 $this->oTokenizer->setCountryRestriction($this->aCountryCodes);
501 Debug::newSection('Query Preprocessing');
503 $sQuery = $this->sQuery;
504 if (!preg_match('//u', $sQuery)) {
505 userError('Query string is not UTF-8 encoded.');
508 // Conflicts between US state abreviations and various words for 'the' in different languages
509 if (isset($this->aLangPrefOrder['name:en'])) {
510 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
511 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
512 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
515 // Do we have anything that looks like a lat/lon pair?
516 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
518 if ($sQuery || $this->aStructuredQuery) {
519 // Start with a single blank search
520 $aSearches = array(new SearchDescription($oCtx));
523 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
529 '/\\[([\\w ]*)\\]/u',
534 if (!empty($aSpecialTermsRaw)) {
535 Debug::printVar('Special terms', $aSpecialTermsRaw);
538 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
539 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
540 if (!$sSpecialTerm) {
541 $sSpecialTerm = $aSpecialTerm[1];
545 if (!$sSpecialTerm && $this->aStructuredQuery
546 && isset($this->aStructuredQuery['amenity'])) {
547 $sSpecialTerm = $this->aStructuredQuery['amenity'];
548 unset($this->aStructuredQuery['amenity']);
551 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
552 $aTokens = $this->oTokenizer->tokensForSpecialTerm($sSpecialTerm);
554 if (!empty($aTokens)) {
555 $aNewSearches = array();
556 foreach ($aSearches as $oSearch) {
557 foreach ($aTokens as $oToken) {
558 $oNewSearch = clone $oSearch;
559 $oNewSearch->setPoiSearch(
564 $aNewSearches[] = $oNewSearch;
567 $aSearches = $aNewSearches;
571 // Split query into phrases
572 // Commas are used to reduce the search space by indicating where phrases split
574 if ($this->aStructuredQuery) {
575 foreach ($this->aStructuredQuery as $iPhrase => $sPhrase) {
576 $aPhrases[] = new Phrase($sPhrase, $iPhrase);
579 foreach (explode(',', $sQuery) as $sPhrase) {
580 $aPhrases[] = new Phrase($sPhrase, '');
584 Debug::printDebugArray('Search context', $oCtx);
585 Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
587 Debug::newSection('Tokenization');
588 $oValidTokens = $this->oTokenizer->extractTokensFromPhrases($aPhrases);
590 if ($oValidTokens->count() > 0) {
591 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
593 $aPhrases = array_filter($aPhrases, function ($oPhrase) {
594 return $oPhrase->getWordSets() !== null;
597 // Any words that have failed completely?
600 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
601 Debug::printDebugTable('Phrases', $aPhrases);
603 Debug::newSection('Search candidates');
605 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
607 if (!$this->aStructuredQuery) {
608 // Reverse phrase array and also reverse the order of the wordsets in
609 // the first and final phrase. Don't bother about phrases in the middle
610 // because order in the address doesn't matter.
611 $aPhrases = array_reverse($aPhrases);
612 $aPhrases[0]->invertWordSets();
613 if (count($aPhrases) > 1) {
614 $aPhrases[count($aPhrases)-1]->invertWordSets();
616 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
618 foreach ($aGroupedSearches as $aSearches) {
619 foreach ($aSearches as $aSearch) {
620 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
621 $aReverseGroupedSearches[$aSearch->getRank()] = array();
623 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
627 $aGroupedSearches = $aReverseGroupedSearches;
628 ksort($aGroupedSearches);
631 // Re-group the searches by their score, junk anything over 20 as just not worth trying
632 $aGroupedSearches = array();
633 foreach ($aSearches as $aSearch) {
634 if ($aSearch->getRank() < $this->iMaxRank) {
635 if (!isset($aGroupedSearches[$aSearch->getRank()])) {
636 $aGroupedSearches[$aSearch->getRank()] = array();
638 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
641 ksort($aGroupedSearches);
644 // Filter out duplicate searches
645 $aSearchHash = array();
646 foreach ($aGroupedSearches as $iGroup => $aSearches) {
647 foreach ($aSearches as $iSearch => $aSearch) {
648 $sHash = serialize($aSearch);
649 if (isset($aSearchHash[$sHash])) {
650 unset($aGroupedSearches[$iGroup][$iSearch]);
651 if (empty($aGroupedSearches[$iGroup])) {
652 unset($aGroupedSearches[$iGroup]);
655 $aSearchHash[$sHash] = 1;
660 Debug::printGroupedSearch(
662 $oValidTokens->debugTokenByWordIdList()
665 // Start the search process
668 $aNextResults = array();
669 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
671 $aResults = $aNextResults;
672 foreach ($aSearches as $oSearch) {
675 Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
676 Debug::printGroupedSearch(
677 array($iGroupedRank => array($oSearch)),
678 $oValidTokens->debugTokenByWordIdList()
681 $aNewResults = $oSearch->query(
683 $this->iMinAddressRank,
684 $this->iMaxAddressRank,
688 // The same result may appear in different rounds, only
689 // use the one with minimal rank.
690 foreach ($aNewResults as $iPlace => $oRes) {
691 if (!isset($aResults[$iPlace])
692 || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
693 $aResults[$iPlace] = $oRes;
697 if ($iQueryLoop > 20) {
702 if (!empty($aResults)) {
703 $aSplitResults = Result::splitResults($aResults);
704 Debug::printVar('Split results', $aSplitResults);
706 && reset($aSplitResults['head'])->iResultRank > 0
707 && $iGroupedRank !== array_key_last($aGroupedSearches)) {
708 // Haven't found an exact match for the query yet.
709 // Therefore add result from the next group level.
710 $aNextResults = $aSplitResults['head'];
711 foreach ($aNextResults as $oRes) {
712 $oRes->iResultRank--;
714 foreach ($aSplitResults['tail'] as $oRes) {
715 $oRes->iResultRank--;
716 $aNextResults[$oRes->iId] = $oRes;
720 $aResults = $aSplitResults['head'];
724 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
725 // Need to verify passes rank limits before dropping out of the loop (yuk!)
726 // reduces the number of place ids, like a filter
727 // rank_address is 30 for interpolated housenumbers
728 $aFilterSql = array();
729 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
731 $sSQL = 'SELECT place_id FROM placex ';
732 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
734 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
735 $sSQL .= " OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
736 if ($this->aAddressRankList) {
737 $sSQL .= ' OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
740 $aFilterSql[] = $sSQL;
742 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
744 $sSQL = ' SELECT place_id FROM location_postcode lp ';
745 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
746 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
747 if ($this->aAddressRankList) {
748 $sSQL .= ' OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
751 $aFilterSql[] = $sSQL;
754 $aFilteredIDs = array();
756 $sSQL = join(' UNION ', $aFilterSql);
757 Debug::printSQL($sSQL);
758 $aFilteredIDs = $this->oDB->getCol($sSQL);
762 foreach ($aResults as $oResult) {
763 if (($this->iMaxAddressRank == 30 &&
764 ($oResult->iTable == Result::TABLE_OSMLINE
765 || $oResult->iTable == Result::TABLE_TIGER))
766 || in_array($oResult->iId, $aFilteredIDs)
768 $tempIDs[$oResult->iId] = $oResult;
771 $aResults = $tempIDs;
774 if (!empty($aResults) || $iGroupLoop > 4 || $iQueryLoop > 30) {
779 // Just interpret as a reverse geocode
780 $oReverse = new ReverseGeocode($this->oDB);
781 $oReverse->setZoom(18);
783 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
785 Debug::printVar('Reverse search', $oLookup);
788 $aResults = array($oLookup->iId => $oLookup);
793 if (empty($aResults)) {
794 if ($this->bFallback && $this->fallbackStructuredQuery()) {
795 return $this->lookup();
801 if ($this->aAddressRankList) {
802 $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
804 $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
805 $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
806 if ($oCtx->hasNearPoint()) {
807 $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
810 $aSearchResults = $this->oPlaceLookup->lookup($aResults);
812 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
813 foreach ($aRecheckWords as $i => $sWord) {
814 if (!preg_match('/[\pL\pN]/', $sWord)) {
815 unset($aRecheckWords[$i]);
819 Debug::printVar('Recheck words', $aRecheckWords);
821 foreach ($aSearchResults as $iIdx => $aResult) {
822 $fRadius = ClassTypes\getDefRadius($aResult);
824 $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fRadius);
825 if ($aOutlineResult) {
826 $aResult = array_merge($aResult, $aOutlineResult);
829 // Is there an icon set for this type of result?
830 $sIcon = ClassTypes\getIconFile($aResult);
832 $aResult['icon'] = $sIcon;
835 $sLabel = ClassTypes\getLabel($aResult);
836 if (isset($sLabel)) {
837 $aResult['label'] = $sLabel;
839 $aResult['name'] = $aResult['langaddress'];
841 if ($oCtx->hasNearPoint()) {
842 $aResult['importance'] = 0.001;
843 $aResult['foundorder'] = $aResult['addressimportance'];
845 $aResult['importance'] = max(0.001, $aResult['importance']);
846 $aResult['importance'] *= $this->viewboxImportanceFactor(
851 // secondary ordering (for results with same importance (the smaller the better):
852 // - approximate importance of address parts
853 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
854 $aResult['foundorder'] = -$aResult['addressimportance']/10;
856 $aResult['foundorder'] = -$aResult['importance'];
858 // - number of exact matches from the query
859 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
860 // - importance of the class/type
861 $iClassImportance = ClassTypes\getImportance($aResult);
862 if (isset($iClassImportance)) {
863 $aResult['foundorder'] += 0.0001 * $iClassImportance;
865 $aResult['foundorder'] += 0.01;
868 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
870 // Adjust importance for the number of exact string matches in the result
872 $sAddress = $aResult['langaddress'];
873 foreach ($aRecheckWords as $i => $sWord) {
874 if (stripos($sAddress, $sWord)!==false) {
876 if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) {
882 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
883 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
885 $aSearchResults[$iIdx] = $aResult;
887 uasort($aSearchResults, 'byImportance');
888 Debug::printVar('Pre-filter results', $aSearchResults);
890 $aOSMIDDone = array();
891 $aClassTypeNameDone = array();
892 $aToFilter = $aSearchResults;
893 $aSearchResults = array();
895 foreach ($aToFilter as $aResult) {
896 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
897 if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
898 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
900 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
901 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
902 $aSearchResults[] = $aResult;
905 // Absolute limit on number of results
906 if (count($aSearchResults) >= $this->iFinalLimit) {
911 Debug::printVar('Post-filter results', $aSearchResults);
912 return $aSearchResults;
915 public function debugInfo()
918 'Query' => $this->sQuery,
919 'Structured query' => $this->aStructuredQuery,
920 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
921 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
922 'Limit (for searches)' => $this->iLimit,
923 'Limit (for results)'=> $this->iFinalLimit,
924 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
925 'Bounded search' => $this->bBoundedSearch,
926 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
927 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
928 'Route width' => $this->aRouteWidth,
929 'Max rank' => $this->iMaxRank,
930 'Min address rank' => $this->iMinAddressRank,
931 'Max address rank' => $this->iMaxAddressRank,
932 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)