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) $aParams['bounded'] = '1';
75 if ($this->aCountryCodes) {
76 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
79 if ($this->aViewBox) {
80 $aParams['viewbox'] = join(',', $this->aViewBox);
86 public function setLimit($iLimit = 10)
88 if ($iLimit > 50) $iLimit = 50;
89 if ($iLimit < 1) $iLimit = 1;
91 $this->iFinalLimit = $iLimit;
92 $this->iLimit = $iLimit + min($iLimit, 10);
95 public function setFeatureType($sFeatureType)
97 switch ($sFeatureType) {
99 $this->setRankRange(4, 4);
102 $this->setRankRange(8, 8);
105 $this->setRankRange(14, 16);
108 $this->setRankRange(8, 20);
113 public function setRankRange($iMin, $iMax)
115 $this->iMinAddressRank = $iMin;
116 $this->iMaxAddressRank = $iMax;
119 public function setViewbox($aViewbox)
121 $aBox = array_map('floatval', $aViewbox);
123 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
124 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
125 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
126 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
128 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
129 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
131 userError("Bad parameter 'viewbox'. Not a box.");
135 private function viewboxImportanceFactor($fX, $fY)
137 if (!$this->aViewBox) {
141 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
142 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
144 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
145 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
147 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
151 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
158 public function setQuery($sQueryString)
160 $this->sQuery = $sQueryString;
161 $this->aStructuredQuery = false;
164 public function getQueryString()
166 return $this->sQuery;
170 public function loadParamArray($oParams, $sForceGeometryType = null)
172 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
174 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
175 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
177 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
179 // List of excluded Place IDs - used for more acurate pageing
180 $sExcluded = $oParams->getStringList('exclude_place_ids');
182 foreach ($sExcluded as $iExcludedPlaceID) {
183 $iExcludedPlaceID = (int)$iExcludedPlaceID;
184 if ($iExcludedPlaceID)
185 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
188 if (isset($aExcludePlaceIDs))
189 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
192 // Only certain ranks of feature
193 $sFeatureType = $oParams->getString('featureType');
194 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
195 if ($sFeatureType) $this->setFeatureType($sFeatureType);
198 $sCountries = $oParams->getStringList('countrycodes');
200 foreach ($sCountries as $sCountryCode) {
201 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
202 $aCountries[] = strtolower($sCountryCode);
205 if (isset($aCountries))
206 $this->aCountryCodes = $aCountries;
209 $aViewbox = $oParams->getStringList('viewboxlbrt');
211 if (count($aViewbox) != 4) {
212 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
214 $this->setViewbox($aViewbox);
216 $aViewbox = $oParams->getStringList('viewbox');
218 if (count($aViewbox) != 4) {
219 userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
221 $this->setViewBox($aViewbox);
223 $aRoute = $oParams->getStringList('route');
224 $fRouteWidth = $oParams->getFloat('routewidth');
225 if ($aRoute && $fRouteWidth) {
226 $this->aRoutePoints = $aRoute;
227 $this->aRouteWidth = $fRouteWidth;
232 $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
233 $this->oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', false));
236 public function setQueryFromParams($oParams)
239 $sQuery = $oParams->getString('q');
241 $this->setStructuredQuery(
242 $oParams->getString('amenity'),
243 $oParams->getString('street'),
244 $oParams->getString('city'),
245 $oParams->getString('county'),
246 $oParams->getString('state'),
247 $oParams->getString('country'),
248 $oParams->getString('postalcode')
251 $this->setQuery($sQuery);
255 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
257 $sValue = trim($sValue);
258 if (!$sValue) return false;
259 $this->aStructuredQuery[$sKey] = $sValue;
260 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
261 $this->iMinAddressRank = $iNewMinAddressRank;
262 $this->iMaxAddressRank = $iNewMaxAddressRank;
264 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
268 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
270 $this->sQuery = false;
273 $this->iMinAddressRank = 0;
274 $this->iMaxAddressRank = 30;
275 $this->aAddressRankList = array();
277 $this->aStructuredQuery = array();
278 $this->sAllowedTypesSQLList = false;
280 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
281 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
282 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
283 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
284 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
285 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
286 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
288 if (!empty($this->aStructuredQuery)) {
289 $this->sQuery = join(', ', $this->aStructuredQuery);
290 if ($this->iMaxAddressRank < 30) {
291 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
296 public function fallbackStructuredQuery()
298 if (!$this->aStructuredQuery) return false;
300 $aParams = $this->aStructuredQuery;
302 if (count($aParams) == 1) return false;
304 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
306 foreach ($aOrderToFallback as $sType) {
307 if (isset($aParams[$sType])) {
308 unset($aParams[$sType]);
309 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
317 public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens)
320 Calculate all searches using oValidTokens i.e.
321 'Wodsworth Road, Sheffield' =>
325 0 1 (wodsworth)(road)
328 Score how good the search is so they can be ordered
330 foreach ($aPhrases as $iPhrase => $oPhrase) {
331 $aNewPhraseSearches = array();
332 $sPhraseType = $oPhrase->getPhraseType();
334 foreach ($oPhrase->getWordSets() as $aWordset) {
335 $aWordsetSearches = $aSearches;
337 // Add all words from this wordset
338 foreach ($aWordset as $iToken => $sToken) {
339 //echo "<br><b>$sToken</b>";
340 $aNewWordsetSearches = array();
342 foreach ($aWordsetSearches as $oCurrentSearch) {
344 //var_dump($oCurrentSearch);
347 // Tokens with full name matches.
348 foreach ($oValidTokens->get(' '.$sToken) as $oSearchTerm) {
349 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
352 $iToken == 0 && $iPhrase == 0,
354 $iToken + 1 == count($aWordset)
355 && $iPhrase + 1 == count($aPhrases)
358 foreach ($aNewSearches as $oSearch) {
359 if ($oSearch->getRank() < $this->iMaxRank) {
360 $aNewWordsetSearches[] = $oSearch;
364 // Look for partial matches.
365 // Note that there is no point in adding country terms here
366 // because country is omitted in the address.
367 if ($sPhraseType != 'country') {
368 // Allow searching for a word - but at extra cost
369 foreach ($oValidTokens->get($sToken) as $oSearchTerm) {
370 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
375 $oValidTokens->get(' '.$sToken)
378 foreach ($aNewSearches as $oSearch) {
379 if ($oSearch->getRank() < $this->iMaxRank) {
380 $aNewWordsetSearches[] = $oSearch;
387 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
388 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
390 //var_Dump('<hr>',count($aWordsetSearches)); exit;
392 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
393 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
395 $aSearchHash = array();
396 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
397 $sHash = serialize($aSearch);
398 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
399 else $aSearchHash[$sHash] = 1;
402 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
405 // Re-group the searches by their score, junk anything over 20 as just not worth trying
406 $aGroupedSearches = array();
407 foreach ($aNewPhraseSearches as $aSearch) {
408 $iRank = $aSearch->getRank();
409 if ($iRank < $this->iMaxRank) {
410 if (!isset($aGroupedSearches[$iRank])) {
411 $aGroupedSearches[$iRank] = array();
413 $aGroupedSearches[$iRank][] = $aSearch;
416 ksort($aGroupedSearches);
419 $aSearches = array();
420 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
421 $iSearchCount += count($aNewSearches);
422 $aSearches = array_merge($aSearches, $aNewSearches);
423 if ($iSearchCount > 50) break;
427 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
428 $aGroupedSearches = array();
429 foreach ($aSearches as $oSearch) {
430 if (!$oSearch->isValidSearch()) {
434 $iRank = $oSearch->getRank();
435 if (!isset($aGroupedSearches[$iRank])) {
436 $aGroupedSearches[$iRank] = array();
438 $aGroupedSearches[$iRank][] = $oSearch;
440 ksort($aGroupedSearches);
442 return $aGroupedSearches;
445 /* Perform the actual query lookup.
447 Returns an ordered list of results, each with the following fields:
448 osm_type: type of corresponding OSM object
452 P - postcode (internally computed)
453 osm_id: id of corresponding OSM object
454 class: general object class (corresponds to tag key of primary OSM tag)
455 type: subclass of object (corresponds to tag value of primary OSM tag)
456 admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
457 rank_search: rank in search hierarchy
458 (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
459 rank_address: rank in address hierarchy (determines orer in address)
460 place_id: internal key (may differ between different instances)
461 country_code: ISO country code
462 langaddress: localized full address
463 placename: localized name of object
464 ref: content of ref tag (if available)
467 importance: importance of place based on Wikipedia link count
468 addressimportance: cumulated importance of address elements
469 extra_place: type of place (for admin boundaries, if there is a place tag)
470 aBoundingBox: bounding Box
471 label: short description of the object class/type (English only)
472 name: full name (currently the same as langaddress)
473 foundorder: secondary ordering for places with same importance
477 public function lookup()
479 Debug::newFunction('Geocode::lookup');
480 if (!$this->sQuery && !$this->aStructuredQuery) return array();
482 Debug::printDebugArray('Geocode', $this);
484 $oCtx = new SearchContext();
486 if ($this->aRoutePoints) {
487 $oCtx->setViewboxFromRoute(
491 $this->bBoundedSearch
493 } elseif ($this->aViewBox) {
494 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
496 if ($this->aExcludePlaceIDs) {
497 $oCtx->setExcludeList($this->aExcludePlaceIDs);
499 if ($this->aCountryCodes) {
500 $oCtx->setCountryList($this->aCountryCodes);
502 $this->oTokenizer->setCountryRestriction($this->aCountryCodes);
504 Debug::newSection('Query Preprocessing');
506 $sLanguagePrefArraySQL = $this->oDB->getArraySQL(
507 $this->oDB->getDBQuotedList($this->aLangPrefOrder)
510 $sQuery = $this->sQuery;
511 if (!preg_match('//u', $sQuery)) {
512 userError('Query string is not UTF-8 encoded.');
515 // Conflicts between US state abreviations and various words for 'the' in different languages
516 if (isset($this->aLangPrefOrder['name:en'])) {
517 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
518 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
519 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
522 // Do we have anything that looks like a lat/lon pair?
523 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
525 if ($sQuery || $this->aStructuredQuery) {
526 // Start with a single blank search
527 $aSearches = array(new SearchDescription($oCtx));
530 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
536 '/\\[([\\w ]*)\\]/u',
541 if (!empty($aSpecialTermsRaw)) {
542 Debug::printVar('Special terms', $aSpecialTermsRaw);
545 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
546 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
547 if (!$sSpecialTerm) {
548 $sSpecialTerm = $aSpecialTerm[1];
552 if (!$sSpecialTerm && $this->aStructuredQuery
553 && isset($this->aStructuredQuery['amenity'])) {
554 $sSpecialTerm = $this->aStructuredQuery['amenity'];
555 unset($this->aStructuredQuery['amenity']);
558 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
559 $aTokens = $this->oTokenizer->tokensForSpecialTerm($sSpecialTerm);
561 if (!empty($aTokens)) {
562 $aNewSearches = array();
563 foreach ($aSearches as $oSearch) {
564 foreach ($aTokens as $oToken) {
565 $oNewSearch = clone $oSearch;
566 $oNewSearch->setPoiSearch(
571 $aNewSearches[] = $oNewSearch;
574 $aSearches = $aNewSearches;
578 // Split query into phrases
579 // Commas are used to reduce the search space by indicating where phrases split
581 if ($this->aStructuredQuery) {
582 foreach ($this->aStructuredQuery as $iPhrase => $sPhrase) {
583 $aPhrases[] = new Phrase($sPhrase, $iPhrase);
586 foreach (explode(',', $sQuery) as $sPhrase) {
587 $aPhrases[] = new Phrase($sPhrase, '');
591 Debug::printDebugArray('Search context', $oCtx);
592 Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
594 Debug::newSection('Tokenization');
595 $oValidTokens = $this->oTokenizer->extractTokensFromPhrases($aPhrases);
597 if ($oValidTokens->count() > 0) {
598 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
600 $aPhrases = array_filter($aPhrases, function ($oPhrase) {
601 return $oPhrase->getWordSets() !== null;
604 // Any words that have failed completely?
607 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
608 Debug::printDebugTable('Phrases', $aPhrases);
610 Debug::newSection('Search candidates');
612 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
614 if (!$this->aStructuredQuery) {
615 // Reverse phrase array and also reverse the order of the wordsets in
616 // the first and final phrase. Don't bother about phrases in the middle
617 // because order in the address doesn't matter.
618 $aPhrases = array_reverse($aPhrases);
619 $aPhrases[0]->invertWordSets();
620 if (count($aPhrases) > 1) {
621 $aPhrases[count($aPhrases)-1]->invertWordSets();
623 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens);
625 foreach ($aGroupedSearches as $aSearches) {
626 foreach ($aSearches as $aSearch) {
627 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
628 $aReverseGroupedSearches[$aSearch->getRank()] = array();
630 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
634 $aGroupedSearches = $aReverseGroupedSearches;
635 ksort($aGroupedSearches);
638 // Re-group the searches by their score, junk anything over 20 as just not worth trying
639 $aGroupedSearches = array();
640 foreach ($aSearches as $aSearch) {
641 if ($aSearch->getRank() < $this->iMaxRank) {
642 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
643 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
646 ksort($aGroupedSearches);
649 // Filter out duplicate searches
650 $aSearchHash = array();
651 foreach ($aGroupedSearches as $iGroup => $aSearches) {
652 foreach ($aSearches as $iSearch => $aSearch) {
653 $sHash = serialize($aSearch);
654 if (isset($aSearchHash[$sHash])) {
655 unset($aGroupedSearches[$iGroup][$iSearch]);
656 if (empty($aGroupedSearches[$iGroup])) unset($aGroupedSearches[$iGroup]);
658 $aSearchHash[$sHash] = 1;
663 Debug::printGroupedSearch(
665 $oValidTokens->debugTokenByWordIdList()
668 // Start the search process
671 $aNextResults = array();
672 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
674 $aResults = $aNextResults;
675 foreach ($aSearches as $oSearch) {
678 Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
679 Debug::printGroupedSearch(
680 array($iGroupedRank => array($oSearch)),
681 $oValidTokens->debugTokenByWordIdList()
684 $aNewResults = $oSearch->query(
686 $this->iMinAddressRank,
687 $this->iMaxAddressRank,
691 // The same result may appear in different rounds, only
692 // use the one with minimal rank.
693 foreach ($aNewResults as $iPlace => $oRes) {
694 if (!isset($aResults[$iPlace])
695 || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
696 $aResults[$iPlace] = $oRes;
700 if ($iQueryLoop > 20) break;
703 if (!empty($aResults)) {
704 $aSplitResults = Result::splitResults($aResults);
705 Debug::printVar('Split results', $aSplitResults);
707 && reset($aSplitResults['head'])->iResultRank > 0
708 && $iGroupedRank !== array_key_last($aGroupedSearches)) {
709 // Haven't found an exact match for the query yet.
710 // Therefore add result from the next group level.
711 $aNextResults = $aSplitResults['head'];
712 foreach ($aNextResults as $oRes) {
713 $oRes->iResultRank--;
715 foreach ($aSplitResults['tail'] as $oRes) {
716 $oRes->iResultRank--;
717 $aNextResults[$oRes->iId] = $oRes;
721 $aResults = $aSplitResults['head'];
725 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
726 // Need to verify passes rank limits before dropping out of the loop (yuk!)
727 // reduces the number of place ids, like a filter
728 // rank_address is 30 for interpolated housenumbers
729 $aFilterSql = array();
730 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
732 $sSQL = 'SELECT place_id FROM placex ';
733 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
735 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
736 $sSQL .= " OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
737 if ($this->aAddressRankList) {
738 $sSQL .= ' OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
741 $aFilterSql[] = $sSQL;
743 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
745 $sSQL = ' SELECT place_id FROM location_postcode lp ';
746 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
747 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
748 if ($this->aAddressRankList) {
749 $sSQL .= ' OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
752 $aFilterSql[] = $sSQL;
755 $aFilteredIDs = array();
757 $sSQL = join(' UNION ', $aFilterSql);
758 Debug::printSQL($sSQL);
759 $aFilteredIDs = $this->oDB->getCol($sSQL);
763 foreach ($aResults as $oResult) {
764 if (($this->iMaxAddressRank == 30 &&
765 ($oResult->iTable == Result::TABLE_OSMLINE
766 || $oResult->iTable == Result::TABLE_TIGER))
767 || in_array($oResult->iId, $aFilteredIDs)
769 $tempIDs[$oResult->iId] = $oResult;
772 $aResults = $tempIDs;
775 if (!empty($aResults)) break;
776 if ($iGroupLoop > 4) break;
777 if ($iQueryLoop > 30) break;
780 // Just interpret as a reverse geocode
781 $oReverse = new ReverseGeocode($this->oDB);
782 $oReverse->setZoom(18);
784 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
786 Debug::printVar('Reverse search', $oLookup);
789 $aResults = array($oLookup->iId => $oLookup);
794 if (empty($aResults)) {
795 if ($this->bFallback) {
796 if ($this->fallbackStructuredQuery()) {
797 return $this->lookup();
804 if ($this->aAddressRankList) {
805 $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
807 $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
808 $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
809 if ($oCtx->hasNearPoint()) {
810 $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
813 $aSearchResults = $this->oPlaceLookup->lookup($aResults);
815 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
816 foreach ($aRecheckWords as $i => $sWord) {
817 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
820 Debug::printVar('Recheck words', $aRecheckWords);
822 foreach ($aSearchResults as $iIdx => $aResult) {
823 $fRadius = ClassTypes\getDefRadius($aResult);
825 $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fRadius);
826 if ($aOutlineResult) {
827 $aResult = array_merge($aResult, $aOutlineResult);
830 // Is there an icon set for this type of result?
831 $sIcon = ClassTypes\getIconFile($aResult);
833 $aResult['icon'] = $sIcon;
836 $sLabel = ClassTypes\getLabel($aResult);
837 if (isset($sLabel)) {
838 $aResult['label'] = $sLabel;
840 $aResult['name'] = $aResult['langaddress'];
842 if ($oCtx->hasNearPoint()) {
843 $aResult['importance'] = 0.001;
844 $aResult['foundorder'] = $aResult['addressimportance'];
846 $aResult['importance'] = max(0.001, $aResult['importance']);
847 $aResult['importance'] *= $this->viewboxImportanceFactor(
852 // secondary ordering (for results with same importance (the smaller the better):
853 // - approximate importance of address parts
854 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
855 $aResult['foundorder'] = -$aResult['addressimportance']/10;
857 $aResult['foundorder'] = -$aResult['importance'];
859 // - number of exact matches from the query
860 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
861 // - importance of the class/type
862 $iClassImportance = ClassTypes\getImportance($aResult);
863 if (isset($iClassImportance)) {
864 $aResult['foundorder'] += 0.0001 * $iClassImportance;
866 $aResult['foundorder'] += 0.01;
869 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
871 // Adjust importance for the number of exact string matches in the result
873 $sAddress = $aResult['langaddress'];
874 foreach ($aRecheckWords as $i => $sWord) {
875 if (stripos($sAddress, $sWord)!==false) {
877 if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) $iCountWords += 0.1;
881 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
882 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
884 $aSearchResults[$iIdx] = $aResult;
886 uasort($aSearchResults, 'byImportance');
887 Debug::printVar('Pre-filter results', $aSearchResults);
889 $aOSMIDDone = array();
890 $aClassTypeNameDone = array();
891 $aToFilter = $aSearchResults;
892 $aSearchResults = array();
895 foreach ($aToFilter as $aResult) {
896 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
898 $fLat = $aResult['lat'];
899 $fLon = $aResult['lon'];
900 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
903 if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
904 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
906 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
907 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
908 $aSearchResults[] = $aResult;
911 // Absolute limit on number of results
912 if (count($aSearchResults) >= $this->iFinalLimit) break;
915 Debug::printVar('Post-filter results', $aSearchResults);
916 return $aSearchResults;
919 public function debugInfo()
922 'Query' => $this->sQuery,
923 'Structured query' => $this->aStructuredQuery,
924 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
925 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
926 'Limit (for searches)' => $this->iLimit,
927 'Limit (for results)'=> $this->iFinalLimit,
928 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
929 'Bounded search' => $this->bBoundedSearch,
930 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
931 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
932 'Route width' => $this->aRouteWidth,
933 'Max rank' => $this->iMaxRank,
934 'Min address rank' => $this->iMinAddressRank,
935 'Max address rank' => $this->iMaxAddressRank,
936 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)