5 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
6 require_once(CONST_BasePath.'/lib/Phrase.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
8 require_once(CONST_BasePath.'/lib/SearchDescription.php');
9 require_once(CONST_BasePath.'/lib/SearchContext.php');
10 require_once(CONST_BasePath.'/lib/TokenList.php');
16 protected $oPlaceLookup;
18 protected $aLangPrefOrder = array();
20 protected $bIncludeAddressDetails = false;
22 protected $aExcludePlaceIDs = array();
23 protected $bReverseInPlan = false;
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;
47 protected $oNormalizer = null;
50 public function __construct(&$oDB)
53 $this->oPlaceLookup = new PlaceLookup($this->oDB);
54 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
57 private function normTerm($sTerm)
59 if ($this->oNormalizer === null) {
63 return $this->oNormalizer->transliterate($sTerm);
66 public function setReverseInPlan($bReverse)
68 $this->bReverseInPlan = $bReverse;
71 public function setLanguagePreference($aLangPref)
73 $this->aLangPrefOrder = $aLangPref;
76 public function getMoreUrlParams()
78 if ($this->aStructuredQuery) {
79 $aParams = $this->aStructuredQuery;
81 $aParams = array('q' => $this->sQuery);
84 $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
86 if ($this->aExcludePlaceIDs) {
87 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
90 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
91 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
93 if ($this->aCountryCodes) {
94 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
97 if ($this->aViewBox) {
98 $aParams['viewbox'] = join(',', $this->aViewBox);
104 public function setLimit($iLimit = 10)
106 if ($iLimit > 50) $iLimit = 50;
107 if ($iLimit < 1) $iLimit = 1;
109 $this->iFinalLimit = $iLimit;
110 $this->iLimit = $iLimit + min($iLimit, 10);
113 public function setFeatureType($sFeatureType)
115 switch ($sFeatureType) {
117 $this->setRankRange(4, 4);
120 $this->setRankRange(8, 8);
123 $this->setRankRange(14, 16);
126 $this->setRankRange(8, 20);
131 public function setRankRange($iMin, $iMax)
133 $this->iMinAddressRank = $iMin;
134 $this->iMaxAddressRank = $iMax;
137 public function setViewbox($aViewbox)
139 $aBox = array_map('floatval', $aViewbox);
141 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
142 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
143 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
144 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
146 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
147 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
149 userError("Bad parameter 'viewbox'. Not a box.");
153 private function viewboxImportanceFactor($fX, $fY)
155 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
156 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
158 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
159 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
161 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
165 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
172 public function setQuery($sQueryString)
174 $this->sQuery = $sQueryString;
175 $this->aStructuredQuery = false;
178 public function getQueryString()
180 return $this->sQuery;
184 public function loadParamArray($oParams, $sForceGeometryType = null)
186 $this->bIncludeAddressDetails
187 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
189 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
191 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
192 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
194 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
196 // List of excluded Place IDs - used for more acurate pageing
197 $sExcluded = $oParams->getStringList('exclude_place_ids');
199 foreach ($sExcluded as $iExcludedPlaceID) {
200 $iExcludedPlaceID = (int)$iExcludedPlaceID;
201 if ($iExcludedPlaceID)
202 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
205 if (isset($aExcludePlaceIDs))
206 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
209 // Only certain ranks of feature
210 $sFeatureType = $oParams->getString('featureType');
211 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
212 if ($sFeatureType) $this->setFeatureType($sFeatureType);
215 $sCountries = $oParams->getStringList('countrycodes');
217 foreach ($sCountries as $sCountryCode) {
218 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
219 $aCountries[] = strtolower($sCountryCode);
222 if (isset($aCountries))
223 $this->aCountryCodes = $aCountries;
226 $aViewbox = $oParams->getStringList('viewboxlbrt');
228 if (count($aViewbox) != 4) {
229 userError("Bad parameter 'viewboxlbrt'. Expected 4 coordinates.");
231 $this->setViewbox($aViewbox);
233 $aViewbox = $oParams->getStringList('viewbox');
235 if (count($aViewbox) != 4) {
236 userError("Bad parameter 'viewbox'. Expected 4 coordinates.");
238 $this->setViewBox($aViewbox);
240 $aRoute = $oParams->getStringList('route');
241 $fRouteWidth = $oParams->getFloat('routewidth');
242 if ($aRoute && $fRouteWidth) {
243 $this->aRoutePoints = $aRoute;
244 $this->aRouteWidth = $fRouteWidth;
249 $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
250 $this->oPlaceLookup->setIncludeAddressDetails(false);
251 $this->oPlaceLookup->setIncludePolygonAsPoints($oParams->getBool('polygon'));
253 if ($this->bIncludeAddressDetails
254 && $oParams->getString('format', '') == 'geocodejson'
256 $this->oPlaceLookup->setAddressAdminLevels(true);
260 public function setQueryFromParams($oParams)
263 $sQuery = $oParams->getString('q');
265 $this->setStructuredQuery(
266 $oParams->getString('amenity'),
267 $oParams->getString('street'),
268 $oParams->getString('city'),
269 $oParams->getString('county'),
270 $oParams->getString('state'),
271 $oParams->getString('country'),
272 $oParams->getString('postalcode')
274 $this->setReverseInPlan(false);
276 $this->setQuery($sQuery);
280 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
282 $sValue = trim($sValue);
283 if (!$sValue) return false;
284 $this->aStructuredQuery[$sKey] = $sValue;
285 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
286 $this->iMinAddressRank = $iNewMinAddressRank;
287 $this->iMaxAddressRank = $iNewMaxAddressRank;
289 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
293 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
295 $this->sQuery = false;
298 $this->iMinAddressRank = 0;
299 $this->iMaxAddressRank = 30;
300 $this->aAddressRankList = array();
302 $this->aStructuredQuery = array();
303 $this->sAllowedTypesSQLList = false;
305 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
306 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
307 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
308 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
309 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
310 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
311 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
313 if (!empty($this->aStructuredQuery)) {
314 $this->sQuery = join(', ', $this->aStructuredQuery);
315 if ($this->iMaxAddressRank < 30) {
316 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
321 public function fallbackStructuredQuery()
323 if (!$this->aStructuredQuery) return false;
325 $aParams = $this->aStructuredQuery;
327 if (count($aParams) == 1) return false;
329 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
331 foreach ($aOrderToFallback as $sType) {
332 if (isset($aParams[$sType])) {
333 unset($aParams[$sType]);
334 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
342 public function getGroupedSearches($aSearches, $aPhrases, $oValidTokens, $bIsStructured)
345 Calculate all searches using oValidTokens i.e.
346 'Wodsworth Road, Sheffield' =>
350 0 1 (wodsworth)(road)
353 Score how good the search is so they can be ordered
355 foreach ($aPhrases as $iPhrase => $oPhrase) {
356 $aNewPhraseSearches = array();
357 $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
359 foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
360 // Too many permutations - too expensive
361 if ($iWordSet > 120) break;
363 $aWordsetSearches = $aSearches;
365 // Add all words from this wordset
366 foreach ($aWordset as $iToken => $sToken) {
367 //echo "<br><b>$sToken</b>";
368 $aNewWordsetSearches = array();
370 foreach ($aWordsetSearches as $oCurrentSearch) {
372 //var_dump($oCurrentSearch);
375 // Tokens with full name matches.
376 foreach ($oValidTokens->get(' '.$sToken) as $oSearchTerm) {
377 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
379 $oValidTokens->contains($sToken)
380 && strpos($sToken, ' ') === false,
382 $iToken == 0 && $iPhrase == 0,
384 $iToken + 1 == count($aWordset)
385 && $iPhrase + 1 == count($aPhrases)
388 foreach ($aNewSearches as $oSearch) {
389 if ($oSearch->getRank() < $this->iMaxRank) {
390 $aNewWordsetSearches[] = $oSearch;
394 // Look for partial matches.
395 // Note that there is no point in adding country terms here
396 // because country is omitted in the address.
397 if ($sPhraseType != 'country') {
398 // Allow searching for a word - but at extra cost
399 foreach ($oValidTokens->get($sToken) as $oSearchTerm) {
400 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
405 $oValidTokens->get(' '.$sToken)
408 foreach ($aNewSearches as $oSearch) {
409 if ($oSearch->getRank() < $this->iMaxRank) {
410 $aNewWordsetSearches[] = $oSearch;
417 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
418 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
420 //var_Dump('<hr>',count($aWordsetSearches)); exit;
422 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
423 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
425 $aSearchHash = array();
426 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
427 $sHash = serialize($aSearch);
428 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
429 else $aSearchHash[$sHash] = 1;
432 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
435 // Re-group the searches by their score, junk anything over 20 as just not worth trying
436 $aGroupedSearches = array();
437 foreach ($aNewPhraseSearches as $aSearch) {
438 $iRank = $aSearch->getRank();
439 if ($iRank < $this->iMaxRank) {
440 if (!isset($aGroupedSearches[$iRank])) {
441 $aGroupedSearches[$iRank] = array();
443 $aGroupedSearches[$iRank][] = $aSearch;
446 ksort($aGroupedSearches);
449 $aSearches = array();
450 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
451 $iSearchCount += count($aNewSearches);
452 $aSearches = array_merge($aSearches, $aNewSearches);
453 if ($iSearchCount > 50) break;
457 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
458 $aGroupedSearches = array();
459 foreach ($aSearches as $oSearch) {
460 if (!$oSearch->isValidSearch()) {
464 $iRank = $oSearch->getRank();
465 if (!isset($aGroupedSearches[$iRank])) {
466 $aGroupedSearches[$iRank] = array();
468 $aGroupedSearches[$iRank][] = $oSearch;
470 ksort($aGroupedSearches);
472 return $aGroupedSearches;
475 /* Perform the actual query lookup.
477 Returns an ordered list of results, each with the following fields:
478 osm_type: type of corresponding OSM object
482 P - postcode (internally computed)
483 osm_id: id of corresponding OSM object
484 class: general object class (corresponds to tag key of primary OSM tag)
485 type: subclass of object (corresponds to tag value of primary OSM tag)
486 admin_level: see https://wiki.openstreetmap.org/wiki/Admin_level
487 rank_search: rank in search hierarchy
488 (see also https://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
489 rank_address: rank in address hierarchy (determines orer in address)
490 place_id: internal key (may differ between different instances)
491 country_code: ISO country code
492 langaddress: localized full address
493 placename: localized name of object
494 ref: content of ref tag (if available)
497 importance: importance of place based on Wikipedia link count
498 addressimportance: cumulated importance of address elements
499 extra_place: type of place (for admin boundaries, if there is a place tag)
500 aBoundingBox: bounding Box
501 label: short description of the object class/type (English only)
502 name: full name (currently the same as langaddress)
503 foundorder: secondary ordering for places with same importance
507 public function lookup()
509 Debug::newFunction('Geocode::lookup');
510 if (!$this->sQuery && !$this->aStructuredQuery) return array();
512 Debug::printDebugArray('Geocode', $this);
514 $oCtx = new SearchContext();
516 if ($this->aRoutePoints) {
517 $oCtx->setViewboxFromRoute(
521 $this->bBoundedSearch
523 } elseif ($this->aViewBox) {
524 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
526 if ($this->aExcludePlaceIDs) {
527 $oCtx->setExcludeList($this->aExcludePlaceIDs);
529 if ($this->aCountryCodes) {
530 $oCtx->setCountryList($this->aCountryCodes);
533 Debug::newSection('Query Preprocessing');
535 $sNormQuery = $this->normTerm($this->sQuery);
536 Debug::printVar('Normalized query', $sNormQuery);
538 $sLanguagePrefArraySQL = getArraySQL(
539 array_map('getDBQuoted', $this->aLangPrefOrder)
542 $sQuery = $this->sQuery;
543 if (!preg_match('//u', $sQuery)) {
544 userError('Query string is not UTF-8 encoded.');
547 // Conflicts between US state abreviations and various words for 'the' in different languages
548 if (isset($this->aLangPrefOrder['name:en'])) {
549 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/i', '\1illinois\2', $sQuery);
550 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/i', '\1alabama\2', $sQuery);
551 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/i', '\1louisiana\2', $sQuery);
554 // Do we have anything that looks like a lat/lon pair?
555 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
558 if ($sQuery || $this->aStructuredQuery) {
559 // Start with a single blank search
560 $aSearches = array(new SearchDescription($oCtx));
563 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
569 '/\\[([\\w ]*)\\]/u',
574 if (!empty($aSpecialTermsRaw)) {
575 Debug::printVar('Special terms', $aSpecialTermsRaw);
578 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
579 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
580 if (!$sSpecialTerm) {
581 $sSpecialTerm = $aSpecialTerm[1];
585 if (!$sSpecialTerm && $this->aStructuredQuery
586 && isset($this->aStructuredQuery['amenity'])) {
587 $sSpecialTerm = $this->aStructuredQuery['amenity'];
588 unset($this->aStructuredQuery['amenity']);
591 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
592 $sSpecialTerm = pg_escape_string($sSpecialTerm);
594 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
595 'Cannot decode query. Wrong encoding?'
597 $sSQL = 'SELECT class, type FROM word ';
598 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
599 $sSQL .= ' AND class is not null AND class not in (\'place\')';
601 Debug::printSQL($sSQL);
602 $aSearchWords = chksql($this->oDB->getAll($sSQL));
603 $aNewSearches = array();
604 foreach ($aSearches as $oSearch) {
605 foreach ($aSearchWords as $aSearchTerm) {
606 $oNewSearch = clone $oSearch;
607 $oNewSearch->setPoiSearch(
609 $aSearchTerm['class'],
612 $aNewSearches[] = $oNewSearch;
615 $aSearches = $aNewSearches;
618 // Split query into phrases
619 // Commas are used to reduce the search space by indicating where phrases split
620 if ($this->aStructuredQuery) {
621 $aInPhrases = $this->aStructuredQuery;
622 $bStructuredPhrases = true;
624 $aInPhrases = explode(',', $sQuery);
625 $bStructuredPhrases = false;
628 Debug::printDebugArray('Search context', $oCtx);
629 Debug::printDebugArray('Base search', empty($aSearches) ? null : $aSearches[0]);
630 Debug::printVar('Final query phrases', $aInPhrases);
632 // Convert each phrase to standard form
633 // Create a list of standard words
634 // Get all 'sets' of words
635 // Generate a complete list of all
636 Debug::newSection('Tokenization');
639 foreach ($aInPhrases as $iPhrase => $sPhrase) {
641 $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
642 'Cannot normalize query string (is it a UTF-8 string?)'
644 if (trim($sPhrase)) {
645 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
646 $oPhrase->addTokens($aTokens);
647 $aPhrases[] = $oPhrase;
651 Debug::printDebugTable('Phrases', $aPhrases);
652 Debug::printVar('Tokens', $aTokens);
654 $oValidTokens = new TokenList();
656 if (!empty($aTokens)) {
657 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
658 $sSQL .= ' FROM word ';
659 $sSQL .= ' WHERE word_token in ('.join(',', array_map('getDBQuoted', $aTokens)).')';
661 Debug::printSQL($sSQL);
663 $oValidTokens->addTokensFromDB(
666 $this->aCountryCodes,
671 // Try more interpretations for Tokens that could not be matched.
672 foreach ($aTokens as $sToken) {
673 if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
674 if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
675 // US ZIP+4 codes - merge in the 5-digit ZIP code
676 $oValidTokens->addToken(
678 new Token\Postcode(null, $aData[1], 'us')
680 } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
681 // Unknown single word token with a number.
682 // Assume it is a house number.
683 $oValidTokens->addToken(
685 new Token\HouseNumber(null, trim($sToken))
691 // Any words that have failed completely?
694 Debug::printGroupTable('Valid Tokens', $oValidTokens->debugInfo());
696 Debug::newSection('Search candidates');
698 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens, $bStructuredPhrases);
700 if ($this->bReverseInPlan) {
701 // Reverse phrase array and also reverse the order of the wordsets in
702 // the first and final phrase. Don't bother about phrases in the middle
703 // because order in the address doesn't matter.
704 $aPhrases = array_reverse($aPhrases);
705 $aPhrases[0]->invertWordSets();
706 if (count($aPhrases) > 1) {
707 $aPhrases[count($aPhrases)-1]->invertWordSets();
709 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $oValidTokens, false);
711 foreach ($aGroupedSearches as $aSearches) {
712 foreach ($aSearches as $aSearch) {
713 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
714 $aReverseGroupedSearches[$aSearch->getRank()] = array();
716 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
720 $aGroupedSearches = $aReverseGroupedSearches;
721 ksort($aGroupedSearches);
724 // Re-group the searches by their score, junk anything over 20 as just not worth trying
725 $aGroupedSearches = array();
726 foreach ($aSearches as $aSearch) {
727 if ($aSearch->getRank() < $this->iMaxRank) {
728 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
729 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
732 ksort($aGroupedSearches);
735 // Filter out duplicate searches
736 $aSearchHash = array();
737 foreach ($aGroupedSearches as $iGroup => $aSearches) {
738 foreach ($aSearches as $iSearch => $aSearch) {
739 $sHash = serialize($aSearch);
740 if (isset($aSearchHash[$sHash])) {
741 unset($aGroupedSearches[$iGroup][$iSearch]);
742 if (empty($aGroupedSearches[$iGroup])) unset($aGroupedSearches[$iGroup]);
744 $aSearchHash[$sHash] = 1;
749 Debug::printGroupedSearch(
751 $oValidTokens->debugTokenByWordIdList()
754 // Start the search process
757 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
759 foreach ($aSearches as $oSearch) {
762 Debug::newSection("Search Loop, group $iGroupLoop, loop $iQueryLoop");
763 Debug::printGroupedSearch(
764 array($iGroupedRank => array($oSearch)),
765 $oValidTokens->debugTokenByWordIdList()
768 $aResults += $oSearch->query(
770 $this->iMinAddressRank,
771 $this->iMaxAddressRank,
775 if ($iQueryLoop > 20) break;
778 if (!empty($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
779 // Need to verify passes rank limits before dropping out of the loop (yuk!)
780 // reduces the number of place ids, like a filter
781 // rank_address is 30 for interpolated housenumbers
782 $aFilterSql = array();
783 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
785 $sSQL = 'SELECT place_id FROM placex ';
786 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
788 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
789 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
790 $sSQL .= " OR (extratags->'place') = 'city'";
792 if ($this->aAddressRankList) {
793 $sSQL .= ' OR placex.rank_address in ('.join(',', $this->aAddressRankList).')';
796 $aFilterSql[] = $sSQL;
798 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
800 $sSQL = ' SELECT place_id FROM location_postcode lp ';
801 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
802 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
803 if ($this->aAddressRankList) {
804 $sSQL .= ' OR lp.rank_address in ('.join(',', $this->aAddressRankList).')';
807 $aFilterSql[] = $sSQL;
810 $aFilteredIDs = array();
812 $sSQL = join(' UNION ', $aFilterSql);
813 Debug::printSQL($sSQL);
814 $aFilteredIDs = chksql($this->oDB->getCol($sSQL));
818 foreach ($aResults as $oResult) {
819 if (($this->iMaxAddressRank == 30 &&
820 ($oResult->iTable == Result::TABLE_OSMLINE
821 || $oResult->iTable == Result::TABLE_AUX
822 || $oResult->iTable == Result::TABLE_TIGER))
823 || in_array($oResult->iId, $aFilteredIDs)
825 $tempIDs[$oResult->iId] = $oResult;
828 $aResults = $tempIDs;
831 if (!empty($aResults)) break;
832 if ($iGroupLoop > 4) break;
833 if ($iQueryLoop > 30) break;
836 // Just interpret as a reverse geocode
837 $oReverse = new ReverseGeocode($this->oDB);
838 $oReverse->setZoom(18);
840 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
842 Debug::printVar('Reverse search', $oLookup);
845 $aResults = array($oLookup->iId => $oLookup);
850 if (empty($aResults)) {
851 if ($this->bFallback) {
852 if ($this->fallbackStructuredQuery()) {
853 return $this->lookup();
860 if ($this->aAddressRankList) {
861 $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
863 $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
864 $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
865 if ($oCtx->hasNearPoint()) {
866 $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
869 $aSearchResults = $this->oPlaceLookup->lookup($aResults);
871 $aClassType = getClassTypesWithImportance();
872 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
873 foreach ($aRecheckWords as $i => $sWord) {
874 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
877 Debug::printVar('Recheck words', $aRecheckWords);
879 foreach ($aSearchResults as $iIdx => $aResult) {
881 $fDiameter = getResultDiameter($aResult);
883 $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
884 if ($aOutlineResult) {
885 $aResult = array_merge($aResult, $aOutlineResult);
888 if ($aResult['extra_place'] == 'city') {
889 $aResult['class'] = 'place';
890 $aResult['type'] = 'city';
891 $aResult['rank_search'] = 16;
894 // Is there an icon set for this type of result?
895 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
896 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
898 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
901 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
902 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
904 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
905 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
906 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
908 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
910 // if tag '&addressdetails=1' is set in query
911 if ($this->bIncludeAddressDetails) {
912 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
913 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResults[$aResult['place_id']]->iHouseNumber);
914 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
915 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
919 $aResult['name'] = $aResult['langaddress'];
921 if ($oCtx->hasNearPoint()) {
922 $aResult['importance'] = 0.001;
923 $aResult['foundorder'] = $aResult['addressimportance'];
925 $aResult['importance'] = max(0.001, $aResult['importance']);
926 $aResult['importance'] *= $this->viewboxImportanceFactor(
930 // Adjust importance for the number of exact string matches in the result
932 $sAddress = $aResult['langaddress'];
933 foreach ($aRecheckWords as $i => $sWord) {
934 if (stripos($sAddress, $sWord)!==false) {
936 if (preg_match('/(^|,)\s*'.preg_quote($sWord, '/').'\s*(,|$)/', $sAddress)) $iCountWords += 0.1;
940 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1); // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
942 // secondary ordering (for results with same importance (the smaller the better):
943 // - approximate importance of address parts
944 $aResult['foundorder'] = -$aResult['addressimportance']/10;
945 // - number of exact matches from the query
946 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
947 // - importance of the class/type
948 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
949 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
951 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
953 $aResult['foundorder'] += 0.01;
956 $aSearchResults[$iIdx] = $aResult;
958 uasort($aSearchResults, 'byImportance');
959 Debug::printVar('Pre-filter results', $aSearchResults);
961 $aOSMIDDone = array();
962 $aClassTypeNameDone = array();
963 $aToFilter = $aSearchResults;
964 $aSearchResults = array();
967 foreach ($aToFilter as $aResult) {
968 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
970 $fLat = $aResult['lat'];
971 $fLon = $aResult['lon'];
972 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
975 if (!$this->oPlaceLookup->doDeDupe() || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
976 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
978 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
979 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
980 $aSearchResults[] = $aResult;
983 // Absolute limit on number of results
984 if (count($aSearchResults) >= $this->iFinalLimit) break;
987 Debug::printVar('Post-filter results', $aSearchResults);
988 return $aSearchResults;
991 public function debugInfo()
994 'Query' => $this->sQuery,
995 'Structured query' => $this->aStructuredQuery,
996 'Name keys' => Debug::fmtArrayVals($this->aLangPrefOrder),
997 'Include address' => $this->bIncludeAddressDetails,
998 'Excluded place IDs' => Debug::fmtArrayVals($this->aExcludePlaceIDs),
999 'Try reversed query'=> $this->bReverseInPlan,
1000 'Limit (for searches)' => $this->iLimit,
1001 'Limit (for results)'=> $this->iFinalLimit,
1002 'Country codes' => Debug::fmtArrayVals($this->aCountryCodes),
1003 'Bounded search' => $this->bBoundedSearch,
1004 'Viewbox' => Debug::fmtArrayVals($this->aViewBox),
1005 'Route points' => Debug::fmtArrayVals($this->aRoutePoints),
1006 'Route width' => $this->aRouteWidth,
1007 'Max rank' => $this->iMaxRank,
1008 'Min address rank' => $this->iMinAddressRank,
1009 'Max address rank' => $this->iMaxAddressRank,
1010 'Address rank list' => Debug::fmtArrayVals($this->aAddressRankList)