2 @define('CONST_ConnectionBucket_PageType', 'Search');
4 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
5 require_once(CONST_BasePath.'/lib/log.php');
7 ini_set('memory_limit', '200M');
12 $fLat = CONST_Default_Lat;
13 $fLon = CONST_Default_Lon;
14 $iZoom = CONST_Default_Zoom;
15 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
16 $sOutputFormat = 'html';
17 $aSearchResults = array();
18 $aExcludePlaceIDs = array();
19 $sCountryCodesSQL = false;
20 $sSuggestion = $sSuggestionURL = false;
21 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
22 $bReverseInPlan = false;
23 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
24 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
26 if ($iFinalLimit > 50) $iFinalLimit = 50;
27 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
29 $iMaxAddressRank = 30;
30 $sAllowedTypesSQLList = false;
33 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
35 $sOutputFormat = $_GET['format'];
38 // Show / use polygons
39 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
40 if ($sOutputFormat == 'html')
42 $bAsText = $bShowPolygons;
43 $bShowPolygons = false;
50 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
51 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
52 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
53 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
54 if ((($bShowPolygons?1:0)
59 ) > CONST_PolygonOutput_MaximumTypes)
61 if (CONST_PolygonOutput_MaximumTypes)
63 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
67 userError("Polygon output is disabled");
73 // Show address breakdown
74 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
77 $aLangPrefOrder = getPreferredLanguages();
78 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
79 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
80 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
82 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
84 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
86 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
88 $iExcludedPlaceID = (int)$iExcludedPlaceID;
89 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
93 // Only certain ranks of feature
94 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
96 if (isset($_GET['featuretype']))
98 switch($_GET['featuretype'])
101 $iMinAddressRank = $iMaxAddressRank = 4;
104 $iMinAddressRank = $iMaxAddressRank = 8;
107 $iMinAddressRank = 14;
108 $iMaxAddressRank = 16;
111 $iMinAddressRank = 8;
112 $iMaxAddressRank = 20;
117 if (isset($_GET['countrycodes']))
119 $aCountryCodes = array();
120 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
122 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
124 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
127 $sCountryCodesSQL = join(',', $aCountryCodes);
131 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
132 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
134 $sQuery = substr($_SERVER['PATH_INFO'], 1);
136 // reverse order of '/' separated string
137 $aPhrases = explode('/', $sQuery);
138 $aPhrases = array_reverse($aPhrases);
139 $sQuery = join(', ',$aPhrases);
142 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
144 if (!isset($_GET[$sKey])) return false;
145 $sValue = trim($_GET[$sKey]);
146 if (!$sValue) return false;
147 $aStructuredQuery[$sKey] = $sValue;
148 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30)
150 $iMinAddressRank = $iNewMinAddressRank;
151 $iMaxAddressRank = $iNewMaxAddressRank;
157 $aStructuredOptions = array(
158 array('amenity', 26, 30),
159 array('street', 26, 30),
160 array('city', 14, 24),
161 array('county', 9, 13),
162 array('state', 8, 8),
163 array('country', 4, 4),
164 array('postalcode', 5, 11),
166 $aStructuredQuery = array();
167 $sAllowedTypesSQLList = '';
168 foreach($aStructuredOptions as $aStructuredOption)
170 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
172 if (sizeof($aStructuredQuery) > 0)
174 $sQuery = join(', ', $aStructuredQuery);
175 if ($iMaxAddressRank < 30)
177 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
183 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
185 // Hack to make it handle "new york, ny" (and variants) correctly
186 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
187 if (isset($aLangPrefOrder['name:en']))
189 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
190 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
191 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
194 // If we have a view box create the SQL
195 // Small is the actual view box, Large is double (on each axis) that
196 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
197 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
199 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
200 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
202 if (isset($_GET['viewbox']) && $_GET['viewbox'])
204 $aCoOrdinates = explode(',',$_GET['viewbox']);
205 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
206 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
207 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
208 $aCoOrdinates[0] += $fHeight;
209 $aCoOrdinates[2] -= $fHeight;
210 $aCoOrdinates[1] += $fWidth;
211 $aCoOrdinates[3] -= $fWidth;
212 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
216 $bBoundingBoxSearch = false;
218 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
220 $aPoints = explode(',',$_GET['route']);
221 if (sizeof($aPoints) % 2 != 0)
223 userError("Uneven number of points");
226 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
228 foreach($aPoints as $i => $fPoint)
232 if ($i != 1) $sViewboxCentreSQL .= ",";
233 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
237 $fPrevCoord = (float)$fPoint;
240 $sViewboxCentreSQL .= ")'::geometry,4326)";
242 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
243 $sViewboxSmallSQL = $oDB->getOne($sSQL);
244 if (PEAR::isError($sViewboxSmallSQL))
246 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
248 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
250 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
251 $sViewboxLargeSQL = $oDB->getOne($sSQL);
252 if (PEAR::isError($sViewboxLargeSQL))
254 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
256 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
257 $bBoundingBoxSearch = true;
260 // Do we have anything that looks like a lat/lon pair?
261 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
263 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
264 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
265 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
267 $_GET['nearlat'] = $fQueryLat;
268 $_GET['nearlon'] = $fQueryLon;
269 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
272 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
274 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
275 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
276 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
278 $_GET['nearlat'] = $fQueryLat;
279 $_GET['nearlon'] = $fQueryLon;
280 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
283 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
285 $fQueryLat = $aData[2];
286 $fQueryLon = $aData[3];
287 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
289 $_GET['nearlat'] = $fQueryLat;
290 $_GET['nearlon'] = $fQueryLon;
291 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
295 if ($sQuery || $aStructuredQuery)
297 // Start with a blank search
299 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
300 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
301 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
304 $sNearPointSQL = false;
305 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
307 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
308 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
309 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
310 $aSearches[0]['fRadius'] = 0.1;
313 $bSpecialTerms = false;
314 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
315 $aSpecialTerms = array();
316 foreach($aSpecialTermsRaw as $aSpecialTerm)
318 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
319 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
322 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
323 $aSpecialTerms = array();
324 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
326 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
327 unset($aStructuredQuery['amenity']);
329 foreach($aSpecialTermsRaw as $aSpecialTerm)
331 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
332 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
333 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
334 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null';
335 if (CONST_Debug) var_Dump($sSQL);
336 $aSearchWords = $oDB->getAll($sSQL);
337 $aNewSearches = array();
338 foreach($aSearches as $aSearch)
340 foreach($aSearchWords as $aSearchTerm)
342 $aNewSearch = $aSearch;
343 if ($aSearchTerm['country_code'])
345 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
346 $aNewSearches[] = $aNewSearch;
347 $bSpecialTerms = true;
349 if ($aSearchTerm['class'])
351 $aNewSearch['sClass'] = $aSearchTerm['class'];
352 $aNewSearch['sType'] = $aSearchTerm['type'];
353 $aNewSearches[] = $aNewSearch;
354 $bSpecialTerms = true;
358 $aSearches = $aNewSearches;
361 // Split query into phrases
362 // Commas are used to reduce the search space by indicating where phrases split
363 if (sizeof($aStructuredQuery) > 0)
365 $aPhrases = $aStructuredQuery;
366 $bStructuredPhrases = true;
370 $aPhrases = explode(',',$sQuery);
371 $bStructuredPhrases = false;
375 // Convert each phrase to standard form
376 // Create a list of standard words
377 // Get all 'sets' of words
378 // Generate a complete list of all
380 foreach($aPhrases as $iPhrase => $sPhrase)
382 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
383 if (PEAR::isError($aPhrase))
385 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
386 if (CONST_Debug) var_dump($aPhrase);
389 if (trim($aPhrase['string']))
391 $aPhrases[$iPhrase] = $aPhrase;
392 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
393 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
394 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
398 unset($aPhrases[$iPhrase]);
402 // reindex phrases - we make assumptions later on
403 $aPhraseTypes = array_keys($aPhrases);
404 $aPhrases = array_values($aPhrases);
406 if (sizeof($aTokens))
409 // Check which tokens we have, get the ID numbers
410 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
411 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
412 //$sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
413 //$sSQL .= ' group by word_token, word, class, type, country_code';
415 if (CONST_Debug) var_Dump($sSQL);
417 $aValidTokens = array();
418 if (sizeof($aTokens)) $aDatabaseWords = $oDB->getAll($sSQL);
419 else $aDatabaseWords = array();
420 if (PEAR::IsError($aDatabaseWords))
422 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
424 $aPossibleMainWordIDs = array();
425 $aWordFrequencyScores = array();
426 foreach($aDatabaseWords as $aToken)
428 // Very special case - require 2 letter country param to match the country code found
429 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
430 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
435 if (isset($aValidTokens[$aToken['word_token']]))
437 $aValidTokens[$aToken['word_token']][] = $aToken;
441 $aValidTokens[$aToken['word_token']] = array($aToken);
443 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
444 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
446 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
448 $aSuggestion = array();
449 $bSuggestion = false;
450 if (CONST_Suggestions_Enabled)
452 foreach($aPhrases as $iPhrase => $aPhrase)
454 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
456 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
457 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
458 $aRow = $aSuggestionWords[0];
459 if ($aRow && $aRow['word'])
461 $aSuggestion[] = $aRow['word'];
466 $aSuggestion[] = $aPhrase['string'];
471 $aSuggestion[] = $aPhrase['string'];
475 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
477 // Try and calculate GB postcodes we might be missing
478 foreach($aTokens as $sToken)
480 // Source of gb postcodes is now definitive - always use
481 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
483 if (substr($aData[1],-2,1) != ' ')
485 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
486 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
488 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
489 if ($aGBPostcodeLocation)
491 $aValidTokens[$sToken] = $aGBPostcodeLocation;
496 foreach($aTokens as $sToken)
498 // Unknown single word token with a number - assume it is a house number
499 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
501 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
505 // Any words that have failed completely?
508 // Start the search process
509 $aResultPlaceIDs = array();
512 Calculate all searches using aValidTokens i.e.
514 'Wodsworth Road, Sheffield' =>
518 0 1 (wodsworth)(road)
521 Score how good the search is so they can be ordered
523 foreach($aPhrases as $iPhrase => $sPhrase)
525 $aNewPhraseSearches = array();
526 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
527 else $sPhraseType = '';
529 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
531 $aWordsetSearches = $aSearches;
533 // Add all words from this wordset
534 foreach($aWordset as $iToken => $sToken)
536 //echo "<br><b>$sToken</b>";
537 $aNewWordsetSearches = array();
539 foreach($aWordsetSearches as $aCurrentSearch)
542 //var_dump($aCurrentSearch);
545 // If the token is valid
546 if (isset($aValidTokens[' '.$sToken]))
548 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
550 $aSearch = $aCurrentSearch;
551 $aSearch['iSearchRank']++;
552 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
554 if ($aSearch['sCountryCode'] === false)
556 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
557 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
558 // If reverse order is enabled, it may appear at the beginning as well.
559 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
560 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
562 $aSearch['iSearchRank'] += 5;
564 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
567 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
569 if ($aSearch['fLat'] === '')
571 $aSearch['fLat'] = $aSearchTerm['lat'];
572 $aSearch['fLon'] = $aSearchTerm['lon'];
573 $aSearch['fRadius'] = $aSearchTerm['radius'];
574 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
577 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
579 if ($aSearch['sHouseNumber'] === '')
581 $aSearch['sHouseNumber'] = $sToken;
582 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
584 // Fall back to not searching for this item (better than nothing)
585 $aSearch = $aCurrentSearch;
586 $aSearch['iSearchRank'] += 1;
587 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
591 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
593 if ($aSearch['sClass'] === '')
595 $aSearch['sOperator'] = $aSearchTerm['operator'];
596 $aSearch['sClass'] = $aSearchTerm['class'];
597 $aSearch['sType'] = $aSearchTerm['type'];
598 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
599 else $aSearch['sOperator'] = 'near'; // near = in for the moment
601 // Do we have a shortcut id?
602 if ($aSearch['sOperator'] == 'name')
604 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
605 if ($iAmenityID = $oDB->getOne($sSQL))
607 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
608 $aSearch['aName'][$iAmenityID] = $iAmenityID;
609 $aSearch['sClass'] = '';
610 $aSearch['sType'] = '';
613 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
616 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
618 if (sizeof($aSearch['aName']))
620 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
622 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
626 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
627 $aSearch['iSearchRank'] += 1000; // skip;
632 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
633 //$aSearch['iNamePhrase'] = $iPhrase;
635 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
639 if (isset($aValidTokens[$sToken]))
641 // Allow searching for a word - but at extra cost
642 foreach($aValidTokens[$sToken] as $aSearchTerm)
644 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
646 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
648 $aSearch = $aCurrentSearch;
649 $aSearch['iSearchRank'] += 1;
650 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
652 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
653 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
655 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
657 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
659 if (empty($aSearchTermToken['country_code'])
660 && empty($aSearchTermToken['lat'])
661 && empty($aSearchTermToken['class']))
663 $aSearch = $aCurrentSearch;
664 $aSearch['iSearchRank'] += 1;
665 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
666 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
672 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
673 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
677 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
679 $aSearch = $aCurrentSearch;
680 $aSearch['iSearchRank'] += 2;
681 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
682 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
683 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
685 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
686 $aSearch['iNamePhrase'] = $iPhrase;
687 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
694 // Allow skipping a word - but at EXTREAM cost
695 //$aSearch = $aCurrentSearch;
696 //$aSearch['iSearchRank']+=100;
697 //$aNewWordsetSearches[] = $aSearch;
701 usort($aNewWordsetSearches, 'bySearchRank');
702 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
704 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
706 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
707 usort($aNewPhraseSearches, 'bySearchRank');
709 $aSearchHash = array();
710 foreach($aNewPhraseSearches as $iSearch => $aSearch)
712 $sHash = serialize($aSearch);
713 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
714 else $aSearchHash[$sHash] = 1;
717 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
720 // Re-group the searches by their score, junk anything over 20 as just not worth trying
721 $aGroupedSearches = array();
722 foreach($aNewPhraseSearches as $aSearch)
724 if ($aSearch['iSearchRank'] < $iMaxRank)
726 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
727 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
730 ksort($aGroupedSearches);
733 $aSearches = array();
734 foreach($aGroupedSearches as $iScore => $aNewSearches)
736 $iSearchCount += sizeof($aNewSearches);
737 $aSearches = array_merge($aSearches, $aNewSearches);
738 if ($iSearchCount > 50) break;
741 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
747 // Re-group the searches by their score, junk anything over 20 as just not worth trying
748 $aGroupedSearches = array();
749 foreach($aSearches as $aSearch)
751 if ($aSearch['iSearchRank'] < $iMaxRank)
753 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
754 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
757 ksort($aGroupedSearches);
760 if (CONST_Debug) var_Dump($aGroupedSearches);
764 $aCopyGroupedSearches = $aGroupedSearches;
765 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
767 foreach($aSearches as $iSearch => $aSearch)
769 if (sizeof($aSearch['aAddress']))
771 $iReverseItem = array_pop($aSearch['aAddress']);
772 if (isset($aPossibleMainWordIDs[$iReverseItem]))
774 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
775 $aSearch['aName'] = array($iReverseItem);
776 $aGroupedSearches[$iGroup][] = $aSearch;
778 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
779 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
785 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
787 $aCopyGroupedSearches = $aGroupedSearches;
788 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
790 foreach($aSearches as $iSearch => $aSearch)
792 $aReductionsList = array($aSearch['aAddress']);
793 $iSearchRank = $aSearch['iSearchRank'];
794 while(sizeof($aReductionsList) > 0)
797 if ($iSearchRank > iMaxRank) break 3;
798 $aNewReductionsList = array();
799 foreach($aReductionsList as $aReductionsWordList)
801 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
803 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
804 $aReverseSearch = $aSearch;
805 $aSearch['aAddress'] = $aReductionsWordListResult;
806 $aSearch['iSearchRank'] = $iSearchRank;
807 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
808 if (sizeof($aReductionsWordListResult) > 0)
810 $aNewReductionsList[] = $aReductionsWordListResult;
814 $aReductionsList = $aNewReductionsList;
818 ksort($aGroupedSearches);
821 // Filter out duplicate searches
822 $aSearchHash = array();
823 foreach($aGroupedSearches as $iGroup => $aSearches)
825 foreach($aSearches as $iSearch => $aSearch)
827 $sHash = serialize($aSearch);
828 if (isset($aSearchHash[$sHash]))
830 unset($aGroupedSearches[$iGroup][$iSearch]);
831 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
835 $aSearchHash[$sHash] = 1;
840 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
844 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
847 foreach($aSearches as $aSearch)
851 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
852 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
855 // Must have a location term
856 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
858 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
860 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
862 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
863 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
864 $sSQL .= " order by st_area(geometry) desc limit 1";
865 if (CONST_Debug) var_dump($sSQL);
866 $aPlaceIDs = $oDB->getCol($sSQL);
871 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
872 if (!$aSearch['sClass']) continue;
873 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
874 if ($oDB->getOne($sSQL))
876 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
877 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
878 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
879 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
880 if (sizeof($aExcludePlaceIDs))
882 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
884 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
885 $sSQL .= " limit $iLimit";
886 if (CONST_Debug) var_dump($sSQL);
887 $aPlaceIDs = $oDB->getCol($sSQL);
889 // If excluded place IDs are given, it is fair to assume that
890 // there have been results in the small box, so no further
891 // expansion in that case.
892 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
894 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
895 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
896 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
897 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
898 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
899 $sSQL .= " limit $iLimit";
900 if (CONST_Debug) var_dump($sSQL);
901 $aPlaceIDs = $oDB->getCol($sSQL);
906 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
907 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
908 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
909 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
910 $sSQL .= " limit $iLimit";
911 if (CONST_Debug) var_dump($sSQL);
912 $aPlaceIDs = $oDB->getCol($sSQL);
918 $aPlaceIDs = array();
920 // First we need a position, either aName or fLat or both
924 // TODO: filter out the pointless search terms (2 letter name tokens and less)
925 // they might be right - but they are just too darned expensive to run
926 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
927 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
928 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
930 // For infrequent name terms disable index usage for address
931 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
932 sizeof($aSearch['aName']) == 1 &&
933 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
935 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
939 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
940 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
943 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
944 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
945 if ($aSearch['fLon'] && $aSearch['fLat'])
947 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
948 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
950 if (sizeof($aExcludePlaceIDs))
952 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
954 if ($sCountryCodesSQL)
956 $aTerms[] = "country_code in ($sCountryCodesSQL)";
959 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
960 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
962 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
963 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
964 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
965 $aOrder[] = "$sImportanceSQL DESC";
966 if (sizeof($aSearch['aFullNameAddress']))
967 $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
971 $sSQL = "select place_id";
972 $sSQL .= " from search_name";
973 $sSQL .= " where ".join(' and ',$aTerms);
974 $sSQL .= " order by ".join(', ',$aOrder);
975 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
976 $sSQL .= " limit 50";
977 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
980 $sSQL .= " limit ".$iLimit;
982 if (CONST_Debug) { var_dump($sSQL); }
983 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
984 if (PEAR::IsError($aViewBoxPlaceIDs))
986 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
988 //var_dump($aViewBoxPlaceIDs);
989 // Did we have an viewbox matches?
990 $aPlaceIDs = array();
991 $bViewBoxMatch = false;
992 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
994 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
995 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
996 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
997 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
998 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1001 //var_Dump($aPlaceIDs);
1004 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1006 $aRoadPlaceIDs = $aPlaceIDs;
1007 $sPlaceIDs = join(',',$aPlaceIDs);
1009 // Now they are indexed look for a house attached to a street we found
1010 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
1011 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1012 if (sizeof($aExcludePlaceIDs))
1014 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1016 $sSQL .= " limit $iLimit";
1017 if (CONST_Debug) var_dump($sSQL);
1018 $aPlaceIDs = $oDB->getCol($sSQL);
1020 // If not try the aux fallback table
1021 if (!sizeof($aPlaceIDs))
1023 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1024 if (sizeof($aExcludePlaceIDs))
1026 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1028 //$sSQL .= " limit $iLimit";
1029 if (CONST_Debug) var_dump($sSQL);
1030 $aPlaceIDs = $oDB->getCol($sSQL);
1033 if (!sizeof($aPlaceIDs))
1035 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1036 if (sizeof($aExcludePlaceIDs))
1038 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1040 //$sSQL .= " limit $iLimit";
1041 if (CONST_Debug) var_dump($sSQL);
1042 $aPlaceIDs = $oDB->getCol($sSQL);
1045 // Fallback to the road
1046 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1048 $aPlaceIDs = $aRoadPlaceIDs;
1053 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1055 $sPlaceIDs = join(',',$aPlaceIDs);
1056 $aClassPlaceIDs = array();
1058 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1060 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1061 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1062 $sSQL .= " and linked_place_id is null";
1063 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1064 $sSQL .= " order by rank_search asc limit $iLimit";
1065 if (CONST_Debug) var_dump($sSQL);
1066 $aClassPlaceIDs = $oDB->getCol($sSQL);
1069 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1071 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1072 $bCacheTable = $oDB->getOne($sSQL);
1074 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1076 if (CONST_Debug) var_dump($sSQL);
1077 $iMaxRank = ((int)$oDB->getOne($sSQL));
1079 // For state / country level searches the normal radius search doesn't work very well
1080 $sPlaceGeom = false;
1081 if ($iMaxRank < 9 && $bCacheTable)
1083 // Try and get a polygon to search in instead
1084 $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
1085 if (CONST_Debug) var_dump($sSQL);
1086 $sPlaceGeom = $oDB->getOne($sSQL);
1096 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1097 if (CONST_Debug) var_dump($sSQL);
1098 $aPlaceIDs = $oDB->getCol($sSQL);
1099 $sPlaceIDs = join(',',$aPlaceIDs);
1102 if ($sPlaceIDs || $sPlaceGeom)
1108 // More efficient - can make the range bigger
1112 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1113 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1114 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1116 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1117 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1120 $sSQL .= ",placex as f where ";
1121 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1126 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1128 if (sizeof($aExcludePlaceIDs))
1130 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1132 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1133 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1134 if ($iOffset) $sSQL .= " offset $iOffset";
1135 $sSQL .= " limit $iLimit";
1136 if (CONST_Debug) var_dump($sSQL);
1137 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1141 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1144 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1145 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1147 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1148 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1149 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1150 if (sizeof($aExcludePlaceIDs))
1152 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1154 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1155 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1156 if ($iOffset) $sSQL .= " offset $iOffset";
1157 $sSQL .= " limit $iLimit";
1158 if (CONST_Debug) var_dump($sSQL);
1159 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1164 $aPlaceIDs = $aClassPlaceIDs;
1170 if (PEAR::IsError($aPlaceIDs))
1172 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1175 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1177 foreach($aPlaceIDs as $iPlaceID)
1179 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1181 if ($iQueryLoop > 20) break;
1185 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1186 if ($iGroupLoop > 4) break;
1187 if ($iQueryLoop > 30) break;
1190 // Did we find anything?
1191 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1193 //var_Dump($aResultPlaceIDs);exit;
1194 // Get the details for display (is this a redundant extra step?)
1195 $sPlaceIDs = join(',',$aResultPlaceIDs);
1196 $sOrderSQL = 'CASE ';
1197 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1199 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1201 $sOrderSQL .= ' ELSE 10000000 END';
1202 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,calculated_country_code as country_code,";
1203 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1204 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1205 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1206 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1207 //$sSQL .= $sOrderSQL." as porder, ";
1208 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1209 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(placex.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
1210 $sSQL .= "(extratags->'place') as extra_place ";
1211 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1212 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1213 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1215 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1216 $sSQL .= "and linked_place_id is null ";
1217 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1218 if (!$bDeDupe) $sSQL .= ",place_id";
1219 $sSQL .= ",langaddress ";
1220 $sSQL .= ",placename ";
1222 $sSQL .= ",extratags->'place' ";
1224 $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1225 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1226 $sSQL .= "null as placename,";
1227 $sSQL .= "null as ref,";
1228 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1229 //$sSQL .= $sOrderSQL." as porder, ";
1230 $sSQL .= "-0.15 as importance, ";
1231 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_tiger.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
1232 $sSQL .= "null as extra_place ";
1233 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1234 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1235 $sSQL .= "group by place_id";
1236 if (!$bDeDupe) $sSQL .= ",place_id";
1238 $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1239 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1240 $sSQL .= "null as placename,";
1241 $sSQL .= "null as ref,";
1242 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1243 //$sSQL .= $sOrderSQL." as porder, ";
1244 $sSQL .= "-0.10 as importance, ";
1245 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_aux.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
1246 $sSQL .= "null as extra_place ";
1247 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1248 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1249 $sSQL .= "group by place_id";
1250 if (!$bDeDupe) $sSQL .= ",place_id";
1251 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1252 $sSQL .= "order by importance desc";
1253 //$sSQL .= "order by rank_search,rank_address,porder asc";
1254 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1255 $aSearchResults = $oDB->getAll($sSQL);
1256 //var_dump($sSQL,$aSearchResults);exit;
1258 if (PEAR::IsError($aSearchResults))
1260 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1263 } // end if ($sQuery)
1266 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1268 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1269 $aResultPlaceIDs = array($iPlaceID);
1271 // TODO: this needs refactoring!
1273 // Get the details for display (is this a redundant extra step?)
1274 $sPlaceIDs = join(',',$aResultPlaceIDs);
1275 $sOrderSQL = 'CASE ';
1276 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1278 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1280 $sOrderSQL .= ' ELSE 10000000 END';
1281 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,calculated_country_code as country_code,";
1282 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1283 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1284 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1285 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1286 //$sSQL .= $sOrderSQL." as porder, ";
1287 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1288 $sSQL .= "(extratags->'place') as extra_place ";
1289 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1290 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1291 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1293 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1294 if (!$bDeDupe) $sSQL .= ",place_id";
1295 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1296 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1297 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1298 $sSQL .= ",extratags->'place' ";
1300 $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1301 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1302 $sSQL .= "null as placename,";
1303 $sSQL .= "null as ref,";
1304 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1305 //$sSQL .= $sOrderSQL." as porder, ";
1306 $sSQL .= "-0.15 as importance, ";
1307 $sSQL .= "null as extra_place ";
1308 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1309 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1310 $sSQL .= "group by place_id";
1311 if (!$bDeDupe) $sSQL .= ",place_id";
1313 $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1314 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1315 $sSQL .= "null as placename,";
1316 $sSQL .= "null as ref,";
1317 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1318 //$sSQL .= $sOrderSQL." as porder, ";
1319 $sSQL .= "-0.10 as importance, ";
1320 $sSQL .= "null as extra_place ";
1321 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1322 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1323 $sSQL .= "group by place_id";
1324 if (!$bDeDupe) $sSQL .= ",place_id";
1325 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1326 $sSQL .= "order by importance desc";
1327 //$sSQL .= "order by rank_search,rank_address,porder asc";
1328 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1329 $aSearchResults = $oDB->getAll($sSQL);
1330 //var_dump($sSQL,$aSearchResults);exit;
1332 if (PEAR::IsError($aSearchResults))
1334 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1340 $sSearchResult = '';
1341 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1343 $sSearchResult = 'No Results Found';
1345 //var_Dump($aSearchResults);
1347 $aClassType = getClassTypesWithImportance();
1348 $aRecheckWords = preg_split('/\b/u',$sQuery);
1349 foreach($aRecheckWords as $i => $sWord)
1351 if (!$sWord) unset($aRecheckWords[$i]);
1353 foreach($aSearchResults as $iResNum => $aResult)
1355 if (CONST_Search_AreaPolygons)
1357 // Get the bounding box and outline polygon
1358 $sSQL = "select place_id,numfeatures,area,outline,";
1359 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1360 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1361 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1363 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1364 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1365 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1366 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1367 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1368 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1369 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1370 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1371 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1372 $aPointPolygon = $oDB->getRow($sSQL);
1373 if (PEAR::IsError($aPointPolygon))
1375 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1377 if ($aPointPolygon['place_id'])
1379 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1380 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1381 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1382 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1384 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1386 $aResult['lat'] = $aPointPolygon['centrelat'];
1387 $aResult['lon'] = $aPointPolygon['centrelon'];
1391 // Translate geometary string to point array
1392 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1394 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1396 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1398 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1400 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1403 $iSteps = ($fRadius * 40000)^2;
1404 $fStepSize = (2*pi())/$iSteps;
1405 $aPolyPoints = array();
1406 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1408 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1410 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1411 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1412 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1413 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1417 // Output data suitable for display (points and a bounding box)
1418 if ($bShowPolygons && isset($aPolyPoints))
1420 $aResult['aPolyPoints'] = array();
1421 foreach($aPolyPoints as $aPoint)
1423 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1426 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1430 if ($aResult['extra_place'] == 'city')
1432 $aResult['class'] = 'place';
1433 $aResult['type'] = 'city';
1434 $aResult['rank_search'] = 16;
1437 if (!isset($aResult['aBoundingBox']))
1440 $fDiameter = 0.0001;
1442 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1443 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1445 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1447 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1448 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1450 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1452 $fRadius = $fDiameter / 2;
1454 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1455 $fStepSize = (2*pi())/$iSteps;
1456 $aPolyPoints = array();
1457 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1459 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1461 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1462 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1463 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1464 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1466 // Output data suitable for display (points and a bounding box)
1469 $aResult['aPolyPoints'] = array();
1470 foreach($aPolyPoints as $aPoint)
1472 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1475 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1478 // Is there an icon set for this type of result?
1479 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1480 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1482 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1485 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1486 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1488 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1491 if ($bShowAddressDetails)
1493 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1494 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1496 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1499 //var_dump($aResult['address']);
1503 // Adjust importance for the number of exact string matches in the result
1504 $aResult['importance'] = max(0.001,$aResult['importance']);
1506 $sAddress = $aResult['langaddress'];
1507 foreach($aRecheckWords as $i => $sWord)
1509 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1512 $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
1514 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1516 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1517 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1519 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1521 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1522 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1524 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1528 $aResult['importance'] = 1000000000000000;
1531 $aResult['name'] = $aResult['langaddress'];
1532 $aResult['foundorder'] = -$aResult['addressimportance'];
1533 $aSearchResults[$iResNum] = $aResult;
1535 uasort($aSearchResults, 'byImportance');
1537 $aOSMIDDone = array();
1538 $aClassTypeNameDone = array();
1539 $aToFilter = $aSearchResults;
1540 $aSearchResults = array();
1543 foreach($aToFilter as $iResNum => $aResult)
1545 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1546 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1549 $fLat = $aResult['lat'];
1550 $fLon = $aResult['lon'];
1551 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1554 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1555 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1557 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1558 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1559 $aSearchResults[] = $aResult;
1562 // Absolute limit on number of results
1563 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1566 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1568 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1570 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1575 logEnd($oDB, $hLog, sizeof($aToFilter));
1577 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1578 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1579 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1580 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1581 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1582 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1585 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1587 $sMoreURL .= '&q='.urlencode($sQuery);
1589 if (CONST_Debug) exit;
1591 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');