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');
15 protected $oPlaceLookup;
17 protected $aLangPrefOrder = array();
19 protected $bIncludeAddressDetails = false;
21 protected $aExcludePlaceIDs = array();
22 protected $bReverseInPlan = false;
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;
46 protected $oNormalizer = null;
49 public function __construct(&$oDB)
52 $this->oPlaceLookup = new PlaceLookup($this->oDB);
53 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
56 private function normTerm($sTerm)
58 if ($this->oNormalizer === null) {
62 return $this->oNormalizer->transliterate($sTerm);
65 public function setReverseInPlan($bReverse)
67 $this->bReverseInPlan = $bReverse;
70 public function setLanguagePreference($aLangPref)
72 $this->aLangPrefOrder = $aLangPref;
75 public function getMoreUrlParams()
77 if ($this->aStructuredQuery) {
78 $aParams = $this->aStructuredQuery;
80 $aParams = array('q' => $this->sQuery);
83 $aParams = array_merge($aParams, $this->oPlaceLookup->getMoreUrlParams());
85 if ($this->aExcludePlaceIDs) {
86 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
89 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
90 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
92 if ($this->aCountryCodes) {
93 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
96 if ($this->aViewBox) {
97 $aParams['viewbox'] = join(',', $this->aViewBox);
103 public function setLimit($iLimit = 10)
105 if ($iLimit > 50) $iLimit = 50;
106 if ($iLimit < 1) $iLimit = 1;
108 $this->iFinalLimit = $iLimit;
109 $this->iLimit = $iLimit + min($iLimit, 10);
112 public function setFeatureType($sFeatureType)
114 switch ($sFeatureType) {
116 $this->setRankRange(4, 4);
119 $this->setRankRange(8, 8);
122 $this->setRankRange(14, 16);
125 $this->setRankRange(8, 20);
130 public function setRankRange($iMin, $iMax)
132 $this->iMinAddressRank = $iMin;
133 $this->iMaxAddressRank = $iMax;
136 public function setViewbox($aViewbox)
138 $aBox = array_map('floatval', $aViewbox);
140 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
141 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
142 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
143 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
145 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
146 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
148 userError("Bad parameter 'viewbox'. Not a box.");
152 private function viewboxImportanceFactor($fX, $fY)
154 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
155 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
157 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
158 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
160 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
164 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
171 public function setQuery($sQueryString)
173 $this->sQuery = $sQueryString;
174 $this->aStructuredQuery = false;
177 public function getQueryString()
179 return $this->sQuery;
183 public function loadParamArray($oParams, $sForceGeometryType = null)
185 $this->bIncludeAddressDetails
186 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
188 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
190 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
191 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
193 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
195 // List of excluded Place IDs - used for more acurate pageing
196 $sExcluded = $oParams->getStringList('exclude_place_ids');
198 foreach ($sExcluded as $iExcludedPlaceID) {
199 $iExcludedPlaceID = (int)$iExcludedPlaceID;
200 if ($iExcludedPlaceID)
201 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
204 if (isset($aExcludePlaceIDs))
205 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
208 // Only certain ranks of feature
209 $sFeatureType = $oParams->getString('featureType');
210 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
211 if ($sFeatureType) $this->setFeatureType($sFeatureType);
214 $sCountries = $oParams->getStringList('countrycodes');
216 foreach ($sCountries as $sCountryCode) {
217 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
218 $aCountries[] = strtolower($sCountryCode);
221 if (isset($aCountries))
222 $this->aCountryCodes = $aCountries;
225 $aViewbox = $oParams->getStringList('viewboxlbrt');
227 if (count($aViewbox) != 4) {
228 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
230 $this->setViewbox($aViewbox);
232 $aViewbox = $oParams->getStringList('viewbox');
234 if (count($aViewbox) != 4) {
235 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
237 $this->setViewBox($aViewbox);
239 $aRoute = $oParams->getStringList('route');
240 $fRouteWidth = $oParams->getFloat('routewidth');
241 if ($aRoute && $fRouteWidth) {
242 $this->aRoutePoints = $aRoute;
243 $this->aRouteWidth = $fRouteWidth;
248 $this->oPlaceLookup->loadParamArray($oParams, $sForceGeometryType);
249 $this->oPlaceLookup->setIncludeAddressDetails(false);
250 $this->oPlaceLookup->setIncludePolygonAsPoints($oParams->getBool('polygon'));
253 public function setQueryFromParams($oParams)
256 $sQuery = $oParams->getString('q');
258 $this->setStructuredQuery(
259 $oParams->getString('amenity'),
260 $oParams->getString('street'),
261 $oParams->getString('city'),
262 $oParams->getString('county'),
263 $oParams->getString('state'),
264 $oParams->getString('country'),
265 $oParams->getString('postalcode')
267 $this->setReverseInPlan(false);
269 $this->setQuery($sQuery);
273 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
275 $sValue = trim($sValue);
276 if (!$sValue) return false;
277 $this->aStructuredQuery[$sKey] = $sValue;
278 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
279 $this->iMinAddressRank = $iNewMinAddressRank;
280 $this->iMaxAddressRank = $iNewMaxAddressRank;
282 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
286 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
288 $this->sQuery = false;
291 $this->iMinAddressRank = 0;
292 $this->iMaxAddressRank = 30;
293 $this->aAddressRankList = array();
295 $this->aStructuredQuery = array();
296 $this->sAllowedTypesSQLList = false;
298 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
299 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
300 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
301 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
302 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
303 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
304 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
306 if (sizeof($this->aStructuredQuery) > 0) {
307 $this->sQuery = join(', ', $this->aStructuredQuery);
308 if ($this->iMaxAddressRank < 30) {
309 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
314 public function fallbackStructuredQuery()
316 if (!$this->aStructuredQuery) return false;
318 $aParams = $this->aStructuredQuery;
320 if (sizeof($aParams) == 1) return false;
322 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
324 foreach ($aOrderToFallback as $sType) {
325 if (isset($aParams[$sType])) {
326 unset($aParams[$sType]);
327 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
335 public function getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bIsStructured)
338 Calculate all searches using aValidTokens i.e.
339 'Wodsworth Road, Sheffield' =>
343 0 1 (wodsworth)(road)
346 Score how good the search is so they can be ordered
348 foreach ($aPhrases as $iPhrase => $oPhrase) {
349 $aNewPhraseSearches = array();
350 $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
352 foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
353 // Too many permutations - too expensive
354 if ($iWordSet > 120) break;
356 $aWordsetSearches = $aSearches;
358 // Add all words from this wordset
359 foreach ($aWordset as $iToken => $sToken) {
360 //echo "<br><b>$sToken</b>";
361 $aNewWordsetSearches = array();
363 foreach ($aWordsetSearches as $oCurrentSearch) {
365 //var_dump($oCurrentSearch);
368 // If the token is valid
369 if (isset($aValidTokens[' '.$sToken])) {
370 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
371 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
373 isset($aValidTokens[$sToken])
374 && strpos($sToken, ' ') === false,
376 $iToken == 0 && $iPhrase == 0,
378 $iToken + 1 == sizeof($aWordset)
379 && $iPhrase + 1 == sizeof($aPhrases)
382 foreach ($aNewSearches as $oSearch) {
383 if ($oSearch->getRank() < $this->iMaxRank) {
384 $aNewWordsetSearches[] = $oSearch;
389 // Look for partial matches.
390 // Note that there is no point in adding country terms here
391 // because country is omitted in the address.
392 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
393 // Allow searching for a word - but at extra cost
394 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
395 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
399 isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
402 foreach ($aNewSearches as $oSearch) {
403 if ($oSearch->getRank() < $this->iMaxRank) {
404 $aNewWordsetSearches[] = $oSearch;
411 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
412 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
414 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
416 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
417 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
419 $aSearchHash = array();
420 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
421 $sHash = serialize($aSearch);
422 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
423 else $aSearchHash[$sHash] = 1;
426 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
429 // Re-group the searches by their score, junk anything over 20 as just not worth trying
430 $aGroupedSearches = array();
431 foreach ($aNewPhraseSearches as $aSearch) {
432 $iRank = $aSearch->getRank();
433 if ($iRank < $this->iMaxRank) {
434 if (!isset($aGroupedSearches[$iRank])) {
435 $aGroupedSearches[$iRank] = array();
437 $aGroupedSearches[$iRank][] = $aSearch;
440 ksort($aGroupedSearches);
443 $aSearches = array();
444 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
445 $iSearchCount += sizeof($aNewSearches);
446 $aSearches = array_merge($aSearches, $aNewSearches);
447 if ($iSearchCount > 50) break;
450 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
453 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
454 $aGroupedSearches = array();
455 foreach ($aSearches as $oSearch) {
456 if (!$oSearch->isValidSearch()) {
460 if (!isset($aGroupedSearches[$iRank])) {
461 $aGroupedSearches[$iRank] = array();
463 $aGroupedSearches[$iRank][] = $oSearch;
465 ksort($aGroupedSearches);
467 return $aGroupedSearches;
470 /* Perform the actual query lookup.
472 Returns an ordered list of results, each with the following fields:
473 osm_type: type of corresponding OSM object
477 P - postcode (internally computed)
478 osm_id: id of corresponding OSM object
479 class: general object class (corresponds to tag key of primary OSM tag)
480 type: subclass of object (corresponds to tag value of primary OSM tag)
481 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
482 rank_search: rank in search hierarchy
483 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
484 rank_address: rank in address hierarchy (determines orer in address)
485 place_id: internal key (may differ between different instances)
486 country_code: ISO country code
487 langaddress: localized full address
488 placename: localized name of object
489 ref: content of ref tag (if available)
492 importance: importance of place based on Wikipedia link count
493 addressimportance: cumulated importance of address elements
494 extra_place: type of place (for admin boundaries, if there is a place tag)
495 aBoundingBox: bounding Box
496 label: short description of the object class/type (English only)
497 name: full name (currently the same as langaddress)
498 foundorder: secondary ordering for places with same importance
502 public function lookup()
504 if (!$this->sQuery && !$this->aStructuredQuery) return array();
506 $oCtx = new SearchContext();
508 if ($this->aRoutePoints) {
509 $oCtx->setViewboxFromRoute(
513 $this->bBoundedSearch
515 } elseif ($this->aViewBox) {
516 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
518 if ($this->aExcludePlaceIDs) {
519 $oCtx->setExcludeList($this->aExcludePlaceIDs);
521 if ($this->aCountryCodes) {
522 $oCtx->setCountryList($this->aCountryCodes);
525 $sNormQuery = $this->normTerm($this->sQuery);
526 $sLanguagePrefArraySQL = getArraySQL(
527 array_map("getDBQuoted", $this->aLangPrefOrder)
530 $sQuery = $this->sQuery;
531 if (!preg_match('//u', $sQuery)) {
532 userError("Query string is not UTF-8 encoded.");
535 // Conflicts between US state abreviations and various words for 'the' in different languages
536 if (isset($this->aLangPrefOrder['name:en'])) {
537 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
538 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
539 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
542 // Do we have anything that looks like a lat/lon pair?
543 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
546 if ($sQuery || $this->aStructuredQuery) {
547 // Start with a single blank search
548 $aSearches = array(new SearchDescription($oCtx));
551 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
557 '/\\[([\\w ]*)\\]/u',
562 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
563 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
564 if (!$sSpecialTerm) {
565 $sSpecialTerm = $aSpecialTerm[1];
569 if (!$sSpecialTerm && $this->aStructuredQuery
570 && isset($this->aStructuredQuery['amenity'])) {
571 $sSpecialTerm = $this->aStructuredQuery['amenity'];
572 unset($this->aStructuredQuery['amenity']);
575 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
576 $sSpecialTerm = pg_escape_string($sSpecialTerm);
578 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
579 "Cannot decode query. Wrong encoding?"
581 $sSQL = 'SELECT class, type FROM word ';
582 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
583 $sSQL .= ' AND class is not null AND class not in (\'place\')';
584 if (CONST_Debug) var_Dump($sSQL);
585 $aSearchWords = chksql($this->oDB->getAll($sSQL));
586 $aNewSearches = array();
587 foreach ($aSearches as $oSearch) {
588 foreach ($aSearchWords as $aSearchTerm) {
589 $oNewSearch = clone $oSearch;
590 $oNewSearch->setPoiSearch(
592 $aSearchTerm['class'],
595 $aNewSearches[] = $oNewSearch;
598 $aSearches = $aNewSearches;
601 // Split query into phrases
602 // Commas are used to reduce the search space by indicating where phrases split
603 if ($this->aStructuredQuery) {
604 $aInPhrases = $this->aStructuredQuery;
605 $bStructuredPhrases = true;
607 $aInPhrases = explode(',', $sQuery);
608 $bStructuredPhrases = false;
611 // Convert each phrase to standard form
612 // Create a list of standard words
613 // Get all 'sets' of words
614 // Generate a complete list of all
617 foreach ($aInPhrases as $iPhrase => $sPhrase) {
619 $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
620 "Cannot normalize query string (is it a UTF-8 string?)"
622 if (trim($sPhrase)) {
623 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
624 $oPhrase->addTokens($aTokens);
625 $aPhrases[] = $oPhrase;
629 if (sizeof($aTokens)) {
630 // Check which tokens we have, get the ID numbers
631 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
632 $sSQL .= ' FROM word ';
633 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
635 if (CONST_Debug) var_Dump($sSQL);
637 $aValidTokens = array();
638 $aDatabaseWords = chksql(
639 $this->oDB->getAll($sSQL),
640 "Could not get word tokens."
642 $aWordFrequencyScores = array();
643 foreach ($aDatabaseWords as $aToken) {
644 // Filter country tokens that do not match restricted countries.
645 if ($this->aCountryCodes
646 && $aToken['country_code']
647 && !in_array($aToken['country_code'], $this->aCountryCodes)
652 // Special terms need to appear in their normalized form.
653 if ($aToken['word'] && $aToken['class']) {
654 $sNormWord = $this->normTerm($aToken['word']);
655 if (strpos($sNormQuery, $sNormWord) === false) {
660 if (isset($aValidTokens[$aToken['word_token']])) {
661 $aValidTokens[$aToken['word_token']][] = $aToken;
663 $aValidTokens[$aToken['word_token']] = array($aToken);
665 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
667 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
669 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
670 foreach ($aTokens as $sToken) {
671 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
672 if (isset($aValidTokens[$aData[1]])) {
673 foreach ($aValidTokens[$aData[1]] as $aToken) {
674 if (!$aToken['class']) {
675 if (isset($aValidTokens[$sToken])) {
676 $aValidTokens[$sToken][] = $aToken;
678 $aValidTokens[$sToken] = array($aToken);
686 foreach ($aTokens as $sToken) {
687 // Unknown single word token with a number - assume it is a house number
688 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
689 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
693 // Any words that have failed completely?
696 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bStructuredPhrases);
698 if ($this->bReverseInPlan) {
699 // Reverse phrase array and also reverse the order of the wordsets in
700 // the first and final phrase. Don't bother about phrases in the middle
701 // because order in the address doesn't matter.
702 $aPhrases = array_reverse($aPhrases);
703 $aPhrases[0]->invertWordSets();
704 if (sizeof($aPhrases) > 1) {
705 $aPhrases[sizeof($aPhrases)-1]->invertWordSets();
707 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, false);
709 foreach ($aGroupedSearches as $aSearches) {
710 foreach ($aSearches as $aSearch) {
711 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
712 $aReverseGroupedSearches[$aSearch->getRank()] = array();
714 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
718 $aGroupedSearches = $aReverseGroupedSearches;
719 ksort($aGroupedSearches);
722 // Re-group the searches by their score, junk anything over 20 as just not worth trying
723 $aGroupedSearches = array();
724 foreach ($aSearches as $aSearch) {
725 if ($aSearch->getRank() < $this->iMaxRank) {
726 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
727 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
730 ksort($aGroupedSearches);
733 // Filter out duplicate searches
734 $aSearchHash = array();
735 foreach ($aGroupedSearches as $iGroup => $aSearches) {
736 foreach ($aSearches as $iSearch => $aSearch) {
737 $sHash = serialize($aSearch);
738 if (isset($aSearchHash[$sHash])) {
739 unset($aGroupedSearches[$iGroup][$iSearch]);
740 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
742 $aSearchHash[$sHash] = 1;
747 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
749 // Start the search process
752 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
754 foreach ($aSearches as $oSearch) {
758 echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
759 _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
762 $aResults += $oSearch->query(
764 $aWordFrequencyScores,
765 $this->iMinAddressRank,
766 $this->iMaxAddressRank,
770 if ($iQueryLoop > 20) break;
773 if (sizeof($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
774 // Need to verify passes rank limits before dropping out of the loop (yuk!)
775 // reduces the number of place ids, like a filter
776 // rank_address is 30 for interpolated housenumbers
777 $aFilterSql = array();
778 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
780 $sSQL = 'SELECT place_id FROM placex ';
781 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
783 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
784 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
785 $sSQL .= " OR (extratags->'place') = 'city'";
787 if ($this->aAddressRankList) {
788 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
791 $aFilterSql[] = $sSQL;
793 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
795 $sSQL = ' SELECT place_id FROM location_postcode lp ';
796 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
797 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
798 if ($this->aAddressRankList) {
799 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
802 $aFilterSql[] = $sSQL;
805 $aFilteredIDs = array();
807 $sSQL = join(' UNION ', $aFilterSql);
808 if (CONST_Debug) var_dump($sSQL);
809 $aFilteredIDs = chksql($this->oDB->getCol($sSQL));
813 foreach ($aResults as $oResult) {
814 if (($this->iMaxAddressRank == 30 &&
815 ($oResult->iTable == Result::TABLE_OSMLINE
816 || $oResult->iTable == Result::TABLE_AUX
817 || $oResult->iTable == Result::TABLE_TIGER))
818 || in_array($oResult->iId, $aFilteredIDs)
820 $tempIDs[$oResult->iId] = $oResult;
823 $aResults = $tempIDs;
826 if (sizeof($aResults)) break;
827 if ($iGroupLoop > 4) break;
828 if ($iQueryLoop > 30) break;
831 // Just interpret as a reverse geocode
832 $oReverse = new ReverseGeocode($this->oDB);
833 $oReverse->setZoom(18);
835 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
837 if (CONST_Debug) var_dump("Reverse search", $aLookup);
840 $aResults = array($oLookup->iId => $oLookup);
845 if (!sizeof($aResults)) {
846 if ($this->bFallback) {
847 if ($this->fallbackStructuredQuery()) {
848 return $this->lookup();
855 if ($this->aAddressRankList) {
856 $this->oPlaceLookup->setAddressRankList($this->aAddressRankList);
858 $this->oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
859 $this->oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
860 if ($oCtx->hasNearPoint()) {
861 $this->oPlaceLookup->setAnchorSql($oCtx->sqlNear);
864 $aSearchResults = $this->oPlaceLookup->lookup($aResults);
866 $aClassType = getClassTypesWithImportance();
867 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
868 foreach ($aRecheckWords as $i => $sWord) {
869 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
873 echo '<i>Recheck words:<\i>';
874 var_dump($aRecheckWords);
877 foreach ($aSearchResults as $iIdx => $aResult) {
879 $fDiameter = getResultDiameter($aResult);
881 $aOutlineResult = $this->oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
882 if ($aOutlineResult) {
883 $aResult = array_merge($aResult, $aOutlineResult);
886 if ($aResult['extra_place'] == 'city') {
887 $aResult['class'] = 'place';
888 $aResult['type'] = 'city';
889 $aResult['rank_search'] = 16;
892 // Is there an icon set for this type of result?
893 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
894 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
896 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
899 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
900 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
902 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
903 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
904 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
906 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
908 // if tag '&addressdetails=1' is set in query
909 if ($this->bIncludeAddressDetails) {
910 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
911 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResults[$aResult['place_id']]->iHouseNumber);
912 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
913 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
917 $aResult['name'] = $aResult['langaddress'];
919 if ($oCtx->hasNearPoint()) {
920 $aResult['importance'] = 0.001;
921 $aResult['foundorder'] = $aResult['addressimportance'];
923 // Adjust importance for the number of exact string matches in the result
924 $aResult['importance'] *= $this->viewboxImportanceFactor(
928 $aResult['importance'] = max(0.001, $aResult['importance']);
930 $sAddress = $aResult['langaddress'];
931 foreach ($aRecheckWords as $i => $sWord) {
932 if (stripos($sAddress, $sWord)!==false) {
934 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
938 $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
940 // secondary ordering (for results with same importance (the smaller the better):
941 // - approximate importance of address parts
942 $aResult['foundorder'] = -$aResult['addressimportance']/10;
943 // - number of exact matches from the query
944 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
945 // - importance of the class/type
946 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
947 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
949 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
951 $aResult['foundorder'] += 0.01;
954 if (CONST_Debug) var_dump($aResult);
955 $aSearchResults[$iIdx] = $aResult;
957 uasort($aSearchResults, 'byImportance');
959 $aOSMIDDone = array();
960 $aClassTypeNameDone = array();
961 $aToFilter = $aSearchResults;
962 $aSearchResults = array();
964 if (CONST_Debug) var_dump($aToFilter);
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 (sizeof($aSearchResults) >= $this->iFinalLimit) break;
987 if (CONST_Debug) var_dump($aSearchResults);
988 return $aSearchResults;