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 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
21 $bReverseInPlan = false;
22 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
23 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
25 if ($iFinalLimit > 50) $iFinalLimit = 50;
26 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
28 $iMaxAddressRank = 30;
29 $sAllowedTypesSQLList = false;
32 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
34 $sOutputFormat = $_GET['format'];
37 // Show / use polygons
38 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
39 if ($sOutputFormat == 'html')
41 $bAsText = $bShowPolygons;
42 $bShowPolygons = false;
49 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
50 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
51 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
52 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
53 if ((($bShowPolygons?1:0)
58 ) > CONST_PolygonOutput_MaximumTypes)
60 if (CONST_PolygonOutput_MaximumTypes)
62 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
66 userError("Polygon output is disabled");
72 // Show address breakdown
73 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
76 $aLangPrefOrder = getPreferredLanguages();
77 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
78 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
79 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
81 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
83 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
85 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
87 $iExcludedPlaceID = (int)$iExcludedPlaceID;
88 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
92 // Only certain ranks of feature
93 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
95 if (isset($_GET['featuretype']))
97 switch($_GET['featuretype'])
100 $iMinAddressRank = $iMaxAddressRank = 4;
103 $iMinAddressRank = $iMaxAddressRank = 8;
106 $iMinAddressRank = 14;
107 $iMaxAddressRank = 16;
110 $iMinAddressRank = 8;
111 $iMaxAddressRank = 20;
116 if (isset($_GET['countrycodes']))
118 $aCountryCodes = array();
119 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
121 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
123 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
126 $sCountryCodesSQL = join(',', $aCountryCodes);
130 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
131 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
133 $sQuery = substr($_SERVER['PATH_INFO'], 1);
135 // reverse order of '/' separated string
136 $aPhrases = explode('/', $sQuery);
137 $aPhrases = array_reverse($aPhrases);
138 $sQuery = join(', ',$aPhrases);
141 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
143 if (!isset($_GET[$sKey])) return false;
144 $sValue = trim($_GET[$sKey]);
145 if (!$sValue) return false;
146 $aStructuredQuery[$sKey] = $sValue;
147 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30)
149 $iMinAddressRank = $iNewMinAddressRank;
150 $iMaxAddressRank = $iNewMaxAddressRank;
156 $aStructuredOptions = array(
157 array('amenity', 26, 30),
158 array('street', 26, 30),
159 array('city', 14, 24),
160 array('county', 9, 13),
161 array('state', 8, 8),
162 array('country', 4, 4),
163 array('postalcode', 5, 11),
165 $aStructuredQuery = array();
166 $sAllowedTypesSQLList = '';
167 foreach($aStructuredOptions as $aStructuredOption)
169 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
171 if (sizeof($aStructuredQuery) > 0)
173 $sQuery = join(', ', $aStructuredQuery);
174 if ($iMaxAddressRank < 30)
176 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
182 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
184 // Hack to make it handle "new york, ny" (and variants) correctly
185 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
186 if (isset($aLangPrefOrder['name:en']))
188 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
189 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
190 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
193 // If we have a view box create the SQL
194 // Small is the actual view box, Large is double (on each axis) that
195 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
196 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
198 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
199 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
201 if (isset($_GET['viewbox']) && $_GET['viewbox'])
203 $aCoOrdinates = explode(',',$_GET['viewbox']);
204 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
205 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
206 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
207 $aCoOrdinates[0] += $fHeight;
208 $aCoOrdinates[2] -= $fHeight;
209 $aCoOrdinates[1] += $fWidth;
210 $aCoOrdinates[3] -= $fWidth;
211 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
215 $bBoundingBoxSearch = false;
217 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
219 $aPoints = explode(',',$_GET['route']);
220 if (sizeof($aPoints) % 2 != 0)
222 userError("Uneven number of points");
225 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
227 foreach($aPoints as $i => $fPoint)
231 if ($i != 1) $sViewboxCentreSQL .= ",";
232 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
236 $fPrevCoord = (float)$fPoint;
239 $sViewboxCentreSQL .= ")'::geometry,4326)";
241 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
242 $sViewboxSmallSQL = $oDB->getOne($sSQL);
243 if (PEAR::isError($sViewboxSmallSQL))
245 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
247 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
249 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
250 $sViewboxLargeSQL = $oDB->getOne($sSQL);
251 if (PEAR::isError($sViewboxLargeSQL))
253 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
255 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
256 $bBoundingBoxSearch = true;
259 // Do we have anything that looks like a lat/lon pair?
260 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
262 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
263 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
264 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
266 $_GET['nearlat'] = $fQueryLat;
267 $_GET['nearlon'] = $fQueryLon;
268 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
271 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
273 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
274 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
275 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
277 $_GET['nearlat'] = $fQueryLat;
278 $_GET['nearlon'] = $fQueryLon;
279 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
282 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
284 $fQueryLat = $aData[2];
285 $fQueryLon = $aData[3];
286 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
288 $_GET['nearlat'] = $fQueryLat;
289 $_GET['nearlon'] = $fQueryLon;
290 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
294 if ($sQuery || $aStructuredQuery)
296 // Start with a blank search
298 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
299 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
300 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
303 $sNearPointSQL = false;
304 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
306 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".(float)$_GET['nearlat']."),4326)";
307 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
308 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
309 $aSearches[0]['fRadius'] = 0.1;
312 $bSpecialTerms = false;
313 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
314 $aSpecialTerms = array();
315 foreach($aSpecialTermsRaw as $aSpecialTerm)
317 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
318 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
321 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
322 $aSpecialTerms = array();
323 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
325 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
326 unset($aStructuredQuery['amenity']);
328 foreach($aSpecialTermsRaw as $aSpecialTerm)
330 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
331 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
332 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
333 $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';
334 if (CONST_Debug) var_Dump($sSQL);
335 $aSearchWords = $oDB->getAll($sSQL);
336 $aNewSearches = array();
337 foreach($aSearches as $aSearch)
339 foreach($aSearchWords as $aSearchTerm)
341 $aNewSearch = $aSearch;
342 if ($aSearchTerm['country_code'])
344 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
345 $aNewSearches[] = $aNewSearch;
346 $bSpecialTerms = true;
348 if ($aSearchTerm['class'])
350 $aNewSearch['sClass'] = $aSearchTerm['class'];
351 $aNewSearch['sType'] = $aSearchTerm['type'];
352 $aNewSearches[] = $aNewSearch;
353 $bSpecialTerms = true;
357 $aSearches = $aNewSearches;
360 // Split query into phrases
361 // Commas are used to reduce the search space by indicating where phrases split
362 if (sizeof($aStructuredQuery) > 0)
364 $aPhrases = $aStructuredQuery;
365 $bStructuredPhrases = true;
369 $aPhrases = explode(',',$sQuery);
370 $bStructuredPhrases = false;
374 // Convert each phrase to standard form
375 // Create a list of standard words
376 // Get all 'sets' of words
377 // Generate a complete list of all
379 foreach($aPhrases as $iPhrase => $sPhrase)
381 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
382 if (PEAR::isError($aPhrase))
384 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
385 if (CONST_Debug) var_dump($aPhrase);
388 if (trim($aPhrase['string']))
390 $aPhrases[$iPhrase] = $aPhrase;
391 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
392 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
393 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
397 unset($aPhrases[$iPhrase]);
401 // reindex phrases - we make assumptions later on
402 $aPhraseTypes = array_keys($aPhrases);
403 $aPhrases = array_values($aPhrases);
405 if (sizeof($aTokens))
408 // Check which tokens we have, get the ID numbers
409 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
410 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
411 //$sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
412 //$sSQL .= ' group by word_token, word, class, type, country_code';
414 if (CONST_Debug) var_Dump($sSQL);
416 $aValidTokens = array();
417 if (sizeof($aTokens)) $aDatabaseWords = $oDB->getAll($sSQL);
418 else $aDatabaseWords = array();
419 if (PEAR::IsError($aDatabaseWords))
421 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
423 $aPossibleMainWordIDs = array();
424 $aWordFrequencyScores = array();
425 foreach($aDatabaseWords as $aToken)
427 // Very special case - require 2 letter country param to match the country code found
428 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
429 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
434 if (isset($aValidTokens[$aToken['word_token']]))
436 $aValidTokens[$aToken['word_token']][] = $aToken;
440 $aValidTokens[$aToken['word_token']] = array($aToken);
442 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
443 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
445 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
447 // Try and calculate GB postcodes we might be missing
448 foreach($aTokens as $sToken)
450 // Source of gb postcodes is now definitive - always use
451 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
453 if (substr($aData[1],-2,1) != ' ')
455 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
456 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
458 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
459 if ($aGBPostcodeLocation)
461 $aValidTokens[$sToken] = $aGBPostcodeLocation;
466 foreach($aTokens as $sToken)
468 // Unknown single word token with a number - assume it is a house number
469 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
471 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
475 // Any words that have failed completely?
478 // Start the search process
479 $aResultPlaceIDs = array();
482 Calculate all searches using aValidTokens i.e.
484 'Wodsworth Road, Sheffield' =>
488 0 1 (wodsworth)(road)
491 Score how good the search is so they can be ordered
493 foreach($aPhrases as $iPhrase => $sPhrase)
495 $aNewPhraseSearches = array();
496 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
497 else $sPhraseType = '';
499 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
501 $aWordsetSearches = $aSearches;
503 // Add all words from this wordset
504 foreach($aWordset as $iToken => $sToken)
506 //echo "<br><b>$sToken</b>";
507 $aNewWordsetSearches = array();
509 foreach($aWordsetSearches as $aCurrentSearch)
512 //var_dump($aCurrentSearch);
515 // If the token is valid
516 if (isset($aValidTokens[' '.$sToken]))
518 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
520 $aSearch = $aCurrentSearch;
521 $aSearch['iSearchRank']++;
522 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
524 if ($aSearch['sCountryCode'] === false)
526 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
527 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
528 // If reverse order is enabled, it may appear at the beginning as well.
529 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
530 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
532 $aSearch['iSearchRank'] += 5;
534 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
537 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
539 if ($aSearch['fLat'] === '')
541 $aSearch['fLat'] = $aSearchTerm['lat'];
542 $aSearch['fLon'] = $aSearchTerm['lon'];
543 $aSearch['fRadius'] = $aSearchTerm['radius'];
544 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
547 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
549 if ($aSearch['sHouseNumber'] === '')
551 $aSearch['sHouseNumber'] = $sToken;
552 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
554 // Fall back to not searching for this item (better than nothing)
555 $aSearch = $aCurrentSearch;
556 $aSearch['iSearchRank'] += 1;
557 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
561 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
563 if ($aSearch['sClass'] === '')
565 $aSearch['sOperator'] = $aSearchTerm['operator'];
566 $aSearch['sClass'] = $aSearchTerm['class'];
567 $aSearch['sType'] = $aSearchTerm['type'];
568 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
569 else $aSearch['sOperator'] = 'near'; // near = in for the moment
571 // Do we have a shortcut id?
572 if ($aSearch['sOperator'] == 'name')
574 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
575 if ($iAmenityID = $oDB->getOne($sSQL))
577 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
578 $aSearch['aName'][$iAmenityID] = $iAmenityID;
579 $aSearch['sClass'] = '';
580 $aSearch['sType'] = '';
583 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
586 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
588 if (sizeof($aSearch['aName']))
590 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
592 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
596 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
597 $aSearch['iSearchRank'] += 1000; // skip;
602 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
603 //$aSearch['iNamePhrase'] = $iPhrase;
605 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
609 if (isset($aValidTokens[$sToken]))
611 // Allow searching for a word - but at extra cost
612 foreach($aValidTokens[$sToken] as $aSearchTerm)
614 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
616 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
618 $aSearch = $aCurrentSearch;
619 $aSearch['iSearchRank'] += 1;
620 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
622 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
623 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
625 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
627 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
629 if (empty($aSearchTermToken['country_code'])
630 && empty($aSearchTermToken['lat'])
631 && empty($aSearchTermToken['class']))
633 $aSearch = $aCurrentSearch;
634 $aSearch['iSearchRank'] += 1;
635 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
636 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
642 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
643 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
647 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
649 $aSearch = $aCurrentSearch;
650 $aSearch['iSearchRank'] += 2;
651 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
652 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
653 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
655 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
656 $aSearch['iNamePhrase'] = $iPhrase;
657 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
664 // Allow skipping a word - but at EXTREAM cost
665 //$aSearch = $aCurrentSearch;
666 //$aSearch['iSearchRank']+=100;
667 //$aNewWordsetSearches[] = $aSearch;
671 usort($aNewWordsetSearches, 'bySearchRank');
672 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
674 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
676 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
677 usort($aNewPhraseSearches, 'bySearchRank');
679 $aSearchHash = array();
680 foreach($aNewPhraseSearches as $iSearch => $aSearch)
682 $sHash = serialize($aSearch);
683 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
684 else $aSearchHash[$sHash] = 1;
687 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
690 // Re-group the searches by their score, junk anything over 20 as just not worth trying
691 $aGroupedSearches = array();
692 foreach($aNewPhraseSearches as $aSearch)
694 if ($aSearch['iSearchRank'] < $iMaxRank)
696 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
697 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
700 ksort($aGroupedSearches);
703 $aSearches = array();
704 foreach($aGroupedSearches as $iScore => $aNewSearches)
706 $iSearchCount += sizeof($aNewSearches);
707 $aSearches = array_merge($aSearches, $aNewSearches);
708 if ($iSearchCount > 50) break;
711 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
717 // Re-group the searches by their score, junk anything over 20 as just not worth trying
718 $aGroupedSearches = array();
719 foreach($aSearches as $aSearch)
721 if ($aSearch['iSearchRank'] < $iMaxRank)
723 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
724 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
727 ksort($aGroupedSearches);
730 if (CONST_Debug) var_Dump($aGroupedSearches);
734 $aCopyGroupedSearches = $aGroupedSearches;
735 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
737 foreach($aSearches as $iSearch => $aSearch)
739 if (sizeof($aSearch['aAddress']))
741 $iReverseItem = array_pop($aSearch['aAddress']);
742 if (isset($aPossibleMainWordIDs[$iReverseItem]))
744 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
745 $aSearch['aName'] = array($iReverseItem);
746 $aGroupedSearches[$iGroup][] = $aSearch;
748 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
749 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
755 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
757 $aCopyGroupedSearches = $aGroupedSearches;
758 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
760 foreach($aSearches as $iSearch => $aSearch)
762 $aReductionsList = array($aSearch['aAddress']);
763 $iSearchRank = $aSearch['iSearchRank'];
764 while(sizeof($aReductionsList) > 0)
767 if ($iSearchRank > iMaxRank) break 3;
768 $aNewReductionsList = array();
769 foreach($aReductionsList as $aReductionsWordList)
771 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
773 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
774 $aReverseSearch = $aSearch;
775 $aSearch['aAddress'] = $aReductionsWordListResult;
776 $aSearch['iSearchRank'] = $iSearchRank;
777 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
778 if (sizeof($aReductionsWordListResult) > 0)
780 $aNewReductionsList[] = $aReductionsWordListResult;
784 $aReductionsList = $aNewReductionsList;
788 ksort($aGroupedSearches);
791 // Filter out duplicate searches
792 $aSearchHash = array();
793 foreach($aGroupedSearches as $iGroup => $aSearches)
795 foreach($aSearches as $iSearch => $aSearch)
797 $sHash = serialize($aSearch);
798 if (isset($aSearchHash[$sHash]))
800 unset($aGroupedSearches[$iGroup][$iSearch]);
801 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
805 $aSearchHash[$sHash] = 1;
810 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
814 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
817 foreach($aSearches as $aSearch)
821 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
822 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
825 // Must have a location term
826 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
828 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
830 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
832 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
833 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
834 $sSQL .= " order by st_area(geometry) desc limit 1";
835 if (CONST_Debug) var_dump($sSQL);
836 $aPlaceIDs = $oDB->getCol($sSQL);
841 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
842 if (!$aSearch['sClass']) continue;
843 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
844 if ($oDB->getOne($sSQL))
846 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
847 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
848 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
849 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
850 if (sizeof($aExcludePlaceIDs))
852 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
854 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
855 $sSQL .= " limit $iLimit";
856 if (CONST_Debug) var_dump($sSQL);
857 $aPlaceIDs = $oDB->getCol($sSQL);
859 // If excluded place IDs are given, it is fair to assume that
860 // there have been results in the small box, so no further
861 // expansion in that case.
862 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
864 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
865 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
866 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
867 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
868 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
869 $sSQL .= " limit $iLimit";
870 if (CONST_Debug) var_dump($sSQL);
871 $aPlaceIDs = $oDB->getCol($sSQL);
876 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
877 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
878 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
879 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
880 $sSQL .= " limit $iLimit";
881 if (CONST_Debug) var_dump($sSQL);
882 $aPlaceIDs = $oDB->getCol($sSQL);
888 $aPlaceIDs = array();
890 // First we need a position, either aName or fLat or both
894 // TODO: filter out the pointless search terms (2 letter name tokens and less)
895 // they might be right - but they are just too darned expensive to run
896 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
897 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
898 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
900 // For infrequent name terms disable index usage for address
901 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
902 sizeof($aSearch['aName']) == 1 &&
903 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
905 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
909 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
910 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
913 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
914 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
915 if ($aSearch['fLon'] && $aSearch['fLat'])
917 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
918 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
920 if (sizeof($aExcludePlaceIDs))
922 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
924 if ($sCountryCodesSQL)
926 $aTerms[] = "country_code in ($sCountryCodesSQL)";
929 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
930 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
932 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
933 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
934 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
935 $aOrder[] = "$sImportanceSQL DESC";
936 if (sizeof($aSearch['aFullNameAddress']))
937 $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
941 $sSQL = "select place_id";
942 $sSQL .= " from search_name";
943 $sSQL .= " where ".join(' and ',$aTerms);
944 $sSQL .= " order by ".join(', ',$aOrder);
945 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
946 $sSQL .= " limit 50";
947 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
950 $sSQL .= " limit ".$iLimit;
952 if (CONST_Debug) { var_dump($sSQL); }
953 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
954 if (PEAR::IsError($aViewBoxPlaceIDs))
956 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
958 //var_dump($aViewBoxPlaceIDs);
959 // Did we have an viewbox matches?
960 $aPlaceIDs = array();
961 $bViewBoxMatch = false;
962 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
964 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
965 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
966 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
967 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
968 $aPlaceIDs[] = $aViewBoxRow['place_id'];
971 //var_Dump($aPlaceIDs);
974 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
976 $aRoadPlaceIDs = $aPlaceIDs;
977 $sPlaceIDs = join(',',$aPlaceIDs);
979 // Now they are indexed look for a house attached to a street we found
980 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
981 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
982 if (sizeof($aExcludePlaceIDs))
984 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
986 $sSQL .= " limit $iLimit";
987 if (CONST_Debug) var_dump($sSQL);
988 $aPlaceIDs = $oDB->getCol($sSQL);
990 // If not try the aux fallback table
991 if (!sizeof($aPlaceIDs))
993 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
994 if (sizeof($aExcludePlaceIDs))
996 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
998 //$sSQL .= " limit $iLimit";
999 if (CONST_Debug) var_dump($sSQL);
1000 $aPlaceIDs = $oDB->getCol($sSQL);
1003 if (!sizeof($aPlaceIDs))
1005 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1006 if (sizeof($aExcludePlaceIDs))
1008 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1010 //$sSQL .= " limit $iLimit";
1011 if (CONST_Debug) var_dump($sSQL);
1012 $aPlaceIDs = $oDB->getCol($sSQL);
1015 // Fallback to the road
1016 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1018 $aPlaceIDs = $aRoadPlaceIDs;
1023 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1025 $sPlaceIDs = join(',',$aPlaceIDs);
1026 $aClassPlaceIDs = array();
1028 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1030 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1031 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1032 $sSQL .= " and linked_place_id is null";
1033 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1034 $sSQL .= " order by rank_search asc limit $iLimit";
1035 if (CONST_Debug) var_dump($sSQL);
1036 $aClassPlaceIDs = $oDB->getCol($sSQL);
1039 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1041 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1042 $bCacheTable = $oDB->getOne($sSQL);
1044 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1046 if (CONST_Debug) var_dump($sSQL);
1047 $iMaxRank = ((int)$oDB->getOne($sSQL));
1049 // For state / country level searches the normal radius search doesn't work very well
1050 $sPlaceGeom = false;
1051 if ($iMaxRank < 9 && $bCacheTable)
1053 // Try and get a polygon to search in instead
1054 $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";
1055 if (CONST_Debug) var_dump($sSQL);
1056 $sPlaceGeom = $oDB->getOne($sSQL);
1066 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1067 if (CONST_Debug) var_dump($sSQL);
1068 $aPlaceIDs = $oDB->getCol($sSQL);
1069 $sPlaceIDs = join(',',$aPlaceIDs);
1072 if ($sPlaceIDs || $sPlaceGeom)
1078 // More efficient - can make the range bigger
1082 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1083 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1084 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1086 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1087 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1090 $sSQL .= ",placex as f where ";
1091 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1096 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1098 if (sizeof($aExcludePlaceIDs))
1100 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1102 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1103 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1104 if ($iOffset) $sSQL .= " offset $iOffset";
1105 $sSQL .= " limit $iLimit";
1106 if (CONST_Debug) var_dump($sSQL);
1107 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1111 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1114 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1115 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1117 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1118 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1119 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1120 if (sizeof($aExcludePlaceIDs))
1122 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1124 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1125 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1126 if ($iOffset) $sSQL .= " offset $iOffset";
1127 $sSQL .= " limit $iLimit";
1128 if (CONST_Debug) var_dump($sSQL);
1129 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1134 $aPlaceIDs = $aClassPlaceIDs;
1140 if (PEAR::IsError($aPlaceIDs))
1142 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1145 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1147 foreach($aPlaceIDs as $iPlaceID)
1149 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1151 if ($iQueryLoop > 20) break;
1155 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1156 if ($iGroupLoop > 4) break;
1157 if ($iQueryLoop > 30) break;
1160 // Did we find anything?
1161 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1163 //var_Dump($aResultPlaceIDs);exit;
1164 // Get the details for display (is this a redundant extra step?)
1165 $sPlaceIDs = join(',',$aResultPlaceIDs);
1166 $sOrderSQL = 'CASE ';
1167 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1169 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1171 $sOrderSQL .= ' ELSE 10000000 END';
1172 $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,";
1173 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1174 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1175 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1176 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1177 //$sSQL .= $sOrderSQL." as porder, ";
1178 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1179 $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, ";
1180 $sSQL .= "(extratags->'place') as extra_place ";
1181 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1182 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1183 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1185 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1186 $sSQL .= "and linked_place_id is null ";
1187 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1188 if (!$bDeDupe) $sSQL .= ",place_id";
1189 $sSQL .= ",langaddress ";
1190 $sSQL .= ",placename ";
1192 $sSQL .= ",extratags->'place' ";
1194 $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,";
1195 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1196 $sSQL .= "null as placename,";
1197 $sSQL .= "null as ref,";
1198 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1199 //$sSQL .= $sOrderSQL." as porder, ";
1200 $sSQL .= "-0.15 as importance, ";
1201 $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, ";
1202 $sSQL .= "null as extra_place ";
1203 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1204 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1205 $sSQL .= "group by place_id";
1206 if (!$bDeDupe) $sSQL .= ",place_id";
1208 $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,";
1209 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1210 $sSQL .= "null as placename,";
1211 $sSQL .= "null as ref,";
1212 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1213 //$sSQL .= $sOrderSQL." as porder, ";
1214 $sSQL .= "-0.10 as importance, ";
1215 $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, ";
1216 $sSQL .= "null as extra_place ";
1217 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1218 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1219 $sSQL .= "group by place_id";
1220 if (!$bDeDupe) $sSQL .= ",place_id";
1221 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1222 $sSQL .= "order by importance desc";
1223 //$sSQL .= "order by rank_search,rank_address,porder asc";
1224 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1225 $aSearchResults = $oDB->getAll($sSQL);
1226 //var_dump($sSQL,$aSearchResults);exit;
1228 if (PEAR::IsError($aSearchResults))
1230 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1233 } // end if ($sQuery)
1236 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1238 $iPlaceID = geocodeReverse((float)$_GET['nearlat'], (float)$_GET['nearlon']);
1242 $aResultPlaceIDs = array($iPlaceID);
1243 // TODO: this needs refactoring!
1245 // Get the details for display (is this a redundant extra step?)
1246 $sPlaceIDs = join(',',$aResultPlaceIDs);
1247 $sOrderSQL = 'CASE ';
1248 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1250 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1252 $sOrderSQL .= ' ELSE 10000000 END';
1253 $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,";
1254 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1255 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1256 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1257 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1258 //$sSQL .= $sOrderSQL." as porder, ";
1259 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1260 $sSQL .= "(extratags->'place') as extra_place ";
1261 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1262 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1263 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1265 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1266 if (!$bDeDupe) $sSQL .= ",place_id";
1267 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1268 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1269 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1270 $sSQL .= ",extratags->'place' ";
1272 $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,";
1273 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1274 $sSQL .= "null as placename,";
1275 $sSQL .= "null as ref,";
1276 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1277 //$sSQL .= $sOrderSQL." as porder, ";
1278 $sSQL .= "-0.15 as importance, ";
1279 $sSQL .= "null as extra_place ";
1280 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1281 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1282 $sSQL .= "group by place_id";
1283 if (!$bDeDupe) $sSQL .= ",place_id";
1285 $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,";
1286 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1287 $sSQL .= "null as placename,";
1288 $sSQL .= "null as ref,";
1289 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1290 //$sSQL .= $sOrderSQL." as porder, ";
1291 $sSQL .= "-0.10 as importance, ";
1292 $sSQL .= "null as extra_place ";
1293 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1294 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1295 $sSQL .= "group by place_id";
1296 if (!$bDeDupe) $sSQL .= ",place_id";
1297 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1298 $sSQL .= "order by importance desc";
1299 //$sSQL .= "order by rank_search,rank_address,porder asc";
1300 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1301 $aSearchResults = $oDB->getAll($sSQL);
1302 //var_dump($sSQL,$aSearchResults);exit;
1304 if (PEAR::IsError($aSearchResults))
1306 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1311 $aSearchResults = array();
1317 $sSearchResult = '';
1318 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1320 $sSearchResult = 'No Results Found';
1322 //var_Dump($aSearchResults);
1324 $aClassType = getClassTypesWithImportance();
1325 $aRecheckWords = preg_split('/\b/u',$sQuery);
1326 foreach($aRecheckWords as $i => $sWord)
1328 if (!$sWord) unset($aRecheckWords[$i]);
1330 foreach($aSearchResults as $iResNum => $aResult)
1332 if (CONST_Search_AreaPolygons)
1334 // Get the bounding box and outline polygon
1335 $sSQL = "select place_id,numfeatures,area,outline,";
1336 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1337 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1338 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1340 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1341 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1342 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1343 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1344 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1345 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1346 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1347 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1348 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1349 $aPointPolygon = $oDB->getRow($sSQL);
1350 if (PEAR::IsError($aPointPolygon))
1352 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1354 if ($aPointPolygon['place_id'])
1356 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1357 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1358 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1359 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1361 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1363 $aResult['lat'] = $aPointPolygon['centrelat'];
1364 $aResult['lon'] = $aPointPolygon['centrelon'];
1368 // Translate geometary string to point array
1369 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1371 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1373 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1375 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1377 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1380 $iSteps = ($fRadius * 40000)^2;
1381 $fStepSize = (2*pi())/$iSteps;
1382 $aPolyPoints = array();
1383 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1385 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1387 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1388 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1389 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1390 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1394 // Output data suitable for display (points and a bounding box)
1395 if ($bShowPolygons && isset($aPolyPoints))
1397 $aResult['aPolyPoints'] = array();
1398 foreach($aPolyPoints as $aPoint)
1400 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1403 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1407 if ($aResult['extra_place'] == 'city')
1409 $aResult['class'] = 'place';
1410 $aResult['type'] = 'city';
1411 $aResult['rank_search'] = 16;
1414 if (!isset($aResult['aBoundingBox']))
1417 $fDiameter = 0.0001;
1419 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1420 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1422 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1424 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1425 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1427 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1429 $fRadius = $fDiameter / 2;
1431 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1432 $fStepSize = (2*pi())/$iSteps;
1433 $aPolyPoints = array();
1434 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1436 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1438 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1439 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1440 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1441 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1443 // Output data suitable for display (points and a bounding box)
1446 $aResult['aPolyPoints'] = array();
1447 foreach($aPolyPoints as $aPoint)
1449 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1452 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1455 // Is there an icon set for this type of result?
1456 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1457 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1459 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1462 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1463 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1465 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1468 if ($bShowAddressDetails)
1470 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1471 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1473 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1476 //var_dump($aResult['address']);
1480 // Adjust importance for the number of exact string matches in the result
1481 $aResult['importance'] = max(0.001,$aResult['importance']);
1483 $sAddress = $aResult['langaddress'];
1484 foreach($aRecheckWords as $i => $sWord)
1486 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1489 $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
1491 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1493 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1494 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1496 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1498 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1499 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1501 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1505 $aResult['importance'] = 1000000000000000;
1508 $aResult['name'] = $aResult['langaddress'];
1509 $aResult['foundorder'] = -$aResult['addressimportance'];
1510 $aSearchResults[$iResNum] = $aResult;
1512 uasort($aSearchResults, 'byImportance');
1514 $aOSMIDDone = array();
1515 $aClassTypeNameDone = array();
1516 $aToFilter = $aSearchResults;
1517 $aSearchResults = array();
1520 foreach($aToFilter as $iResNum => $aResult)
1522 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1523 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1526 $fLat = $aResult['lat'];
1527 $fLon = $aResult['lon'];
1528 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1531 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1532 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1534 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1535 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1536 $aSearchResults[] = $aResult;
1539 // Absolute limit on number of results
1540 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1543 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1545 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1547 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1552 logEnd($oDB, $hLog, sizeof($aToFilter));
1554 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1555 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1556 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1557 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1558 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1559 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1560 $sMoreURL .= '&q='.urlencode($sQuery);
1562 if (CONST_Debug) exit;
1564 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');