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'].",".(float)$_GET['nearlat']."),4326)";
308 echo '<br><b>--'.$sNearPointSQL.'--</b><br>';
309 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
310 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
311 $aSearches[0]['fRadius'] = 0.1;
314 $bSpecialTerms = false;
315 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
316 $aSpecialTerms = array();
317 foreach($aSpecialTermsRaw as $aSpecialTerm)
319 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
320 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
323 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
324 $aSpecialTerms = array();
325 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
327 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
328 unset($aStructuredQuery['amenity']);
330 foreach($aSpecialTermsRaw as $aSpecialTerm)
332 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
333 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
334 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
335 $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';
336 if (CONST_Debug) var_Dump($sSQL);
337 $aSearchWords = $oDB->getAll($sSQL);
338 $aNewSearches = array();
339 foreach($aSearches as $aSearch)
341 foreach($aSearchWords as $aSearchTerm)
343 $aNewSearch = $aSearch;
344 if ($aSearchTerm['country_code'])
346 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
347 $aNewSearches[] = $aNewSearch;
348 $bSpecialTerms = true;
350 if ($aSearchTerm['class'])
352 $aNewSearch['sClass'] = $aSearchTerm['class'];
353 $aNewSearch['sType'] = $aSearchTerm['type'];
354 $aNewSearches[] = $aNewSearch;
355 $bSpecialTerms = true;
359 $aSearches = $aNewSearches;
362 // Split query into phrases
363 // Commas are used to reduce the search space by indicating where phrases split
364 if (sizeof($aStructuredQuery) > 0)
366 $aPhrases = $aStructuredQuery;
367 $bStructuredPhrases = true;
371 $aPhrases = explode(',',$sQuery);
372 $bStructuredPhrases = false;
376 // Convert each phrase to standard form
377 // Create a list of standard words
378 // Get all 'sets' of words
379 // Generate a complete list of all
381 foreach($aPhrases as $iPhrase => $sPhrase)
383 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
384 if (PEAR::isError($aPhrase))
386 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
387 if (CONST_Debug) var_dump($aPhrase);
390 if (trim($aPhrase['string']))
392 $aPhrases[$iPhrase] = $aPhrase;
393 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
394 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
395 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
399 unset($aPhrases[$iPhrase]);
403 // reindex phrases - we make assumptions later on
404 $aPhraseTypes = array_keys($aPhrases);
405 $aPhrases = array_values($aPhrases);
407 if (sizeof($aTokens))
410 // Check which tokens we have, get the ID numbers
411 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
412 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
413 //$sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
414 //$sSQL .= ' group by word_token, word, class, type, country_code';
416 if (CONST_Debug) var_Dump($sSQL);
418 $aValidTokens = array();
419 if (sizeof($aTokens)) $aDatabaseWords = $oDB->getAll($sSQL);
420 else $aDatabaseWords = array();
421 if (PEAR::IsError($aDatabaseWords))
423 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
425 $aPossibleMainWordIDs = array();
426 $aWordFrequencyScores = array();
427 foreach($aDatabaseWords as $aToken)
429 // Very special case - require 2 letter country param to match the country code found
430 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
431 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
436 if (isset($aValidTokens[$aToken['word_token']]))
438 $aValidTokens[$aToken['word_token']][] = $aToken;
442 $aValidTokens[$aToken['word_token']] = array($aToken);
444 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
445 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
447 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
449 $aSuggestion = array();
450 $bSuggestion = false;
451 if (CONST_Suggestions_Enabled)
453 foreach($aPhrases as $iPhrase => $aPhrase)
455 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
457 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
458 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
459 $aRow = $aSuggestionWords[0];
460 if ($aRow && $aRow['word'])
462 $aSuggestion[] = $aRow['word'];
467 $aSuggestion[] = $aPhrase['string'];
472 $aSuggestion[] = $aPhrase['string'];
476 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
478 // Try and calculate GB postcodes we might be missing
479 foreach($aTokens as $sToken)
481 // Source of gb postcodes is now definitive - always use
482 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
484 if (substr($aData[1],-2,1) != ' ')
486 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
487 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
489 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
490 if ($aGBPostcodeLocation)
492 $aValidTokens[$sToken] = $aGBPostcodeLocation;
497 foreach($aTokens as $sToken)
499 // Unknown single word token with a number - assume it is a house number
500 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
502 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
506 // Any words that have failed completely?
509 // Start the search process
510 $aResultPlaceIDs = array();
513 Calculate all searches using aValidTokens i.e.
515 'Wodsworth Road, Sheffield' =>
519 0 1 (wodsworth)(road)
522 Score how good the search is so they can be ordered
524 foreach($aPhrases as $iPhrase => $sPhrase)
526 $aNewPhraseSearches = array();
527 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
528 else $sPhraseType = '';
530 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
532 $aWordsetSearches = $aSearches;
534 // Add all words from this wordset
535 foreach($aWordset as $iToken => $sToken)
537 //echo "<br><b>$sToken</b>";
538 $aNewWordsetSearches = array();
540 foreach($aWordsetSearches as $aCurrentSearch)
543 //var_dump($aCurrentSearch);
546 // If the token is valid
547 if (isset($aValidTokens[' '.$sToken]))
549 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
551 $aSearch = $aCurrentSearch;
552 $aSearch['iSearchRank']++;
553 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
555 if ($aSearch['sCountryCode'] === false)
557 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
558 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
559 // If reverse order is enabled, it may appear at the beginning as well.
560 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
561 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
563 $aSearch['iSearchRank'] += 5;
565 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
568 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
570 if ($aSearch['fLat'] === '')
572 $aSearch['fLat'] = $aSearchTerm['lat'];
573 $aSearch['fLon'] = $aSearchTerm['lon'];
574 $aSearch['fRadius'] = $aSearchTerm['radius'];
575 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
578 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
580 if ($aSearch['sHouseNumber'] === '')
582 $aSearch['sHouseNumber'] = $sToken;
583 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
585 // Fall back to not searching for this item (better than nothing)
586 $aSearch = $aCurrentSearch;
587 $aSearch['iSearchRank'] += 1;
588 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
592 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
594 if ($aSearch['sClass'] === '')
596 $aSearch['sOperator'] = $aSearchTerm['operator'];
597 $aSearch['sClass'] = $aSearchTerm['class'];
598 $aSearch['sType'] = $aSearchTerm['type'];
599 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
600 else $aSearch['sOperator'] = 'near'; // near = in for the moment
602 // Do we have a shortcut id?
603 if ($aSearch['sOperator'] == 'name')
605 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
606 if ($iAmenityID = $oDB->getOne($sSQL))
608 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
609 $aSearch['aName'][$iAmenityID] = $iAmenityID;
610 $aSearch['sClass'] = '';
611 $aSearch['sType'] = '';
614 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
617 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
619 if (sizeof($aSearch['aName']))
621 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
623 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
627 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
628 $aSearch['iSearchRank'] += 1000; // skip;
633 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
634 //$aSearch['iNamePhrase'] = $iPhrase;
636 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
640 if (isset($aValidTokens[$sToken]))
642 // Allow searching for a word - but at extra cost
643 foreach($aValidTokens[$sToken] as $aSearchTerm)
645 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
647 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
649 $aSearch = $aCurrentSearch;
650 $aSearch['iSearchRank'] += 1;
651 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
653 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
654 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
656 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
658 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
660 if (empty($aSearchTermToken['country_code'])
661 && empty($aSearchTermToken['lat'])
662 && empty($aSearchTermToken['class']))
664 $aSearch = $aCurrentSearch;
665 $aSearch['iSearchRank'] += 1;
666 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
667 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
673 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
674 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
678 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
680 $aSearch = $aCurrentSearch;
681 $aSearch['iSearchRank'] += 2;
682 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
683 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
684 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
686 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
687 $aSearch['iNamePhrase'] = $iPhrase;
688 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
695 // Allow skipping a word - but at EXTREAM cost
696 //$aSearch = $aCurrentSearch;
697 //$aSearch['iSearchRank']+=100;
698 //$aNewWordsetSearches[] = $aSearch;
702 usort($aNewWordsetSearches, 'bySearchRank');
703 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
705 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
707 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
708 usort($aNewPhraseSearches, 'bySearchRank');
710 $aSearchHash = array();
711 foreach($aNewPhraseSearches as $iSearch => $aSearch)
713 $sHash = serialize($aSearch);
714 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
715 else $aSearchHash[$sHash] = 1;
718 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
721 // Re-group the searches by their score, junk anything over 20 as just not worth trying
722 $aGroupedSearches = array();
723 foreach($aNewPhraseSearches as $aSearch)
725 if ($aSearch['iSearchRank'] < $iMaxRank)
727 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
728 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
731 ksort($aGroupedSearches);
734 $aSearches = array();
735 foreach($aGroupedSearches as $iScore => $aNewSearches)
737 $iSearchCount += sizeof($aNewSearches);
738 $aSearches = array_merge($aSearches, $aNewSearches);
739 if ($iSearchCount > 50) break;
742 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
748 // Re-group the searches by their score, junk anything over 20 as just not worth trying
749 $aGroupedSearches = array();
750 foreach($aSearches as $aSearch)
752 if ($aSearch['iSearchRank'] < $iMaxRank)
754 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
755 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
758 ksort($aGroupedSearches);
761 if (CONST_Debug) var_Dump($aGroupedSearches);
765 $aCopyGroupedSearches = $aGroupedSearches;
766 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
768 foreach($aSearches as $iSearch => $aSearch)
770 if (sizeof($aSearch['aAddress']))
772 $iReverseItem = array_pop($aSearch['aAddress']);
773 if (isset($aPossibleMainWordIDs[$iReverseItem]))
775 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
776 $aSearch['aName'] = array($iReverseItem);
777 $aGroupedSearches[$iGroup][] = $aSearch;
779 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
780 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
786 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
788 $aCopyGroupedSearches = $aGroupedSearches;
789 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
791 foreach($aSearches as $iSearch => $aSearch)
793 $aReductionsList = array($aSearch['aAddress']);
794 $iSearchRank = $aSearch['iSearchRank'];
795 while(sizeof($aReductionsList) > 0)
798 if ($iSearchRank > iMaxRank) break 3;
799 $aNewReductionsList = array();
800 foreach($aReductionsList as $aReductionsWordList)
802 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
804 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
805 $aReverseSearch = $aSearch;
806 $aSearch['aAddress'] = $aReductionsWordListResult;
807 $aSearch['iSearchRank'] = $iSearchRank;
808 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
809 if (sizeof($aReductionsWordListResult) > 0)
811 $aNewReductionsList[] = $aReductionsWordListResult;
815 $aReductionsList = $aNewReductionsList;
819 ksort($aGroupedSearches);
822 // Filter out duplicate searches
823 $aSearchHash = array();
824 foreach($aGroupedSearches as $iGroup => $aSearches)
826 foreach($aSearches as $iSearch => $aSearch)
828 $sHash = serialize($aSearch);
829 if (isset($aSearchHash[$sHash]))
831 unset($aGroupedSearches[$iGroup][$iSearch]);
832 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
836 $aSearchHash[$sHash] = 1;
841 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
845 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
848 foreach($aSearches as $aSearch)
852 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
853 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
856 // Must have a location term
857 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
859 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
861 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
863 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
864 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
865 $sSQL .= " order by st_area(geometry) desc limit 1";
866 if (CONST_Debug) var_dump($sSQL);
867 $aPlaceIDs = $oDB->getCol($sSQL);
872 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
873 if (!$aSearch['sClass']) continue;
874 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
875 if ($oDB->getOne($sSQL))
877 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
878 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
879 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
880 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
881 if (sizeof($aExcludePlaceIDs))
883 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
885 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
886 $sSQL .= " limit $iLimit";
887 if (CONST_Debug) var_dump($sSQL);
888 $aPlaceIDs = $oDB->getCol($sSQL);
890 // If excluded place IDs are given, it is fair to assume that
891 // there have been results in the small box, so no further
892 // expansion in that case.
893 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
895 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
896 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
897 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
898 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
899 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
900 $sSQL .= " limit $iLimit";
901 if (CONST_Debug) var_dump($sSQL);
902 $aPlaceIDs = $oDB->getCol($sSQL);
907 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
908 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
909 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
910 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
911 $sSQL .= " limit $iLimit";
912 if (CONST_Debug) var_dump($sSQL);
913 $aPlaceIDs = $oDB->getCol($sSQL);
919 $aPlaceIDs = array();
921 // First we need a position, either aName or fLat or both
925 // TODO: filter out the pointless search terms (2 letter name tokens and less)
926 // they might be right - but they are just too darned expensive to run
927 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
928 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
929 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
931 // For infrequent name terms disable index usage for address
932 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
933 sizeof($aSearch['aName']) == 1 &&
934 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
936 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
940 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
941 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
944 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
945 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
946 if ($aSearch['fLon'] && $aSearch['fLat'])
948 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
949 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
951 if (sizeof($aExcludePlaceIDs))
953 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
955 if ($sCountryCodesSQL)
957 $aTerms[] = "country_code in ($sCountryCodesSQL)";
960 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
961 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
963 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
964 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
965 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
966 $aOrder[] = "$sImportanceSQL DESC";
967 if (sizeof($aSearch['aFullNameAddress']))
968 $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
972 $sSQL = "select place_id";
973 $sSQL .= " from search_name";
974 $sSQL .= " where ".join(' and ',$aTerms);
975 $sSQL .= " order by ".join(', ',$aOrder);
976 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
977 $sSQL .= " limit 50";
978 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
981 $sSQL .= " limit ".$iLimit;
983 if (CONST_Debug) { var_dump($sSQL); }
984 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
985 if (PEAR::IsError($aViewBoxPlaceIDs))
987 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
989 //var_dump($aViewBoxPlaceIDs);
990 // Did we have an viewbox matches?
991 $aPlaceIDs = array();
992 $bViewBoxMatch = false;
993 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
995 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
996 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
997 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
998 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
999 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1002 //var_Dump($aPlaceIDs);
1005 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1007 $aRoadPlaceIDs = $aPlaceIDs;
1008 $sPlaceIDs = join(',',$aPlaceIDs);
1010 // Now they are indexed look for a house attached to a street we found
1011 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
1012 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1013 if (sizeof($aExcludePlaceIDs))
1015 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1017 $sSQL .= " limit $iLimit";
1018 if (CONST_Debug) var_dump($sSQL);
1019 $aPlaceIDs = $oDB->getCol($sSQL);
1021 // If not try the aux fallback table
1022 if (!sizeof($aPlaceIDs))
1024 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1025 if (sizeof($aExcludePlaceIDs))
1027 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1029 //$sSQL .= " limit $iLimit";
1030 if (CONST_Debug) var_dump($sSQL);
1031 $aPlaceIDs = $oDB->getCol($sSQL);
1034 if (!sizeof($aPlaceIDs))
1036 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1037 if (sizeof($aExcludePlaceIDs))
1039 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1041 //$sSQL .= " limit $iLimit";
1042 if (CONST_Debug) var_dump($sSQL);
1043 $aPlaceIDs = $oDB->getCol($sSQL);
1046 // Fallback to the road
1047 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1049 $aPlaceIDs = $aRoadPlaceIDs;
1054 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1056 $sPlaceIDs = join(',',$aPlaceIDs);
1057 $aClassPlaceIDs = array();
1059 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1061 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1062 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1063 $sSQL .= " and linked_place_id is null";
1064 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1065 $sSQL .= " order by rank_search asc limit $iLimit";
1066 if (CONST_Debug) var_dump($sSQL);
1067 $aClassPlaceIDs = $oDB->getCol($sSQL);
1070 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1072 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1073 $bCacheTable = $oDB->getOne($sSQL);
1075 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1077 if (CONST_Debug) var_dump($sSQL);
1078 $iMaxRank = ((int)$oDB->getOne($sSQL));
1080 // For state / country level searches the normal radius search doesn't work very well
1081 $sPlaceGeom = false;
1082 if ($iMaxRank < 9 && $bCacheTable)
1084 // Try and get a polygon to search in instead
1085 $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";
1086 if (CONST_Debug) var_dump($sSQL);
1087 $sPlaceGeom = $oDB->getOne($sSQL);
1097 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1098 if (CONST_Debug) var_dump($sSQL);
1099 $aPlaceIDs = $oDB->getCol($sSQL);
1100 $sPlaceIDs = join(',',$aPlaceIDs);
1103 if ($sPlaceIDs || $sPlaceGeom)
1109 // More efficient - can make the range bigger
1113 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1114 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1115 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1117 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1118 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1121 $sSQL .= ",placex as f where ";
1122 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1127 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1129 if (sizeof($aExcludePlaceIDs))
1131 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1133 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1134 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1135 if ($iOffset) $sSQL .= " offset $iOffset";
1136 $sSQL .= " limit $iLimit";
1137 if (CONST_Debug) var_dump($sSQL);
1138 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1142 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1145 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1146 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1148 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1149 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1150 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1151 if (sizeof($aExcludePlaceIDs))
1153 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1155 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1156 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1157 if ($iOffset) $sSQL .= " offset $iOffset";
1158 $sSQL .= " limit $iLimit";
1159 if (CONST_Debug) var_dump($sSQL);
1160 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1165 $aPlaceIDs = $aClassPlaceIDs;
1171 if (PEAR::IsError($aPlaceIDs))
1173 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1176 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1178 foreach($aPlaceIDs as $iPlaceID)
1180 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1182 if ($iQueryLoop > 20) break;
1186 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1187 if ($iGroupLoop > 4) break;
1188 if ($iQueryLoop > 30) break;
1191 // Did we find anything?
1192 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1194 //var_Dump($aResultPlaceIDs);exit;
1195 // Get the details for display (is this a redundant extra step?)
1196 $sPlaceIDs = join(',',$aResultPlaceIDs);
1197 $sOrderSQL = 'CASE ';
1198 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1200 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1202 $sOrderSQL .= ' ELSE 10000000 END';
1203 $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,";
1204 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1205 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1206 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1207 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1208 //$sSQL .= $sOrderSQL." as porder, ";
1209 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1210 $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, ";
1211 $sSQL .= "(extratags->'place') as extra_place ";
1212 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1213 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1214 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1216 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1217 $sSQL .= "and linked_place_id is null ";
1218 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1219 if (!$bDeDupe) $sSQL .= ",place_id";
1220 $sSQL .= ",langaddress ";
1221 $sSQL .= ",placename ";
1223 $sSQL .= ",extratags->'place' ";
1225 $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,";
1226 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1227 $sSQL .= "null as placename,";
1228 $sSQL .= "null as ref,";
1229 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1230 //$sSQL .= $sOrderSQL." as porder, ";
1231 $sSQL .= "-0.15 as importance, ";
1232 $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, ";
1233 $sSQL .= "null as extra_place ";
1234 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1235 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1236 $sSQL .= "group by place_id";
1237 if (!$bDeDupe) $sSQL .= ",place_id";
1239 $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,";
1240 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1241 $sSQL .= "null as placename,";
1242 $sSQL .= "null as ref,";
1243 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1244 //$sSQL .= $sOrderSQL." as porder, ";
1245 $sSQL .= "-0.10 as importance, ";
1246 $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, ";
1247 $sSQL .= "null as extra_place ";
1248 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1249 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1250 $sSQL .= "group by place_id";
1251 if (!$bDeDupe) $sSQL .= ",place_id";
1252 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1253 $sSQL .= "order by importance desc";
1254 //$sSQL .= "order by rank_search,rank_address,porder asc";
1255 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1256 $aSearchResults = $oDB->getAll($sSQL);
1257 //var_dump($sSQL,$aSearchResults);exit;
1259 if (PEAR::IsError($aSearchResults))
1261 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1264 } // end if ($sQuery)
1267 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1269 $iPlaceID = geocodeReverse((float)$_GET['nearlat'], (float)$_GET['nearlon']);
1273 $aResultPlaceIDs = array($iPlaceID);
1274 // TODO: this needs refactoring!
1276 // Get the details for display (is this a redundant extra step?)
1277 $sPlaceIDs = join(',',$aResultPlaceIDs);
1278 $sOrderSQL = 'CASE ';
1279 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1281 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1283 $sOrderSQL .= ' ELSE 10000000 END';
1284 $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,";
1285 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1286 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1287 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1288 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1289 //$sSQL .= $sOrderSQL." as porder, ";
1290 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1291 $sSQL .= "(extratags->'place') as extra_place ";
1292 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1293 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1294 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1296 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1297 if (!$bDeDupe) $sSQL .= ",place_id";
1298 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1299 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1300 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1301 $sSQL .= ",extratags->'place' ";
1303 $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,";
1304 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1305 $sSQL .= "null as placename,";
1306 $sSQL .= "null as ref,";
1307 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1308 //$sSQL .= $sOrderSQL." as porder, ";
1309 $sSQL .= "-0.15 as importance, ";
1310 $sSQL .= "null as extra_place ";
1311 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1312 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1313 $sSQL .= "group by place_id";
1314 if (!$bDeDupe) $sSQL .= ",place_id";
1316 $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,";
1317 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1318 $sSQL .= "null as placename,";
1319 $sSQL .= "null as ref,";
1320 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1321 //$sSQL .= $sOrderSQL." as porder, ";
1322 $sSQL .= "-0.10 as importance, ";
1323 $sSQL .= "null as extra_place ";
1324 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1325 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1326 $sSQL .= "group by place_id";
1327 if (!$bDeDupe) $sSQL .= ",place_id";
1328 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1329 $sSQL .= "order by importance desc";
1330 //$sSQL .= "order by rank_search,rank_address,porder asc";
1331 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1332 $aSearchResults = $oDB->getAll($sSQL);
1333 //var_dump($sSQL,$aSearchResults);exit;
1335 if (PEAR::IsError($aSearchResults))
1337 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1342 $aSearchResults = array();
1348 $sSearchResult = '';
1349 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1351 $sSearchResult = 'No Results Found';
1353 //var_Dump($aSearchResults);
1355 $aClassType = getClassTypesWithImportance();
1356 $aRecheckWords = preg_split('/\b/u',$sQuery);
1357 foreach($aRecheckWords as $i => $sWord)
1359 if (!$sWord) unset($aRecheckWords[$i]);
1361 foreach($aSearchResults as $iResNum => $aResult)
1363 if (CONST_Search_AreaPolygons)
1365 // Get the bounding box and outline polygon
1366 $sSQL = "select place_id,numfeatures,area,outline,";
1367 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1368 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1369 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1371 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1372 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1373 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1374 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1375 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1376 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1377 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1378 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1379 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1380 $aPointPolygon = $oDB->getRow($sSQL);
1381 if (PEAR::IsError($aPointPolygon))
1383 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1385 if ($aPointPolygon['place_id'])
1387 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1388 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1389 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1390 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1392 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1394 $aResult['lat'] = $aPointPolygon['centrelat'];
1395 $aResult['lon'] = $aPointPolygon['centrelon'];
1399 // Translate geometary string to point array
1400 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1402 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1404 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1406 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1408 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1411 $iSteps = ($fRadius * 40000)^2;
1412 $fStepSize = (2*pi())/$iSteps;
1413 $aPolyPoints = array();
1414 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1416 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1418 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1419 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1420 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1421 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1425 // Output data suitable for display (points and a bounding box)
1426 if ($bShowPolygons && isset($aPolyPoints))
1428 $aResult['aPolyPoints'] = array();
1429 foreach($aPolyPoints as $aPoint)
1431 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1434 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1438 if ($aResult['extra_place'] == 'city')
1440 $aResult['class'] = 'place';
1441 $aResult['type'] = 'city';
1442 $aResult['rank_search'] = 16;
1445 if (!isset($aResult['aBoundingBox']))
1448 $fDiameter = 0.0001;
1450 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1451 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1453 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1455 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1456 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1458 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1460 $fRadius = $fDiameter / 2;
1462 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1463 $fStepSize = (2*pi())/$iSteps;
1464 $aPolyPoints = array();
1465 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1467 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1469 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1470 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1471 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1472 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1474 // Output data suitable for display (points and a bounding box)
1477 $aResult['aPolyPoints'] = array();
1478 foreach($aPolyPoints as $aPoint)
1480 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1483 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1486 // Is there an icon set for this type of result?
1487 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1488 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1490 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1493 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1494 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1496 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1499 if ($bShowAddressDetails)
1501 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1502 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1504 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1507 //var_dump($aResult['address']);
1511 // Adjust importance for the number of exact string matches in the result
1512 $aResult['importance'] = max(0.001,$aResult['importance']);
1514 $sAddress = $aResult['langaddress'];
1515 foreach($aRecheckWords as $i => $sWord)
1517 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1520 $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
1522 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1524 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1525 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1527 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1529 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1530 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1532 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1536 $aResult['importance'] = 1000000000000000;
1539 $aResult['name'] = $aResult['langaddress'];
1540 $aResult['foundorder'] = -$aResult['addressimportance'];
1541 $aSearchResults[$iResNum] = $aResult;
1543 uasort($aSearchResults, 'byImportance');
1545 $aOSMIDDone = array();
1546 $aClassTypeNameDone = array();
1547 $aToFilter = $aSearchResults;
1548 $aSearchResults = array();
1551 foreach($aToFilter as $iResNum => $aResult)
1553 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1554 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1557 $fLat = $aResult['lat'];
1558 $fLon = $aResult['lon'];
1559 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1562 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1563 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1565 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1566 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1567 $aSearchResults[] = $aResult;
1570 // Absolute limit on number of results
1571 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1574 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1576 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1578 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1583 logEnd($oDB, $hLog, sizeof($aToFilter));
1585 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1586 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1587 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1588 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1589 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1590 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1593 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1595 $sMoreURL .= '&q='.urlencode($sQuery);
1597 if (CONST_Debug) exit;
1599 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');