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 $aLangPrefOrder = array();
17 protected $bIncludeAddressDetails = false;
18 protected $bIncludeExtraTags = false;
19 protected $bIncludeNameDetails = false;
21 protected $bIncludePolygonAsPoints = false;
22 protected $bIncludePolygonAsText = false;
23 protected $bIncludePolygonAsGeoJSON = false;
24 protected $bIncludePolygonAsKML = false;
25 protected $bIncludePolygonAsSVG = false;
26 protected $fPolygonSimplificationThreshold = 0.0;
28 protected $aExcludePlaceIDs = array();
29 protected $bDeDupe = true;
30 protected $bReverseInPlan = false;
32 protected $iLimit = 20;
33 protected $iFinalLimit = 10;
34 protected $iOffset = 0;
35 protected $bFallback = false;
37 protected $aCountryCodes = false;
39 protected $bBoundedSearch = false;
40 protected $aViewBox = false;
41 protected $aRoutePoints = false;
42 protected $aRouteWidth = false;
44 protected $iMaxRank = 20;
45 protected $iMinAddressRank = 0;
46 protected $iMaxAddressRank = 30;
47 protected $aAddressRankList = array();
49 protected $sAllowedTypesSQLList = false;
51 protected $sQuery = false;
52 protected $aStructuredQuery = false;
54 protected $oNormalizer = null;
57 public function __construct(&$oDB)
60 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
63 private function normTerm($sTerm)
65 if ($this->oNormalizer === null) {
69 return $this->oNormalizer->transliterate($sTerm);
72 public function setReverseInPlan($bReverse)
74 $this->bReverseInPlan = $bReverse;
77 public function setLanguagePreference($aLangPref)
79 $this->aLangPrefOrder = $aLangPref;
82 public function getMoreUrlParams()
84 if ($this->aStructuredQuery) {
85 $aParams = $this->aStructuredQuery;
87 $aParams = array('q' => $this->sQuery);
90 if ($this->aExcludePlaceIDs) {
91 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
94 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
95 if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
96 if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
98 if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
99 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
100 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
101 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
102 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
104 if ($this->fPolygonSimplificationThreshold > 0.0) {
105 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
108 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
109 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
111 if ($this->aCountryCodes) {
112 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
115 if ($this->aViewBox) {
116 $aParams['viewbox'] = join(',', $this->aViewBox);
122 public function setIncludePolygonAsPoints($b = true)
124 $this->bIncludePolygonAsPoints = $b;
127 public function setIncludePolygonAsText($b = true)
129 $this->bIncludePolygonAsText = $b;
132 public function setIncludePolygonAsGeoJSON($b = true)
134 $this->bIncludePolygonAsGeoJSON = $b;
137 public function setIncludePolygonAsKML($b = true)
139 $this->bIncludePolygonAsKML = $b;
142 public function setIncludePolygonAsSVG($b = true)
144 $this->bIncludePolygonAsSVG = $b;
147 public function setPolygonSimplificationThreshold($f)
149 $this->fPolygonSimplificationThreshold = $f;
152 public function setLimit($iLimit = 10)
154 if ($iLimit > 50) $iLimit = 50;
155 if ($iLimit < 1) $iLimit = 1;
157 $this->iFinalLimit = $iLimit;
158 $this->iLimit = $iLimit + min($iLimit, 10);
161 public function setFeatureType($sFeatureType)
163 switch ($sFeatureType) {
165 $this->setRankRange(4, 4);
168 $this->setRankRange(8, 8);
171 $this->setRankRange(14, 16);
174 $this->setRankRange(8, 20);
179 public function setRankRange($iMin, $iMax)
181 $this->iMinAddressRank = $iMin;
182 $this->iMaxAddressRank = $iMax;
185 public function setViewbox($aViewbox)
187 $aBox = array_map('floatval', $aViewbox);
189 $this->aViewBox[0] = max(-180.0, min($aBox[0], $aBox[2]));
190 $this->aViewBox[1] = max(-90.0, min($aBox[1], $aBox[3]));
191 $this->aViewBox[2] = min(180.0, max($aBox[0], $aBox[2]));
192 $this->aViewBox[3] = min(90.0, max($aBox[1], $aBox[3]));
194 if ($this->aViewBox[2] - $this->aViewBox[0] < 0.000000001
195 || $this->aViewBox[3] - $this->aViewBox[1] < 0.000000001
197 userError("Bad parameter 'viewbox'. Not a box.");
201 private function viewboxImportanceFactor($fX, $fY)
203 $fWidth = ($this->aViewBox[2] - $this->aViewBox[0])/2;
204 $fHeight = ($this->aViewBox[3] - $this->aViewBox[1])/2;
206 $fXDist = abs($fX - ($this->aViewBox[0] + $this->aViewBox[2])/2);
207 $fYDist = abs($fY - ($this->aViewBox[1] + $this->aViewBox[3])/2);
209 if ($fXDist <= $fWidth && $fYDist <= $fHeight) {
213 if ($fXDist <= $fWidth * 3 && $fYDist <= 3 * $fHeight) {
220 public function setQuery($sQueryString)
222 $this->sQuery = $sQueryString;
223 $this->aStructuredQuery = false;
226 public function getQueryString()
228 return $this->sQuery;
232 public function loadParamArray($oParams)
234 $this->bIncludeAddressDetails
235 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
236 $this->bIncludeExtraTags
237 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
238 $this->bIncludeNameDetails
239 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
241 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
242 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
244 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
245 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
247 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
249 // List of excluded Place IDs - used for more acurate pageing
250 $sExcluded = $oParams->getStringList('exclude_place_ids');
252 foreach ($sExcluded as $iExcludedPlaceID) {
253 $iExcludedPlaceID = (int)$iExcludedPlaceID;
254 if ($iExcludedPlaceID)
255 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
258 if (isset($aExcludePlaceIDs))
259 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
262 // Only certain ranks of feature
263 $sFeatureType = $oParams->getString('featureType');
264 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
265 if ($sFeatureType) $this->setFeatureType($sFeatureType);
268 $sCountries = $oParams->getStringList('countrycodes');
270 foreach ($sCountries as $sCountryCode) {
271 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
272 $aCountries[] = strtolower($sCountryCode);
275 if (isset($aCountries))
276 $this->aCountryCodes = $aCountries;
279 $aViewbox = $oParams->getStringList('viewboxlbrt');
281 if (count($aViewbox) != 4) {
282 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
284 $this->setViewbox($aViewbox);
286 $aViewbox = $oParams->getStringList('viewbox');
288 if (count($aViewbox) != 4) {
289 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
291 $this->setViewBox($aViewbox);
293 $aRoute = $oParams->getStringList('route');
294 $fRouteWidth = $oParams->getFloat('routewidth');
295 if ($aRoute && $fRouteWidth) {
296 $this->aRoutePoints = $aRoute;
297 $this->aRouteWidth = $fRouteWidth;
303 public function setQueryFromParams($oParams)
306 $sQuery = $oParams->getString('q');
308 $this->setStructuredQuery(
309 $oParams->getString('amenity'),
310 $oParams->getString('street'),
311 $oParams->getString('city'),
312 $oParams->getString('county'),
313 $oParams->getString('state'),
314 $oParams->getString('country'),
315 $oParams->getString('postalcode')
317 $this->setReverseInPlan(false);
319 $this->setQuery($sQuery);
323 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
325 $sValue = trim($sValue);
326 if (!$sValue) return false;
327 $this->aStructuredQuery[$sKey] = $sValue;
328 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
329 $this->iMinAddressRank = $iNewMinAddressRank;
330 $this->iMaxAddressRank = $iNewMaxAddressRank;
332 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
336 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
338 $this->sQuery = false;
341 $this->iMinAddressRank = 0;
342 $this->iMaxAddressRank = 30;
343 $this->aAddressRankList = array();
345 $this->aStructuredQuery = array();
346 $this->sAllowedTypesSQLList = false;
348 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
349 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
350 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
351 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
352 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
353 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
354 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
356 if (sizeof($this->aStructuredQuery) > 0) {
357 $this->sQuery = join(', ', $this->aStructuredQuery);
358 if ($this->iMaxAddressRank < 30) {
359 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
364 public function fallbackStructuredQuery()
366 if (!$this->aStructuredQuery) return false;
368 $aParams = $this->aStructuredQuery;
370 if (sizeof($aParams) == 1) return false;
372 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
374 foreach ($aOrderToFallback as $sType) {
375 if (isset($aParams[$sType])) {
376 unset($aParams[$sType]);
377 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
385 public function getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bIsStructured)
388 Calculate all searches using aValidTokens i.e.
389 'Wodsworth Road, Sheffield' =>
393 0 1 (wodsworth)(road)
396 Score how good the search is so they can be ordered
400 foreach ($aPhrases as $iPhrase => $oPhrase) {
401 $aNewPhraseSearches = array();
402 $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
404 foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
405 // Too many permutations - too expensive
406 if ($iWordSet > 120) break;
408 $aWordsetSearches = $aSearches;
410 // Add all words from this wordset
411 foreach ($aWordset as $iToken => $sToken) {
412 //echo "<br><b>$sToken</b>";
413 $aNewWordsetSearches = array();
415 foreach ($aWordsetSearches as $oCurrentSearch) {
417 //var_dump($oCurrentSearch);
420 // If the token is valid
421 if (isset($aValidTokens[' '.$sToken])) {
422 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
423 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
425 isset($aValidTokens[$sToken])
426 && strpos($sToken, ' ') === false,
428 $iToken == 0 && $iPhrase == 0,
430 $iToken + 1 == sizeof($aWordset)
431 && $iPhrase + 1 == sizeof($aPhrases),
435 foreach ($aNewSearches as $oSearch) {
436 if ($oSearch->getRank() < $this->iMaxRank) {
437 $aNewWordsetSearches[] = $oSearch;
442 // Look for partial matches.
443 // Note that there is no point in adding country terms here
444 // because country is omitted in the address.
445 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
446 // Allow searching for a word - but at extra cost
447 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
448 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
452 isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
455 foreach ($aNewSearches as $oSearch) {
456 if ($oSearch->getRank() < $this->iMaxRank) {
457 $aNewWordsetSearches[] = $oSearch;
464 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
465 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
467 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
469 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
470 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
472 $aSearchHash = array();
473 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
474 $sHash = serialize($aSearch);
475 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
476 else $aSearchHash[$sHash] = 1;
479 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
482 // Re-group the searches by their score, junk anything over 20 as just not worth trying
483 $aGroupedSearches = array();
484 foreach ($aNewPhraseSearches as $aSearch) {
485 $iRank = $aSearch->getRank();
486 if ($iRank < $this->iMaxRank) {
487 if (!isset($aGroupedSearches[$iRank])) {
488 $aGroupedSearches[$iRank] = array();
490 $aGroupedSearches[$iRank][] = $aSearch;
493 ksort($aGroupedSearches);
496 $aSearches = array();
497 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
498 $iSearchCount += sizeof($aNewSearches);
499 $aSearches = array_merge($aSearches, $aNewSearches);
500 if ($iSearchCount > 50) break;
503 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
506 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
507 $aGroupedSearches = array();
508 foreach ($aSearches as $oSearch) {
509 if (!$oSearch->isValidSearch()) {
513 $iRank = $oSearch->addToRank($iGlobalRank);
514 if (!isset($aGroupedSearches[$iRank])) {
515 $aGroupedSearches[$iRank] = array();
517 $aGroupedSearches[$iRank][] = $oSearch;
519 ksort($aGroupedSearches);
521 return $aGroupedSearches;
524 /* Perform the actual query lookup.
526 Returns an ordered list of results, each with the following fields:
527 osm_type: type of corresponding OSM object
531 P - postcode (internally computed)
532 osm_id: id of corresponding OSM object
533 class: general object class (corresponds to tag key of primary OSM tag)
534 type: subclass of object (corresponds to tag value of primary OSM tag)
535 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
536 rank_search: rank in search hierarchy
537 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
538 rank_address: rank in address hierarchy (determines orer in address)
539 place_id: internal key (may differ between different instances)
540 country_code: ISO country code
541 langaddress: localized full address
542 placename: localized name of object
543 ref: content of ref tag (if available)
546 importance: importance of place based on Wikipedia link count
547 addressimportance: cumulated importance of address elements
548 extra_place: type of place (for admin boundaries, if there is a place tag)
549 aBoundingBox: bounding Box
550 label: short description of the object class/type (English only)
551 name: full name (currently the same as langaddress)
552 foundorder: secondary ordering for places with same importance
556 public function lookup()
558 if (!$this->sQuery && !$this->aStructuredQuery) return array();
560 $oCtx = new SearchContext();
562 if ($this->aRoutePoints) {
563 $oCtx->setViewboxFromRoute(
567 $this->bBoundedSearch
569 } elseif ($this->aViewBox) {
570 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
572 if ($this->aExcludePlaceIDs) {
573 $oCtx->setExcludeList($this->aExcludePlaceIDs);
575 if ($this->aCountryCodes) {
576 $oCtx->setCountryList($this->aCountryCodes);
579 $sNormQuery = $this->normTerm($this->sQuery);
580 $sLanguagePrefArraySQL = getArraySQL(
581 array_map("getDBQuoted", $this->aLangPrefOrder)
584 $sQuery = $this->sQuery;
585 if (!preg_match('//u', $sQuery)) {
586 userError("Query string is not UTF-8 encoded.");
589 // Conflicts between US state abreviations and various words for 'the' in different languages
590 if (isset($this->aLangPrefOrder['name:en'])) {
591 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
592 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
593 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
596 // Do we have anything that looks like a lat/lon pair?
597 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
600 if ($sQuery || $this->aStructuredQuery) {
601 // Start with a single blank search
602 $aSearches = array(new SearchDescription($oCtx));
605 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
611 '/\\[([\\w ]*)\\]/u',
616 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
617 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
618 if (!$sSpecialTerm) {
619 $sSpecialTerm = $aSpecialTerm[1];
623 if (!$sSpecialTerm && $this->aStructuredQuery
624 && isset($this->aStructuredQuery['amenity'])) {
625 $sSpecialTerm = $this->aStructuredQuery['amenity'];
626 unset($this->aStructuredQuery['amenity']);
629 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
630 $sSpecialTerm = pg_escape_string($sSpecialTerm);
632 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
633 "Cannot decode query. Wrong encoding?"
635 $sSQL = 'SELECT class, type FROM word ';
636 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
637 $sSQL .= ' AND class is not null AND class not in (\'place\')';
638 if (CONST_Debug) var_Dump($sSQL);
639 $aSearchWords = chksql($this->oDB->getAll($sSQL));
640 $aNewSearches = array();
641 foreach ($aSearches as $oSearch) {
642 foreach ($aSearchWords as $aSearchTerm) {
643 $oNewSearch = clone $oSearch;
644 $oNewSearch->setPoiSearch(
646 $aSearchTerm['class'],
649 $aNewSearches[] = $oNewSearch;
652 $aSearches = $aNewSearches;
655 // Split query into phrases
656 // Commas are used to reduce the search space by indicating where phrases split
657 if ($this->aStructuredQuery) {
658 $aInPhrases = $this->aStructuredQuery;
659 $bStructuredPhrases = true;
661 $aInPhrases = explode(',', $sQuery);
662 $bStructuredPhrases = false;
665 // Convert each phrase to standard form
666 // Create a list of standard words
667 // Get all 'sets' of words
668 // Generate a complete list of all
671 foreach ($aInPhrases as $iPhrase => $sPhrase) {
673 $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
674 "Cannot normalize query string (is it a UTF-8 string?)"
676 if (trim($sPhrase)) {
677 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
678 $oPhrase->addTokens($aTokens);
679 $aPhrases[] = $oPhrase;
683 if (sizeof($aTokens)) {
684 // Check which tokens we have, get the ID numbers
685 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
686 $sSQL .= ' FROM word ';
687 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
689 if (CONST_Debug) var_Dump($sSQL);
691 $aValidTokens = array();
692 $aDatabaseWords = chksql(
693 $this->oDB->getAll($sSQL),
694 "Could not get word tokens."
696 $aWordFrequencyScores = array();
697 foreach ($aDatabaseWords as $aToken) {
698 // Filter country tokens that do not match restricted countries.
699 if ($this->aCountryCodes
700 && $aToken['country_code']
701 && !in_array($aToken['country_code'], $this->aCountryCodes)
706 // Special terms need to appear in their normalized form.
707 if ($aToken['word'] && $aToken['class']) {
708 $sNormWord = $this->normTerm($aToken['word']);
709 if (strpos($sNormQuery, $sNormWord) === false) {
714 if (isset($aValidTokens[$aToken['word_token']])) {
715 $aValidTokens[$aToken['word_token']][] = $aToken;
717 $aValidTokens[$aToken['word_token']] = array($aToken);
719 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
721 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
723 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
724 foreach ($aTokens as $sToken) {
725 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
726 if (isset($aValidTokens[$aData[1]])) {
727 foreach ($aValidTokens[$aData[1]] as $aToken) {
728 if (!$aToken['class']) {
729 if (isset($aValidTokens[$sToken])) {
730 $aValidTokens[$sToken][] = $aToken;
732 $aValidTokens[$sToken] = array($aToken);
740 foreach ($aTokens as $sToken) {
741 // Unknown single word token with a number - assume it is a house number
742 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
743 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
747 // Any words that have failed completely?
750 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bStructuredPhrases);
752 if ($this->bReverseInPlan) {
753 // Reverse phrase array and also reverse the order of the wordsets in
754 // the first and final phrase. Don't bother about phrases in the middle
755 // because order in the address doesn't matter.
756 $aPhrases = array_reverse($aPhrases);
757 $aPhrases[0]->invertWordSets();
758 if (sizeof($aPhrases) > 1) {
759 $aPhrases[sizeof($aPhrases)-1]->invertWordSets();
761 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, false);
763 foreach ($aGroupedSearches as $aSearches) {
764 foreach ($aSearches as $aSearch) {
765 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
766 $aReverseGroupedSearches[$aSearch->getRank()] = array();
768 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
772 $aGroupedSearches = $aReverseGroupedSearches;
773 ksort($aGroupedSearches);
776 // Re-group the searches by their score, junk anything over 20 as just not worth trying
777 $aGroupedSearches = array();
778 foreach ($aSearches as $aSearch) {
779 if ($aSearch->getRank() < $this->iMaxRank) {
780 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
781 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
784 ksort($aGroupedSearches);
787 // Filter out duplicate searches
788 $aSearchHash = array();
789 foreach ($aGroupedSearches as $iGroup => $aSearches) {
790 foreach ($aSearches as $iSearch => $aSearch) {
791 $sHash = serialize($aSearch);
792 if (isset($aSearchHash[$sHash])) {
793 unset($aGroupedSearches[$iGroup][$iSearch]);
794 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
796 $aSearchHash[$sHash] = 1;
801 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
803 // Start the search process
806 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
808 foreach ($aSearches as $oSearch) {
812 echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
813 _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
816 $aResults += $oSearch->query(
818 $aWordFrequencyScores,
819 $this->iMinAddressRank,
820 $this->iMaxAddressRank,
824 if ($iQueryLoop > 20) break;
827 if (sizeof($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
828 // Need to verify passes rank limits before dropping out of the loop (yuk!)
829 // reduces the number of place ids, like a filter
830 // rank_address is 30 for interpolated housenumbers
831 $aFilterSql = array();
832 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
834 $sSQL = 'SELECT place_id FROM placex ';
835 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
837 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
838 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
839 $sSQL .= " OR (extratags->'place') = 'city'";
841 if ($this->aAddressRankList) {
842 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
845 $aFilterSql[] = $sSQL;
847 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
849 $sSQL = ' SELECT place_id FROM location_postcode lp ';
850 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
851 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
852 if ($this->aAddressRankList) {
853 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
856 $aFilterSql[] = $sSQL;
859 $aFilteredIDs = array();
861 $sSQL = join(' UNION ', $aFilterSql);
862 if (CONST_Debug) var_dump($sSQL);
863 $aFilteredIDs = chksql($this->oDB->getCol($sSQL));
867 foreach ($aResults as $oResult) {
868 if (($this->iMaxAddressRank == 30 &&
869 ($oResult->iTable == Result::TABLE_OSMLINE
870 || $oResult->iTable == Result::TABLE_AUX
871 || $oResult->iTable == Result::TABLE_TIGER))
872 || in_array($oResult->iId, $aFilteredIDs)
874 $tempIDs[$oResult->iId] = $oResult;
877 $aResults = $tempIDs;
880 if (sizeof($aResults)) break;
881 if ($iGroupLoop > 4) break;
882 if ($iQueryLoop > 30) break;
885 // Just interpret as a reverse geocode
886 $oReverse = new ReverseGeocode($this->oDB);
887 $oReverse->setZoom(18);
889 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
891 if (CONST_Debug) var_dump("Reverse search", $aLookup);
894 $aResults = array($oLookup->iId => $oLookup);
899 if (!sizeof($aResults)) {
900 if ($this->bFallback) {
901 if ($this->fallbackStructuredQuery()) {
902 return $this->lookup();
909 $oPlaceLookup = new PlaceLookup($this->oDB);
910 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
911 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
912 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
913 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
914 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
915 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
916 $oPlaceLookup->setDeDupe($this->bDeDupe);
917 if ($this->aAddressRankList) {
918 $oPlaceLookup->setAddressRankList($this->aAddressRankList);
920 $oPlaceLookup->setAllowedTypesSQLList($this->sAllowedTypesSQLList);
921 $oPlaceLookup->setLanguagePreference($this->aLangPrefOrder);
922 $oPlaceLookup->setIncludeExtraTags($this->bIncludeExtraTags);
923 $oPlaceLookup->setIncludeNameDetails($this->bIncludeNameDetails);
924 if ($oCtx->hasNearPoint()) {
925 $oPlaceLookup->setAnchorSql($oCtx->sqlNear);
928 $aSearchResults = $oPlaceLookup->lookup($aResults);
930 $aClassType = getClassTypesWithImportance();
931 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
932 foreach ($aRecheckWords as $i => $sWord) {
933 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
937 echo '<i>Recheck words:<\i>';
938 var_dump($aRecheckWords);
941 foreach ($aSearchResults as $iIdx => $aResult) {
943 $fDiameter = getResultDiameter($aResult);
945 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
946 if ($aOutlineResult) {
947 $aResult = array_merge($aResult, $aOutlineResult);
950 if ($aResult['extra_place'] == 'city') {
951 $aResult['class'] = 'place';
952 $aResult['type'] = 'city';
953 $aResult['rank_search'] = 16;
956 // Is there an icon set for this type of result?
957 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
958 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
960 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
963 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
964 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
966 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
967 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
968 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
970 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
972 // if tag '&addressdetails=1' is set in query
973 if ($this->bIncludeAddressDetails) {
974 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
975 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResults[$aResult['place_id']]->iHouseNumber);
976 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
977 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
981 $aResult['name'] = $aResult['langaddress'];
983 if ($oCtx->hasNearPoint()) {
984 $aResult['importance'] = 0.001;
985 $aResult['foundorder'] = $aResult['addressimportance'];
987 // Adjust importance for the number of exact string matches in the result
988 $aResult['importance'] *= $this->viewboxImportanceFactor(
992 $aResult['importance'] = max(0.001, $aResult['importance']);
994 $sAddress = $aResult['langaddress'];
995 foreach ($aRecheckWords as $i => $sWord) {
996 if (stripos($sAddress, $sWord)!==false) {
998 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1002 $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
1004 // secondary ordering (for results with same importance (the smaller the better):
1005 // - approximate importance of address parts
1006 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1007 // - number of exact matches from the query
1008 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
1009 // - importance of the class/type
1010 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1011 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1013 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1015 $aResult['foundorder'] += 0.01;
1018 if (CONST_Debug) var_dump($aResult);
1019 $aSearchResults[$iIdx] = $aResult;
1021 uasort($aSearchResults, 'byImportance');
1023 $aOSMIDDone = array();
1024 $aClassTypeNameDone = array();
1025 $aToFilter = $aSearchResults;
1026 $aSearchResults = array();
1028 if (CONST_Debug) var_dump($aToFilter);
1031 foreach ($aToFilter as $aResult) {
1032 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1034 $fLat = $aResult['lat'];
1035 $fLon = $aResult['lon'];
1036 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1039 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1040 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1042 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1043 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1044 $aSearchResults[] = $aResult;
1047 // Absolute limit on number of results
1048 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1051 if (CONST_Debug) var_dump($aSearchResults);
1052 return $aSearchResults;