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;
81 if (isset($aLangPrefOrder['name:pl'])) $bReverseInPlan = true;
83 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
85 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
87 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
89 $iExcludedPlaceID = (int)$iExcludedPlaceID;
90 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
94 // Only certain ranks of feature
95 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
97 if (isset($_GET['featuretype']))
99 switch($_GET['featuretype'])
102 $iMinAddressRank = $iMaxAddressRank = 4;
105 $iMinAddressRank = $iMaxAddressRank = 8;
108 $iMinAddressRank = 14;
109 $iMaxAddressRank = 16;
112 $iMinAddressRank = 8;
113 $iMaxAddressRank = 20;
118 if (isset($_GET['countrycodes']))
120 $aCountryCodes = array();
121 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
123 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
125 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
128 $sCountryCodesSQL = join(',', $aCountryCodes);
132 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
133 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
135 $sQuery = substr($_SERVER['PATH_INFO'], 1);
137 // reverse order of '/' separated string
138 $aPhrases = explode('/', $sQuery);
139 $aPhrases = array_reverse($aPhrases);
140 $sQuery = join(', ',$aPhrases);
143 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
145 if (!isset($_GET[$sKey])) return false;
146 $sValue = trim($_GET[$sKey]);
147 if (!$sValue) return false;
148 $aStructuredQuery[$sKey] = $sValue;
149 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30)
151 $iMinAddressRank = $iNewMinAddressRank;
152 $iMaxAddressRank = $iNewMaxAddressRank;
158 $aStructuredOptions = array(
159 array('amenity', 26, 30),
160 array('street', 26, 30),
161 array('city', 14, 24),
162 array('county', 9, 13),
163 array('state', 8, 8),
164 array('country', 4, 4),
165 array('postalcode', 5, 11),
167 $aStructuredQuery = array();
168 $sAllowedTypesSQLList = '';
169 foreach($aStructuredOptions as $aStructuredOption)
171 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
173 if (sizeof($aStructuredQuery) > 0)
175 $sQuery = join(', ', $aStructuredQuery);
176 if ($iMaxAddressRank < 30)
178 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
184 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
186 // Hack to make it handle "new york, ny" (and variants) correctly
187 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
188 if (isset($aLangPrefOrder['name:en']))
190 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
191 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
192 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
195 // If we have a view box create the SQL
196 // Small is the actual view box, Large is double (on each axis) that
197 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
198 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
200 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
201 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
203 if (isset($_GET['viewbox']) && $_GET['viewbox'])
205 $aCoOrdinates = explode(',',$_GET['viewbox']);
206 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
207 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
208 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
209 $aCoOrdinates[0] += $fHeight;
210 $aCoOrdinates[2] -= $fHeight;
211 $aCoOrdinates[1] += $fWidth;
212 $aCoOrdinates[3] -= $fWidth;
213 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
217 $bBoundingBoxSearch = false;
219 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
221 $aPoints = explode(',',$_GET['route']);
222 if (sizeof($aPoints) % 2 != 0)
224 userError("Uneven number of points");
227 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
229 foreach($aPoints as $i => $fPoint)
233 if ($i != 1) $sViewboxCentreSQL .= ",";
234 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
238 $fPrevCoord = (float)$fPoint;
241 $sViewboxCentreSQL .= ")'::geometry,4326)";
243 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
244 $sViewboxSmallSQL = $oDB->getOne($sSQL);
245 if (PEAR::isError($sViewboxSmallSQL))
247 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
249 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
251 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
252 $sViewboxLargeSQL = $oDB->getOne($sSQL);
253 if (PEAR::isError($sViewboxLargeSQL))
255 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
257 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
258 $bBoundingBoxSearch = true;
261 // Do we have anything that looks like a lat/lon pair?
262 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
264 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
265 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/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.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
275 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
276 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
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));
284 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
286 $fQueryLat = $aData[2];
287 $fQueryLon = $aData[3];
288 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
290 $_GET['nearlat'] = $fQueryLat;
291 $_GET['nearlon'] = $fQueryLon;
292 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
296 if ($sQuery || $aStructuredQuery)
298 // Start with a blank search
300 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
301 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
302 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
305 $sNearPointSQL = false;
306 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
308 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
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']);
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 in (26,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($_GET['nearlat'], $_GET['nearlon']);
1270 $aResultPlaceIDs = array($iPlaceID);
1272 // TODO: this needs refactoring!
1274 // Get the details for display (is this a redundant extra step?)
1275 $sPlaceIDs = join(',',$aResultPlaceIDs);
1276 $sOrderSQL = 'CASE ';
1277 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1279 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1281 $sOrderSQL .= ' ELSE 10000000 END';
1282 $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,";
1283 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1284 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1285 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1286 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1287 //$sSQL .= $sOrderSQL." as porder, ";
1288 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1289 $sSQL .= "(extratags->'place') as extra_place ";
1290 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1291 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1292 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1294 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1295 if (!$bDeDupe) $sSQL .= ",place_id";
1296 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1297 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1298 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1299 $sSQL .= ",extratags->'place' ";
1301 $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,";
1302 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1303 $sSQL .= "null as placename,";
1304 $sSQL .= "null as ref,";
1305 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1306 //$sSQL .= $sOrderSQL." as porder, ";
1307 $sSQL .= "-0.15 as importance, ";
1308 $sSQL .= "null as extra_place ";
1309 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1310 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1311 $sSQL .= "group by place_id";
1312 if (!$bDeDupe) $sSQL .= ",place_id";
1314 $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,";
1315 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1316 $sSQL .= "null as placename,";
1317 $sSQL .= "null as ref,";
1318 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1319 //$sSQL .= $sOrderSQL." as porder, ";
1320 $sSQL .= "-0.10 as importance, ";
1321 $sSQL .= "null as extra_place ";
1322 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1323 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1324 $sSQL .= "group by place_id";
1325 if (!$bDeDupe) $sSQL .= ",place_id";
1326 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1327 $sSQL .= "order by importance desc";
1328 //$sSQL .= "order by rank_search,rank_address,porder asc";
1329 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1330 $aSearchResults = $oDB->getAll($sSQL);
1331 //var_dump($sSQL,$aSearchResults);exit;
1333 if (PEAR::IsError($aSearchResults))
1335 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1341 $sSearchResult = '';
1342 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1344 $sSearchResult = 'No Results Found';
1346 //var_Dump($aSearchResults);
1348 $aClassType = getClassTypesWithImportance();
1349 $aRecheckWords = preg_split('/\b/u',$sQuery);
1350 foreach($aRecheckWords as $i => $sWord)
1352 if (!$sWord) unset($aRecheckWords[$i]);
1354 foreach($aSearchResults as $iResNum => $aResult)
1356 if (CONST_Search_AreaPolygons)
1358 // Get the bounding box and outline polygon
1359 $sSQL = "select place_id,numfeatures,area,outline,";
1360 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1361 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1362 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1364 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1365 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1366 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1367 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1368 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1369 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1370 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1371 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1372 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1373 $aPointPolygon = $oDB->getRow($sSQL);
1374 if (PEAR::IsError($aPointPolygon))
1376 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1378 if ($aPointPolygon['place_id'])
1380 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1381 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1382 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1383 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1385 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1387 $aResult['lat'] = $aPointPolygon['centrelat'];
1388 $aResult['lon'] = $aPointPolygon['centrelon'];
1392 // Translate geometary string to point array
1393 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1395 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1397 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1399 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1401 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1404 $iSteps = ($fRadius * 40000)^2;
1405 $fStepSize = (2*pi())/$iSteps;
1406 $aPolyPoints = array();
1407 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1409 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1411 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1412 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1413 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1414 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1418 // Output data suitable for display (points and a bounding box)
1419 if ($bShowPolygons && isset($aPolyPoints))
1421 $aResult['aPolyPoints'] = array();
1422 foreach($aPolyPoints as $aPoint)
1424 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1427 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1431 if ($aResult['extra_place'] == 'city')
1433 $aResult['class'] = 'place';
1434 $aResult['type'] = 'city';
1435 $aResult['rank_search'] = 16;
1438 if (!isset($aResult['aBoundingBox']))
1441 $fDiameter = 0.0001;
1443 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1444 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1446 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1448 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1449 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1451 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1453 $fRadius = $fDiameter / 2;
1455 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1456 $fStepSize = (2*pi())/$iSteps;
1457 $aPolyPoints = array();
1458 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1460 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1462 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1463 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1464 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1465 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1467 // Output data suitable for display (points and a bounding box)
1470 $aResult['aPolyPoints'] = array();
1471 foreach($aPolyPoints as $aPoint)
1473 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1476 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1479 // Is there an icon set for this type of result?
1480 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1481 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1483 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1486 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1487 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1489 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1492 if ($bShowAddressDetails)
1494 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1495 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1497 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1500 //var_dump($aResult['address']);
1504 // Adjust importance for the number of exact string matches in the result
1505 $aResult['importance'] = max(0.001,$aResult['importance']);
1507 $sAddress = $aResult['langaddress'];
1508 foreach($aRecheckWords as $i => $sWord)
1510 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1513 $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
1515 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1517 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1518 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1520 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1522 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1523 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1525 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1529 $aResult['importance'] = 1000000000000000;
1532 $aResult['name'] = $aResult['langaddress'];
1533 $aResult['foundorder'] = -$aResult['addressimportance'];
1534 $aSearchResults[$iResNum] = $aResult;
1536 uasort($aSearchResults, 'byImportance');
1538 $aOSMIDDone = array();
1539 $aClassTypeNameDone = array();
1540 $aToFilter = $aSearchResults;
1541 $aSearchResults = array();
1544 foreach($aToFilter as $iResNum => $aResult)
1546 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1547 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1550 $fLat = $aResult['lat'];
1551 $fLon = $aResult['lon'];
1552 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1555 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1556 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1558 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1559 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1560 $aSearchResults[] = $aResult;
1563 // Absolute limit on number of results
1564 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1567 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1569 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1571 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1576 logEnd($oDB, $hLog, sizeof($aToFilter));
1578 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1579 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1580 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1581 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1582 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1583 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1586 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1588 $sMoreURL .= '&q='.urlencode($sQuery);
1590 if (CONST_Debug) exit;
1592 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');