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') {
41 $bAsText = $bShowPolygons;
42 $bShowPolygons = false;
47 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
48 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
49 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
50 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
51 if ((($bShowPolygons?1:0)
56 ) > CONST_PolygonOutput_MaximumTypes) {
57 if (CONST_PolygonOutput_MaximumTypes) {
58 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
60 userError("Polygon output is disabled");
66 // Show address breakdown
67 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
70 $aLangPrefOrder = getPreferredLanguages();
71 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
72 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
73 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
74 if (isset($aLangPrefOrder['name:pl'])) $bReverseInPlan = true;
76 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
78 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
80 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
82 $iExcludedPlaceID = (int)$iExcludedPlaceID;
83 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
87 // Only certain ranks of feature
88 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
90 if (isset($_GET['featuretype']))
92 switch($_GET['featuretype'])
95 $iMinAddressRank = $iMaxAddressRank = 4;
98 $iMinAddressRank = $iMaxAddressRank = 8;
101 $iMinAddressRank = 14;
102 $iMaxAddressRank = 16;
105 $iMinAddressRank = 8;
106 $iMaxAddressRank = 20;
111 if (isset($_GET['countrycodes']))
113 $aCountryCodes = array();
114 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
116 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
118 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
121 $sCountryCodesSQL = join(',', $aCountryCodes);
125 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
126 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
128 $sQuery = substr($_SERVER['PATH_INFO'], 1);
130 // reverse order of '/' separated string
131 $aPhrases = explode('/', $sQuery);
132 $aPhrases = array_reverse($aPhrases);
133 $sQuery = join(', ',$aPhrases);
136 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
138 if (!isset($_GET[$sKey])) return false;
139 $sValue = trim($_GET[$sKey]);
140 if (!$sValue) return false;
141 $aStructuredQuery[$sKey] = $sValue;
142 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
143 $iMinAddressRank = $iNewMinAddressRank;
144 $iMaxAddressRank = $iNewMaxAddressRank;
150 $aStructuredOptions = array(
151 array('amenity', 26, 30),
152 array('street', 26, 30),
153 array('city', 14, 24),
154 array('county', 9, 13),
155 array('state', 8, 8),
156 array('country', 4, 4),
157 array('postalcode', 5, 11),
159 $aStructuredQuery = array();
160 $sAllowedTypesSQLList = '';
161 foreach($aStructuredOptions as $aStructuredOption)
163 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
165 if (sizeof($aStructuredQuery) > 0) {
166 $sQuery = join(', ', $aStructuredQuery);
167 if ($iMaxAddressRank < 30)
169 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
175 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
177 // Hack to make it handle "new york, ny" (and variants) correctly
178 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
179 if (isset($aLangPrefOrder['name:en']))
181 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
182 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
183 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
186 // If we have a view box create the SQL
187 // Small is the actual view box, Large is double (on each axis) that
188 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
189 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
191 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
192 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
194 if (isset($_GET['viewbox']) && $_GET['viewbox'])
196 $aCoOrdinates = explode(',',$_GET['viewbox']);
197 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
198 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
199 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
200 $aCoOrdinates[0] += $fHeight;
201 $aCoOrdinates[2] -= $fHeight;
202 $aCoOrdinates[1] += $fWidth;
203 $aCoOrdinates[3] -= $fWidth;
204 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
206 $bBoundingBoxSearch = false;
208 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
210 $aPoints = explode(',',$_GET['route']);
211 if (sizeof($aPoints) % 2 != 0)
213 userError("Uneven number of points");
216 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
218 foreach($aPoints as $i => $fPoint)
222 if ($i != 1) $sViewboxCentreSQL .= ",";
223 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
227 $fPrevCoord = (float)$fPoint;
230 $sViewboxCentreSQL .= ")'::geometry,4326)";
232 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
233 $sViewboxSmallSQL = $oDB->getOne($sSQL);
234 if (PEAR::isError($sViewboxSmallSQL))
236 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
238 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
240 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
241 $sViewboxLargeSQL = $oDB->getOne($sSQL);
242 if (PEAR::isError($sViewboxLargeSQL))
244 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
246 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
247 $bBoundingBoxSearch = true;
250 // Do we have anything that looks like a lat/lon pair?
251 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
253 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
254 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
255 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
257 $_GET['nearlat'] = $fQueryLat;
258 $_GET['nearlon'] = $fQueryLon;
259 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
262 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
264 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
265 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
266 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
268 $_GET['nearlat'] = $fQueryLat;
269 $_GET['nearlon'] = $fQueryLon;
270 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
273 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
275 $fQueryLat = $aData[2];
276 $fQueryLon = $aData[3];
277 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
279 $_GET['nearlat'] = $fQueryLat;
280 $_GET['nearlon'] = $fQueryLon;
281 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
285 if ($sQuery || $aStructuredQuery)
287 // Start with a blank search
289 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
290 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
291 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
294 $sNearPointSQL = false;
295 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
297 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
298 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
299 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
300 $aSearches[0]['fRadius'] = 0.1;
303 $bSpecialTerms = false;
304 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
305 $aSpecialTerms = array();
306 foreach($aSpecialTermsRaw as $aSpecialTerm)
308 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
309 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
312 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
313 $aSpecialTerms = array();
314 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
316 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
317 unset($aStructuredQuery['amenity']);
319 foreach($aSpecialTermsRaw as $aSpecialTerm)
321 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
322 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
323 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
324 $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';
325 if (CONST_Debug) var_Dump($sSQL);
326 $aSearchWords = $oDB->getAll($sSQL);
327 $aNewSearches = array();
328 foreach($aSearches as $aSearch)
330 foreach($aSearchWords as $aSearchTerm)
332 $aNewSearch = $aSearch;
333 if ($aSearchTerm['country_code'])
335 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
336 $aNewSearches[] = $aNewSearch;
337 $bSpecialTerms = true;
339 if ($aSearchTerm['class'])
341 $aNewSearch['sClass'] = $aSearchTerm['class'];
342 $aNewSearch['sType'] = $aSearchTerm['type'];
343 $aNewSearches[] = $aNewSearch;
344 $bSpecialTerms = true;
348 $aSearches = $aNewSearches;
351 // Split query into phrases
352 // Commas are used to reduce the search space by indicating where phrases split
353 if (sizeof($aStructuredQuery) > 0)
355 $aPhrases = $aStructuredQuery;
356 $bStructuredPhrases = true;
360 $aPhrases = explode(',',$sQuery);
361 $bStructuredPhrases = false;
365 // Convert each phrase to standard form
366 // Create a list of standard words
367 // Get all 'sets' of words
368 // Generate a complete list of all
370 foreach($aPhrases as $iPhrase => $sPhrase)
372 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
373 if (PEAR::isError($aPhrase))
375 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
376 if (CONST_Debug) var_dump($aPhrase);
379 if (trim($aPhrase['string']))
381 $aPhrases[$iPhrase] = $aPhrase;
382 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
383 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
384 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
388 unset($aPhrases[$iPhrase]);
392 // reindex phrases - we make assumptions later on
393 $aPhraseTypes = array_keys($aPhrases);
394 $aPhrases = array_values($aPhrases);
396 if (sizeof($aTokens))
399 // Check which tokens we have, get the ID numbers
400 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator, search_name_count';
401 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
402 // $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
403 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
405 if (CONST_Debug) var_Dump($sSQL);
407 $aValidTokens = array();
408 if (sizeof($aTokens))
409 $aDatabaseWords = $oDB->getAll($sSQL);
411 $aDatabaseWords = array();
412 if (PEAR::IsError($aDatabaseWords))
414 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
416 $aPossibleMainWordIDs = array();
417 $aWordFrequencyScores = array();
418 foreach($aDatabaseWords as $aToken)
420 // Very special case - require 2 letter country param to match the country code found
421 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
422 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
427 if (isset($aValidTokens[$aToken['word_token']]))
429 $aValidTokens[$aToken['word_token']][] = $aToken;
433 $aValidTokens[$aToken['word_token']] = array($aToken);
435 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
436 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
438 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
440 $aSuggestion = array();
441 $bSuggestion = false;
442 if (CONST_Suggestions_Enabled)
444 foreach($aPhrases as $iPhrase => $aPhrase)
446 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
448 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
449 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
450 $aRow = $aSuggestionWords[0];
451 if ($aRow && $aRow['word'])
453 $aSuggestion[] = $aRow['word'];
458 $aSuggestion[] = $aPhrase['string'];
463 $aSuggestion[] = $aPhrase['string'];
467 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
469 // Try and calculate GB postcodes we might be missing
470 foreach($aTokens as $sToken)
472 // Source of gb postcodes is now definitive - always use
473 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
475 if (substr($aData[1],-2,1) != ' ')
477 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
478 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
480 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
481 if ($aGBPostcodeLocation)
483 $aValidTokens[$sToken] = $aGBPostcodeLocation;
488 foreach($aTokens as $sToken)
490 // Unknown single word token with a number - assume it is a house number
491 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
493 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
497 // Any words that have failed completely?
500 // Start the search process
501 $aResultPlaceIDs = array();
504 Calculate all searches using aValidTokens i.e.
506 'Wodsworth Road, Sheffield' =>
510 0 1 (wodsworth)(road)
513 Score how good the search is so they can be ordered
515 foreach($aPhrases as $iPhrase => $sPhrase)
517 $aNewPhraseSearches = array();
518 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
519 else $sPhraseType = '';
521 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
523 $aWordsetSearches = $aSearches;
525 // Add all words from this wordset
526 foreach($aWordset as $iToken => $sToken)
528 //echo "<br><b>$sToken</b>";
529 $aNewWordsetSearches = array();
531 foreach($aWordsetSearches as $aCurrentSearch)
534 //var_dump($aCurrentSearch);
537 // If the token is valid
538 if (isset($aValidTokens[' '.$sToken]))
540 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
542 $aSearch = $aCurrentSearch;
543 $aSearch['iSearchRank']++;
544 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
546 if ($aSearch['sCountryCode'] === false)
548 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
549 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
550 // If reverse order is enabled, it may appear at the beginning as well.
551 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
552 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
554 $aSearch['iSearchRank'] += 5;
556 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
559 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
561 if ($aSearch['fLat'] === '')
563 $aSearch['fLat'] = $aSearchTerm['lat'];
564 $aSearch['fLon'] = $aSearchTerm['lon'];
565 $aSearch['fRadius'] = $aSearchTerm['radius'];
566 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
569 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
571 if ($aSearch['sHouseNumber'] === '')
573 $aSearch['sHouseNumber'] = $sToken;
574 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
576 // Fall back to not searching for this item (better than nothing)
577 $aSearch = $aCurrentSearch;
578 $aSearch['iSearchRank'] += 1;
579 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
583 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
585 if ($aSearch['sClass'] === '')
587 $aSearch['sOperator'] = $aSearchTerm['operator'];
588 $aSearch['sClass'] = $aSearchTerm['class'];
589 $aSearch['sType'] = $aSearchTerm['type'];
590 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
591 else $aSearch['sOperator'] = 'near'; // near = in for the moment
593 // Do we have a shortcut id?
594 if ($aSearch['sOperator'] == 'name')
596 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
597 if ($iAmenityID = $oDB->getOne($sSQL))
599 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
600 $aSearch['aName'][$iAmenityID] = $iAmenityID;
601 $aSearch['sClass'] = '';
602 $aSearch['sType'] = '';
605 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
608 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
610 if (sizeof($aSearch['aName']))
612 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
614 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
618 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
619 $aSearch['iSearchRank'] += 1000; // skip;
624 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
625 // $aSearch['iNamePhrase'] = $iPhrase;
627 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
631 if (isset($aValidTokens[$sToken]))
633 // Allow searching for a word - but at extra cost
634 foreach($aValidTokens[$sToken] as $aSearchTerm)
636 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
638 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
640 $aSearch = $aCurrentSearch;
641 $aSearch['iSearchRank'] += 1;
642 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
644 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
645 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
647 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
649 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
651 if (empty($aSearchTermToken['country_code'])
652 && empty($aSearchTermToken['lat'])
653 && empty($aSearchTermToken['class']))
655 $aSearch = $aCurrentSearch;
656 $aSearch['iSearchRank'] += 1;
657 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
658 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
664 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
665 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
669 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
671 $aSearch = $aCurrentSearch;
672 $aSearch['iSearchRank'] += 2;
673 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
674 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
675 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
677 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
678 $aSearch['iNamePhrase'] = $iPhrase;
679 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
686 // Allow skipping a word - but at EXTREAM cost
687 //$aSearch = $aCurrentSearch;
688 //$aSearch['iSearchRank']+=100;
689 //$aNewWordsetSearches[] = $aSearch;
693 usort($aNewWordsetSearches, 'bySearchRank');
694 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
696 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
698 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
699 usort($aNewPhraseSearches, 'bySearchRank');
701 $aSearchHash = array();
702 foreach($aNewPhraseSearches as $iSearch => $aSearch)
704 $sHash = serialize($aSearch);
705 if (isset($aSearchHash[$sHash]))
707 unset($aNewPhraseSearches[$iSearch]);
711 $aSearchHash[$sHash] = 1;
715 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
718 // Re-group the searches by their score, junk anything over 20 as just not worth trying
719 $aGroupedSearches = array();
720 foreach($aNewPhraseSearches as $aSearch)
722 if ($aSearch['iSearchRank'] < $iMaxRank)
724 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
725 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
728 ksort($aGroupedSearches);
731 $aSearches = array();
732 foreach($aGroupedSearches as $iScore => $aNewSearches)
734 $iSearchCount += sizeof($aNewSearches);
735 $aSearches = array_merge($aSearches, $aNewSearches);
736 if ($iSearchCount > 50) break;
739 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
745 // Re-group the searches by their score, junk anything over 20 as just not worth trying
746 $aGroupedSearches = array();
747 foreach($aSearches as $aSearch)
749 if ($aSearch['iSearchRank'] < $iMaxRank)
751 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
752 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
755 ksort($aGroupedSearches);
758 if (CONST_Debug) var_Dump($aGroupedSearches);
762 $aCopyGroupedSearches = $aGroupedSearches;
763 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
765 foreach($aSearches as $iSearch => $aSearch)
767 if (sizeof($aSearch['aAddress']))
769 $iReverseItem = array_pop($aSearch['aAddress']);
770 if (isset($aPossibleMainWordIDs[$iReverseItem]))
772 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
773 $aSearch['aName'] = array($iReverseItem);
774 $aGroupedSearches[$iGroup][] = $aSearch;
776 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
777 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
783 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
785 $aCopyGroupedSearches = $aGroupedSearches;
786 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
788 foreach($aSearches as $iSearch => $aSearch)
790 $aReductionsList = array($aSearch['aAddress']);
791 $iSearchRank = $aSearch['iSearchRank'];
792 while(sizeof($aReductionsList) > 0)
795 if ($iSearchRank > iMaxRank) break 3;
796 $aNewReductionsList = array();
797 foreach($aReductionsList as $aReductionsWordList)
799 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
801 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
802 $aReverseSearch = $aSearch;
803 $aSearch['aAddress'] = $aReductionsWordListResult;
804 $aSearch['iSearchRank'] = $iSearchRank;
805 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
806 if (sizeof($aReductionsWordListResult) > 0)
808 $aNewReductionsList[] = $aReductionsWordListResult;
812 $aReductionsList = $aNewReductionsList;
816 ksort($aGroupedSearches);
819 // Filter out duplicate searches
820 $aSearchHash = array();
821 foreach($aGroupedSearches as $iGroup => $aSearches)
823 foreach($aSearches as $iSearch => $aSearch)
825 $sHash = serialize($aSearch);
826 if (isset($aSearchHash[$sHash]))
828 unset($aGroupedSearches[$iGroup][$iSearch]);
829 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
833 $aSearchHash[$sHash] = 1;
838 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
842 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
845 foreach($aSearches as $aSearch)
849 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
850 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
853 // Must have a location term
854 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
856 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
858 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
860 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
861 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
862 $sSQL .= " order by st_area(geometry) desc limit 1";
863 if (CONST_Debug) var_dump($sSQL);
864 $aPlaceIDs = $oDB->getCol($sSQL);
869 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
870 if (!$aSearch['sClass']) continue;
871 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
872 if ($oDB->getOne($sSQL))
874 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
875 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
876 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
877 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
878 if (sizeof($aExcludePlaceIDs))
880 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
882 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
883 $sSQL .= " limit $iLimit";
884 if (CONST_Debug) var_dump($sSQL);
885 $aPlaceIDs = $oDB->getCol($sSQL);
887 // If excluded place IDs are given, it is fair to assume that
888 // there have been results in the small box, so no further
889 // expansion in that case.
890 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
892 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
893 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
894 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
895 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
896 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
897 $sSQL .= " limit $iLimit";
898 if (CONST_Debug) var_dump($sSQL);
899 $aPlaceIDs = $oDB->getCol($sSQL);
904 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
905 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
906 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
907 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
908 $sSQL .= " limit $iLimit";
909 if (CONST_Debug) var_dump($sSQL);
910 $aPlaceIDs = $oDB->getCol($sSQL);
916 $aPlaceIDs = array();
918 // First we need a position, either aName or fLat or both
922 // TODO: filter out the pointless search terms (2 letter name tokens and less)
923 // they might be right - but they are just too darned expensive to run
924 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
925 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
926 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
928 // For infrequent name terms disable index usage for address
929 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
930 sizeof($aSearch['aName']) == 1 &&
931 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
933 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
937 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
938 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
941 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
942 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
943 if ($aSearch['fLon'] && $aSearch['fLat'])
945 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
946 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
948 if (sizeof($aExcludePlaceIDs))
950 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
952 if ($sCountryCodesSQL)
954 $aTerms[] = "country_code in ($sCountryCodesSQL)";
957 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
958 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
960 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
961 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
962 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
963 $aOrder[] = "$sImportanceSQL DESC";
964 if (sizeof($aSearch['aFullNameAddress']))
965 $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
970 $sSQL = "select place_id";
971 $sSQL .= " from search_name";
972 $sSQL .= " where ".join(' and ',$aTerms);
973 $sSQL .= " order by ".join(', ',$aOrder);
974 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
975 $sSQL .= " limit 50";
976 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
979 $sSQL .= " limit ".$iLimit;
981 if (CONST_Debug) var_dump($sSQL);
982 $iStartTime = time();
983 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
984 if (PEAR::IsError($aViewBoxPlaceIDs))
986 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
988 if (time() - $iStartTime > 60) {
989 file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
992 //var_dump($aViewBoxPlaceIDs);
993 // Did we have an viewbox matches?
994 $aPlaceIDs = array();
995 $bViewBoxMatch = false;
996 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
998 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
999 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1000 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1001 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1002 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1005 //var_Dump($aPlaceIDs);
1008 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1010 $aRoadPlaceIDs = $aPlaceIDs;
1011 $sPlaceIDs = join(',',$aPlaceIDs);
1013 // Now they are indexed look for a house attached to a street we found
1014 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
1015 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1016 if (sizeof($aExcludePlaceIDs))
1018 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1020 $sSQL .= " limit $iLimit";
1021 if (CONST_Debug) var_dump($sSQL);
1022 $aPlaceIDs = $oDB->getCol($sSQL);
1024 // If not try the aux fallback table
1025 if (!sizeof($aPlaceIDs))
1027 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1028 if (sizeof($aExcludePlaceIDs))
1030 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1032 // $sSQL .= " limit $iLimit";
1033 if (CONST_Debug) var_dump($sSQL);
1034 $aPlaceIDs = $oDB->getCol($sSQL);
1037 if (!sizeof($aPlaceIDs))
1039 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1040 if (sizeof($aExcludePlaceIDs))
1042 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1044 // $sSQL .= " limit $iLimit";
1045 if (CONST_Debug) var_dump($sSQL);
1046 $aPlaceIDs = $oDB->getCol($sSQL);
1049 // Fallback to the road
1050 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1052 $aPlaceIDs = $aRoadPlaceIDs;
1057 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1059 $sPlaceIDs = join(',',$aPlaceIDs);
1061 $aClassPlaceIDs = array();
1063 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1065 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1066 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1067 $sSQL .= " and linked_place_id is null";
1068 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1069 $sSQL .= " order by rank_search asc limit $iLimit";
1070 if (CONST_Debug) var_dump($sSQL);
1071 $aClassPlaceIDs = $oDB->getCol($sSQL);
1074 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1076 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1077 $bCacheTable = $oDB->getOne($sSQL);
1079 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1081 if (CONST_Debug) var_dump($sSQL);
1082 $iMaxRank = ((int)$oDB->getOne($sSQL));
1084 // For state / country level searches the normal radius search doesn't work very well
1085 $sPlaceGeom = false;
1086 if ($iMaxRank < 9 && $bCacheTable)
1088 // Try and get a polygon to search in instead
1089 $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";
1090 if (CONST_Debug) var_dump($sSQL);
1091 $sPlaceGeom = $oDB->getOne($sSQL);
1101 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1102 if (CONST_Debug) var_dump($sSQL);
1103 $aPlaceIDs = $oDB->getCol($sSQL);
1104 $sPlaceIDs = join(',',$aPlaceIDs);
1107 if ($sPlaceIDs || $sPlaceGeom)
1113 // More efficient - can make the range bigger
1117 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1118 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1119 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1121 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1122 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1125 $sSQL .= ",placex as f where ";
1126 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1131 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1133 if (sizeof($aExcludePlaceIDs))
1135 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1137 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1138 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1139 if ($iOffset) $sSQL .= " offset $iOffset";
1140 $sSQL .= " limit $iLimit";
1141 if (CONST_Debug) var_dump($sSQL);
1142 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1146 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1149 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1150 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1152 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1153 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1154 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1155 if (sizeof($aExcludePlaceIDs))
1157 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1159 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1160 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1161 if ($iOffset) $sSQL .= " offset $iOffset";
1162 $sSQL .= " limit $iLimit";
1163 if (CONST_Debug) var_dump($sSQL);
1164 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1169 $aPlaceIDs = $aClassPlaceIDs;
1175 if (PEAR::IsError($aPlaceIDs))
1177 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1180 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1182 foreach($aPlaceIDs as $iPlaceID)
1184 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1186 if ($iQueryLoop > 20) break;
1190 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1191 if ($iGroupLoop > 4) break;
1192 if ($iQueryLoop > 30) break;
1195 // Did we find anything?
1196 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1198 //var_Dump($aResultPlaceIDs);exit;
1199 // Get the details for display (is this a redundant extra step?)
1200 $sPlaceIDs = join(',',$aResultPlaceIDs);
1201 $sOrderSQL = 'CASE ';
1202 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1204 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1206 $sOrderSQL .= ' ELSE 10000000 END';
1207 $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,";
1208 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1209 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1210 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1211 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1212 // $sSQL .= $sOrderSQL." as porder, ";
1213 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1214 $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, ";
1215 $sSQL .= "(extratags->'place') as extra_place ";
1216 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1217 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1218 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1220 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1221 $sSQL .= "and linked_place_id is null ";
1222 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1223 if (!$bDeDupe) $sSQL .= ",place_id";
1224 $sSQL .= ",langaddress ";
1225 $sSQL .= ",placename ";
1227 $sSQL .= ",extratags->'place' ";
1229 $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,";
1230 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1231 $sSQL .= "null as placename,";
1232 $sSQL .= "null as ref,";
1233 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1234 // $sSQL .= $sOrderSQL." as porder, ";
1235 $sSQL .= "-0.15 as importance, ";
1236 $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, ";
1237 $sSQL .= "null as extra_place ";
1238 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1239 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1240 $sSQL .= "group by place_id";
1241 if (!$bDeDupe) $sSQL .= ",place_id";
1243 $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,";
1244 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1245 $sSQL .= "null as placename,";
1246 $sSQL .= "null as ref,";
1247 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1248 // $sSQL .= $sOrderSQL." as porder, ";
1249 $sSQL .= "-0.10 as importance, ";
1250 $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, ";
1251 $sSQL .= "null as extra_place ";
1252 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1253 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1254 $sSQL .= "group by place_id";
1255 if (!$bDeDupe) $sSQL .= ",place_id";
1256 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1257 $sSQL .= "order by importance desc";
1258 // $sSQL .= "order by rank_search,rank_address,porder asc";
1259 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1260 $aSearchResults = $oDB->getAll($sSQL);
1261 //var_dump($sSQL,$aSearchResults);exit;
1263 if (PEAR::IsError($aSearchResults))
1265 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1268 } // end if ($sQuery)
1271 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1273 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1274 $aResultPlaceIDs = array($iPlaceID);
1276 // TODO: this needs refactoring!
1278 // Get the details for display (is this a redundant extra step?)
1279 $sPlaceIDs = join(',',$aResultPlaceIDs);
1280 $sOrderSQL = 'CASE ';
1281 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1283 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1285 $sOrderSQL .= ' ELSE 10000000 END';
1286 $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,";
1287 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1288 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1289 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1290 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1291 // $sSQL .= $sOrderSQL." as porder, ";
1292 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1293 $sSQL .= "(extratags->'place') as extra_place ";
1294 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1295 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1296 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1298 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1299 if (!$bDeDupe) $sSQL .= ",place_id";
1300 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1301 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1302 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1303 $sSQL .= ",extratags->'place' ";
1305 $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,";
1306 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1307 $sSQL .= "null as placename,";
1308 $sSQL .= "null as ref,";
1309 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1310 // $sSQL .= $sOrderSQL." as porder, ";
1311 $sSQL .= "-0.15 as importance, ";
1312 $sSQL .= "null as extra_place ";
1313 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1314 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1315 $sSQL .= "group by place_id";
1316 if (!$bDeDupe) $sSQL .= ",place_id";
1318 $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,";
1319 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1320 $sSQL .= "null as placename,";
1321 $sSQL .= "null as ref,";
1322 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1323 // $sSQL .= $sOrderSQL." as porder, ";
1324 $sSQL .= "-0.10 as importance, ";
1325 $sSQL .= "null as extra_place ";
1326 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1327 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1328 $sSQL .= "group by place_id";
1329 if (!$bDeDupe) $sSQL .= ",place_id";
1330 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1331 $sSQL .= "order by importance desc";
1332 // $sSQL .= "order by rank_search,rank_address,porder asc";
1333 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1334 $aSearchResults = $oDB->getAll($sSQL);
1335 //var_dump($sSQL,$aSearchResults);exit;
1337 if (PEAR::IsError($aSearchResults))
1339 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1345 $sSearchResult = '';
1346 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1348 $sSearchResult = 'No Results Found';
1350 //var_Dump($aSearchResults);
1352 $aClassType = getClassTypesWithImportance();
1353 $aRecheckWords = preg_split('/\b/u',$sQuery);
1354 foreach($aRecheckWords as $i => $sWord)
1356 if (!$sWord) unset($aRecheckWords[$i]);
1358 foreach($aSearchResults as $iResNum => $aResult)
1360 if (CONST_Search_AreaPolygons)
1362 // Get the bounding box and outline polygon
1363 $sSQL = "select place_id,numfeatures,area,outline,";
1364 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1365 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1366 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1368 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1369 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1370 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1371 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1372 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1373 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1374 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1375 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1376 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1377 $aPointPolygon = $oDB->getRow($sSQL);
1378 if (PEAR::IsError($aPointPolygon))
1380 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1382 if ($aPointPolygon['place_id'])
1384 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1385 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1386 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1387 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1389 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1390 $aResult['lat'] = $aPointPolygon['centrelat'];
1391 $aResult['lon'] = $aPointPolygon['centrelon'];
1395 // Translate geometary string to point array
1396 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1398 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1400 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1402 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1404 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1407 $iSteps = ($fRadius * 40000)^2;
1408 $fStepSize = (2*pi())/$iSteps;
1409 $aPolyPoints = array();
1410 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1412 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1414 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1415 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1416 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1417 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1421 // Output data suitable for display (points and a bounding box)
1422 if ($bShowPolygons && isset($aPolyPoints))
1424 $aResult['aPolyPoints'] = array();
1425 foreach($aPolyPoints as $aPoint)
1427 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1430 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1434 if ($aResult['extra_place'] == 'city')
1436 $aResult['class'] = 'place';
1437 $aResult['type'] = 'city';
1438 $aResult['rank_search'] = 16;
1441 if (!isset($aResult['aBoundingBox']))
1444 $fDiameter = 0.0001;
1446 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1447 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1449 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1451 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1452 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1454 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1456 $fRadius = $fDiameter / 2;
1458 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1459 $fStepSize = (2*pi())/$iSteps;
1460 $aPolyPoints = array();
1461 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1463 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1465 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1466 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1467 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1468 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1470 // Output data suitable for display (points and a bounding box)
1473 $aResult['aPolyPoints'] = array();
1474 foreach($aPolyPoints as $aPoint)
1476 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1479 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1482 // Is there an icon set for this type of result?
1483 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1484 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1486 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1489 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1490 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1492 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1495 if ($bShowAddressDetails)
1497 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1498 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1500 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1503 //var_dump($aResult['address']);
1507 // Adjust importance for the number of exact string matches in the result
1508 $aResult['importance'] = max(0.001,$aResult['importance']);
1510 $sAddress = $aResult['langaddress'];
1511 foreach($aRecheckWords as $i => $sWord)
1513 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1516 $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
1518 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1520 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1521 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1523 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1525 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1526 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1528 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1532 $aResult['importance'] = 1000000000000000;
1535 $aResult['name'] = $aResult['langaddress'];
1536 $aResult['foundorder'] = -$aResult['addressimportance'];
1537 $aSearchResults[$iResNum] = $aResult;
1539 uasort($aSearchResults, 'byImportance');
1541 $aOSMIDDone = array();
1542 $aClassTypeNameDone = array();
1543 $aToFilter = $aSearchResults;
1544 $aSearchResults = array();
1547 foreach($aToFilter as $iResNum => $aResult)
1549 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1550 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1553 $fLat = $aResult['lat'];
1554 $fLon = $aResult['lon'];
1555 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1558 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1559 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1561 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1562 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1563 $aSearchResults[] = $aResult;
1566 // Absolute limit on number of results
1567 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1570 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1572 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1574 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1579 logEnd($oDB, $hLog, sizeof($aToFilter));
1581 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1582 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1583 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1584 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1585 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1586 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1589 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1591 $sMoreURL .= '&q='.urlencode($sQuery);
1593 if (CONST_Debug) exit;
1595 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');