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');
16 protected $oPlaceLookup;
18 protected $aLangPrefOrder = array();
20 protected $aExcludePlaceIDs = array();
22 protected $iLimit = 20;
23 protected $iFinalLimit = 10;
24 protected $iOffset = 0;
25 protected $bFallback = false;
27 protected $aCountryCodes = false;
29 protected $bBoundedSearch = false;
30 protected $aViewBox = false;
31 protected $aRoutePoints = false;
32 protected $aRouteWidth = false;
34 protected $iMaxRank = 20;
35 protected $iMinAddressRank = 0;
36 protected $iMaxAddressRank = 30;
37 protected $aAddressRankList = array();
39 protected $sAllowedTypesSQLList = false;
41 protected $sQuery = false;
42 protected $aStructuredQuery = false;
44 protected $oNormalizer = null;
47 public function __construct(&$oDB)
50 $this->oPlaceLookup = new PlaceLookup($this->oDB);
51 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
54 private function normTerm($sTerm)
56 if ($this->oNormalizer === null) {
60 return $this->oNormalizer->transliterate($sTerm);
63 public function setLanguagePreference($aLangPref)
65 $this->aLangPrefOrder = $aLangPref;
68 public function getMoreUrlParams()
70 if ($this->aStructuredQuery) {
71 $aParams = $this->aStructuredQuery;
73 $aParams = array('q' => $this->sQuery);
76 $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
78 if ($this->aExcludePlaceIDs) {
79 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
82 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
84 if ($this->aCountryCodes) {
85 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
88 if ($this->aViewBox) {
89 $aParams['viewbox'] = join(',', $this->aViewBox);
95 public function setLimit($iLimit = 10)
97 if ($iLimit > 50) $iLimit = 50;
98 if ($iLimit < 1) $iLimit = 1;
100 $this->iFinalLimit = $iLimit;
101 $this->iLimit = $iLimit + min($iLimit, 10);
104 public function setFeatureType($sFeatureType)
106 switch ($sFeatureType) {
108 $this->setRankRange(4, 4);
111 $this->setRankRange(8, 8);
114 $this->setRankRange(14, 16);
117 $this->setRankRange(8, 20);
122 public function setRankRange($iMin, $iMax)
124 $this->iMinAddressRank = $iMin;
125 $this->iMaxAddressRank = $iMax;
128 public function setViewbox($aViewbox)
130 $aBox = array_map('floatval', $aViewbox);
132 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
133 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
134 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
135 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
137 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
138 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
140 userError("Bad parameter 'viewbox'. Not a box.");
144 private function viewboxImportanceFactor($fX, $fY)
146 if (!$this->aViewBox) {
150 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
151 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
153 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
154 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
156 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
160 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
167 public function setQuery($sQueryString)
169 $this->sQuery = $sQueryString;
170 $this->aStructuredQuery = false;
173 public function getQueryString()
175 return $this->sQuery;
179 public function loadParamArray($oParams, $sForceGeometryType = null)
181 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
183 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
184 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
186 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
188 // List of excluded Place IDs - used for more acurate pageing
189 $sExcluded = $oParams->getStringList('exclude_place_ids');
191 foreach ($sExcluded as $iExcludedPlaceID) {
192 $iExcludedPlaceID = (int)$iExcludedPlaceID;
193 if ($iExcludedPlaceID)
194 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
197 if (isset($aExcludePlaceIDs))
198 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
201 // Only certain ranks of feature
202 $sFeatureType = $oParams->getString('featureType');
203 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
204 if ($sFeatureType) $this->setFeatureType($sFeatureType);
207 $sCountries = $oParams->getStringList('countrycodes');
209 foreach ($sCountries as $sCountryCode) {
210 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
211 $aCountries[] = strtolower($sCountryCode);
214 if (isset($aCountries))
215 $this->aCountryCodes = $aCountries;
218 $aViewbox = $oParams->getStringList('viewboxlbrt');
220 if (count($aViewbox) != 4) {
221 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
223 $this->setViewbox($aViewbox);
225 $aViewbox = $oParams->getStringList('viewbox');
227 if (count($aViewbox) != 4) {
228 userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
230 $this->setViewBox($aViewbox);
232 $aRoute = $oParams->getStringList('route');
233 $fRouteWidth = $oParams->getFloat('routewidth');
234 if ($aRoute && $fRouteWidth) {
235 $this->aRoutePoints = $aRoute;
236 $this->aRouteWidth = $fRouteWidth;
241 $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
242 $this->oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', false));
245 public function setQueryFromParams($oParams)
248 $sQuery = $oParams->getString('q');
250 $this->setStructuredQuery(
251 $oParams->getString('amenity'),
252 $oParams->getString('street'),
253 $oParams->getString('city'),
254 $oParams->getString('county'),
255 $oParams->getString('state'),
256 $oParams->getString('country'),
257 $oParams->getString('postalcode')
260 $this->setQuery($sQuery);
264 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
266 $sValue = trim($sValue);
267 if (!$sValue) return false;
268 $this->aStructuredQuery[$sKey] = $sValue;
269 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
270 $this->iMinAddressRank = $iNewMinAddressRank;
271 $this->iMaxAddressRank = $iNewMaxAddressRank;
273 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
277 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
279 $this->sQuery = false;
282 $this->iMinAddressRank = 0;
283 $this->iMaxAddressRank = 30;
284 $this->aAddressRankList = array();
286 $this->aStructuredQuery = array();
287 $this->sAllowedTypesSQLList = false;
289 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
290 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
291 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
292 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
293 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
294 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
295 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
297 if (!empty($this->aStructuredQuery)) {
298 $this->sQuery = join(', ', $this->aStructuredQuery);
299 if ($this->iMaxAddressRank < 30) {
300 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
305 public function fallbackStructuredQuery()
307 if (!$this->aStructuredQuery) return false;
309 $aParams = $this->aStructuredQuery;
311 if (count($aParams) == 1) return false;
313 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
315 foreach ($aOrderToFallback as $sType) {
316 if (isset($aParams[$sType])) {
317 unset($aParams[$sType]);
318 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
326 public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens, $bIsStructured)
329 Calculate all searches using oValidTokens i.e.
330 'Wodsworth Road, Sheffield' =>
334 0 1 (wodsworth)(road)
337 Score how good the search is so they can be ordered
339 foreach ($aPhrases as $iPhrase => $oPhrase) {
340 $aNewPhraseSearches = array();
341 $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
343 foreach ($oPhrase->getWordSets() as $aWordset) {
344 $aWordsetSearches = $aSearches;
346 // Add all words from this wordset
347 foreach ($aWordset as $iToken => $sToken) {
348 //echo "<br><b>$sToken</b>";
349 $aNewWordsetSearches = array();
351 foreach ($aWordsetSearches as $oCurrentSearch) {
353 //var_dump($oCurrentSearch);
356 // Tokens with full name matches.
357 foreach ($oValidTokens->get(' '.$sToken) as $oSearchTerm) {
358 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
360 $oValidTokens->contains($sToken)
361 && strpos($sToken, ' ') === false,
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);
401 //var_Dump('<hr>',count($aWordsetSearches)); exit;
403 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
404 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
406 $aSearchHash = array();
407 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
408 $sHash = serialize($aSearch);
409 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
410 else $aSearchHash[$sHash] = 1;
413 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
416 // Re-group the searches by their score, junk anything over 20 as just not worth trying
417 $aGroupedSearches = array();
418 foreach ($aNewPhraseSearches as $aSearch) {
419 $iRank = $aSearch->getRank();
420 if ($iRank < $this->iMaxRank) {
421 if (!isset($aGroupedSearches[$iRank])) {
422 $aGroupedSearches[$iRank] = array();
424 $aGroupedSearches[$iRank][] = $aSearch;
427 ksort($aGroupedSearches);
430 $aSearches = array();
431 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
432 $iSearchCount += count($aNewSearches);
433 $aSearches = array_merge($aSearches, $aNewSearches);
434 if ($iSearchCount > 50) break;
438 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
439 $aGroupedSearches = array();
440 foreach ($aSearches as $oSearch) {
441 if (!$oSearch->isValidSearch()) {
445 $iRank = $oSearch->getRank();
446 if (!isset($aGroupedSearches[$iRank])) {
447 $aGroupedSearches[$iRank] = array();
449 $aGroupedSearches[$iRank][] = $oSearch;
451 ksort($aGroupedSearches);
453 return $aGroupedSearches;
456 /* Perform the actual query lookup.
458 Returns an ordered list of results, each with the following fields:
459 osm_type: type of corresponding OSM object
463 P - postcode (internally computed)
464 osm_id: id of corresponding OSM object
465 class: general object class (corresponds to tag key of primary OSM tag)
466 type: subclass of object (corresponds to tag value of primary OSM tag)
467 admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
468 rank_search: rank in search hierarchy
469 (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
470 rank_address: rank in address hierarchy (determines orer in address)
471 place_id: internal key (may differ between different instances)
472 country_code: ISO country code
473 langaddress: localized full address
474 placename: localized name of object
475 ref: content of ref tag (if available)
478 importance: importance of place based on Wikipedia link count
479 addressimportance: cumulated importance of address elements
480 extra_place: type of place (for admin boundaries, if there is a place tag)
481 aBoundingBox: bounding Box
482 label: short description of the object class/type (English only)
483 name: full name (currently the same as langaddress)
484 foundorder: secondary ordering for places with same importance
488 public function lookup()
490 Debug::newFunction('Geocode::lookup');
491 if (!$this->sQuery && !$this->aStructuredQuery) return array();
493 Debug::printDebugArray('Geocode', $this);
495 $oCtx = new SearchContext();
497 if ($this->aRoutePoints) {
498 $oCtx->setViewboxFromRoute(
502 $this->bBoundedSearch
504 } elseif ($this->aViewBox) {
505 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
507 if ($this->aExcludePlaceIDs) {
508 $oCtx->setExcludeList($this->aExcludePlaceIDs);
510 if ($this->aCountryCodes) {
511 $oCtx->setCountryList($this->aCountryCodes);
514 Debug::newSection('Query Preprocessing');
516 $sNormQuery = $this->normTerm($this->sQuery);
517 Debug::printVar('Normalized query', $sNormQuery);
519 $sLanguagePrefArraySQL = $this->oDB->getArraySQL(
520 $this->oDB->getDBQuotedList($this->aLangPrefOrder)
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 $sSpecialTerm = pg_escape_string($sSpecialTerm);
573 $sToken = $this->oDB->getOne(
574 'SELECT make_standard_name(:term)',
575 array(':term' => $sSpecialTerm),
576 'Cannot decode query. Wrong encoding?'
578 $sSQL = 'SELECT class, type FROM word ';
579 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
580 $sSQL .= ' AND class is not null AND class not in (\'place\')';
582 Debug::printSQL($sSQL);
583 $aSearchWords = $this->oDB->getAll($sSQL);
584 $aNewSearches = array();
585 foreach ($aSearches as $oSearch) {
586 foreach ($aSearchWords as $aSearchTerm) {
587 $oNewSearch = clone $oSearch;
588 $oNewSearch->setPoiSearch(
590 $aSearchTerm['class'],
593 $aNewSearches[] = $oNewSearch;
596 $aSearches = $aNewSearches;
599 // Split query into phrases
600 // Commas are used to reduce the search space by indicating where phrases split
601 if ($this->aStructuredQuery) {
602 $aInPhrases = $this->aStructuredQuery;
603 $bStructuredPhrases = true;
605 $aInPhrases = explode(',', $sQuery);
606 $bStructuredPhrases = false;
609 Debug::printDebugArray('Search context', $oCtx);
610 Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
611 Debug::printVar('Final query phrases', $aInPhrases);
613 // Convert each phrase to standard form
614 // Create a list of standard words
615 // Get all 'sets' of words
616 // Generate a complete list of all
617 Debug::newSection('Tokenization');
620 foreach ($aInPhrases as $iPhrase => $sPhrase) {
621 $sPhrase = $this->oDB->getOne(
622 'SELECT make_standard_name(:phrase)',
623 array(':phrase' => $sPhrase),
624 'Cannot normalize query string (is it a UTF-8 string?)'
626 if (trim($sPhrase)) {
627 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
628 $oPhrase->addTokens($aTokens);
629 $aPhrases[] = $oPhrase;
633 Debug::printVar('Tokens', $aTokens);
635 $oValidTokens = new TokenList();
637 if (!empty($aTokens)) {
638 $oValidTokens->addTokensFromDB(
641 $this->aCountryCodes,
646 $oCtx->setFullNameWords($oValidTokens->getFullWordIDs());
648 // Try more interpretations for Tokens that could not be matched.
649 foreach ($aTokens as $sToken) {
650 if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
651 if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
652 // US ZIP+4 codes - merge in the 5-digit ZIP code
653 $oValidTokens->addToken(
655 new Token\Postcode(null, $aData[1], 'us')
657 } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
658 // Unknown single word token with a number.
659 // Assume it is a house number.
660 $oValidTokens->addToken(
662 new Token\HouseNumber(null, trim($sToken))
668 // Any words that have failed completely?
671 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
673 foreach ($aPhrases as $oPhrase) {
674 $oPhrase->computeWordSets($oValidTokens);
676 Debug::printDebugTable('Phrases', $aPhrases);
678 Debug::newSection('Search candidates');
680 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens, $bStructuredPhrases);
682 if (!$this->aStructuredQuery) {
683 // Reverse phrase array and also reverse the order of the wordsets in
684 // the first and final phrase. Don't bother about phrases in the middle
685 // because order in the address doesn't matter.
686 $aPhrases = array_reverse($aPhrases);
687 $aPhrases[0]->invertWordSets();
688 if (count($aPhrases) > 1) {
689 $aPhrases[count($aPhrases)-1]->invertWordSets();
691 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens, false);
693 foreach ($aGroupedSearches as $aSearches) {
694 foreach ($aSearches as $aSearch) {
695 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
696 $aReverseGroupedSearches[$aSearch->getRank()] = array();
698 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
702 $aGroupedSearches = $aReverseGroupedSearches;
703 ksort($aGroupedSearches);
706 // Re-group the searches by their score, junk anything over 20 as just not worth trying
707 $aGroupedSearches = array();
708 foreach ($aSearches as $aSearch) {
709 if ($aSearch->getRank() < $this->iMaxRank) {
710 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
711 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
714 ksort($aGroupedSearches);
717 // Filter out duplicate searches
718 $aSearchHash = array();
719 foreach ($aGroupedSearches as $iGroup => $aSearches) {
720 foreach ($aSearches as $iSearch => $aSearch) {
721 $sHash = serialize($aSearch);
722 if (isset($aSearchHash[$sHash])) {
723 unset($aGroupedSearches[$iGroup][$iSearch]);
724 if (empty($aGroupedSearches[$iGroup])) unset($aGroupedSearches[$iGroup]);
726 $aSearchHash[$sHash] = 1;
731 Debug::printGroupedSearch(
733 $oValidTokens->debugTokenByWordIdList()
736 // Start the search process
739 $aNextResults = array();
740 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
742 $aResults = $aNextResults;
743 foreach ($aSearches as $oSearch) {
746 Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
747 Debug::printGroupedSearch(
748 array($iGroupedRank => array($oSearch)),
749 $oValidTokens->debugTokenByWordIdList()
752 $aNewResults = $oSearch->query(
754 $this->iMinAddressRank,
755 $this->iMaxAddressRank,
759 // The same result may appear in different rounds, only
760 // use the one with minimal rank.
761 foreach ($aNewResults as $iPlace => $oRes) {
762 if (!isset($aResults[$iPlace])
763 || $aResults[$iPlace]->iResultRank > $oRes->iResultRank) {
764 $aResults[$iPlace] = $oRes;
768 if ($iQueryLoop > 20) break;
771 if (!empty($aResults)) {
772 $aSplitResults = Result::splitResults($aResults);
773 Debug::printVar('Split results', $aSplitResults);
775 && reset($aSplitResults['head'])->iResultRank > 0
776 && $iGroupedRank !== array_key_last($aGroupedSearches)) {
777 // Haven't found an exact match for the query yet.
778 // Therefore add result from the next group level.
779 $aNextResults = $aSplitResults['head'];
780 foreach ($aNextResults as $oRes) {
781 $oRes->iResultRank--;
783 foreach ($aSplitResults['tail'] as $oRes) {
784 $oRes->iResultRank--;
785 $aNextResults[$oRes->iId] = $oRes;
789 $aResults = $aSplitResults['head'];
793 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
794 // Need to verify passes rank limits before dropping out of the loop (yuk!)
795 // reduces the number of place ids, like a filter
796 // rank_address is 30 for interpolated housenumbers
797 $aFilterSql = array();
798 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
800 $sSQL = 'SELECT place_id FROM placex ';
801 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
803 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
804 $sSQL .= " OR placex.rank_search between $this->iMinAddressRank and $this->iMaxAddressRank ";
805 if ($this->aAddressRankList) {
806 $sSQL .= ' OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
809 $aFilterSql[] = $sSQL;
811 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
813 $sSQL = ' SELECT place_id FROM location_postcode lp ';
814 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
815 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
816 if ($this->aAddressRankList) {
817 $sSQL .= ' OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
820 $aFilterSql[] = $sSQL;
823 $aFilteredIDs = array();
825 $sSQL = join(' UNION ', $aFilterSql);
826 Debug::printSQL($sSQL);
827 $aFilteredIDs = $this->oDB->getCol($sSQL);
831 foreach ($aResults as $oResult) {
832 if (($this->iMaxAddressRank == 30 &&
833 ($oResult->iTable == Result::TABLE_OSMLINE
834 || $oResult->iTable == Result::TABLE_AUX
835 || $oResult->iTable == Result::TABLE_TIGER))
836 || in_array($oResult->iId, $aFilteredIDs)
838 $tempIDs[$oResult->iId] = $oResult;
841 $aResults = $tempIDs;
844 if (!empty($aResults)) break;
845 if ($iGroupLoop > 4) break;
846 if ($iQueryLoop > 30) break;
849 // Just interpret as a reverse geocode
850 $oReverse = new ReverseGeocode($this->oDB);
851 $oReverse->setZoom(18);
853 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
855 Debug::printVar('Reverse search', $oLookup);
858 $aResults = array($oLookup->iId => $oLookup);
863 if (empty($aResults)) {
864 if ($this->bFallback) {
865 if ($this->fallbackStructuredQuery()) {
866 return $this->lookup();
873 if ($this->aAddressRankList) {
874 $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
876 $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
877 $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
878 if ($oCtx->hasNearPoint()) {
879 $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
882 $aSearchResults = $this->oPlaceLookup->lookup($aResults);
884 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
885 foreach ($aRecheckWords as $i => $sWord) {
886 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
889 Debug::printVar('Recheck words', $aRecheckWords);
891 foreach ($aSearchResults as $iIdx => $aResult) {
892 $fRadius = ClassTypes\getDefRadius($aResult);
894 $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fRadius);
895 if ($aOutlineResult) {
896 $aResult = array_merge($aResult, $aOutlineResult);
899 // Is there an icon set for this type of result?
900 $sIcon = ClassTypes\getIconFile($aResult);
902 $aResult['icon'] = $sIcon;
905 $sLabel = ClassTypes\getLabel($aResult);
906 if (isset($sLabel)) {
907 $aResult['label'] = $sLabel;
909 $aResult['name'] = $aResult['langaddress'];
911 if ($oCtx->hasNearPoint()) {
912 $aResult['importance'] = 0.001;
913 $aResult['foundorder'] = $aResult['addressimportance'];
915 $aResult['importance'] = max(0.001, $aResult['importance']);
916 $aResult['importance'] *= $this->viewboxImportanceFactor(
921 // secondary ordering (for results with same importance (the smaller the better):
922 // - approximate importance of address parts
923 if (isset($aResult['addressimportance']) && $aResult['addressimportance']) {
924 $aResult['foundorder'] = -$aResult['addressimportance']/10;
926 $aResult['foundorder'] = -$aResult['importance'];
928 // - number of exact matches from the query
929 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
930 // - importance of the class/type
931 $iClassImportance = ClassTypes\getImportance($aResult);
932 if (isset($iClassImportance)) {
933 $aResult['foundorder'] += 0.0001 * $iClassImportance;
935 $aResult['foundorder'] += 0.01;
938 $aResult['foundorder'] -= 0.00001 * (30 - $aResult['rank_search']);
940 // Adjust importance for the number of exact string matches in the result
942 $sAddress = $aResult['langaddress'];
943 foreach ($aRecheckWords as $i => $sWord) {
944 if (stripos($sAddress, $sWord)!==false) {
946 if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) $iCountWords += 0.1;
950 // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
951 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1);
953 $aSearchResults[$iIdx] = $aResult;
955 uasort($aSearchResults, 'byImportance');
956 Debug::printVar('Pre-filter results', $aSearchResults);
958 $aOSMIDDone = array();
959 $aClassTypeNameDone = array();
960 $aToFilter = $aSearchResults;
961 $aSearchResults = array();
964 foreach ($aToFilter as $aResult) {
965 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
967 $fLat = $aResult['lat'];
968 $fLon = $aResult['lon'];
969 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
972 if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
973 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
975 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
976 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
977 $aSearchResults[] = $aResult;
980 // Absolute limit on number of results
981 if (count($aSearchResults) >= $this->iFinalLimit) break;
984 Debug::printVar('Post-filter results', $aSearchResults);
985 return $aSearchResults;
988 public function debugInfo()
991 'Query' => $this->sQuery,
992 'Structured query' => $this->aStructuredQuery,
993 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
994 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
995 'Limit (for searches)' => $this->iLimit,
996 'Limit (for results)'=> $this->iFinalLimit,
997 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
998 'Bounded search' => $this->bBoundedSearch,
999 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
1000 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
1001 'Route width' => $this->aRouteWidth,
1002 'Max rank' => $this->iMaxRank,
1003 'Min address rank' => $this->iMinAddressRank,
1004 'Max address rank' => $this->iMaxAddressRank,
1005 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)