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;
80 if (isset($aLangPrefOrder['name:pl'])) $bReverseInPlan = true;
82 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
84 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
86 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
88 $iExcludedPlaceID = (int)$iExcludedPlaceID;
89 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
93 // Only certain ranks of feature
94 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
96 if (isset($_GET['featuretype']))
98 switch($_GET['featuretype'])
101 $iMinAddressRank = $iMaxAddressRank = 4;
104 $iMinAddressRank = $iMaxAddressRank = 8;
107 $iMinAddressRank = 14;
108 $iMaxAddressRank = 16;
111 $iMinAddressRank = 8;
112 $iMaxAddressRank = 20;
117 if (isset($_GET['countrycodes']))
119 $aCountryCodes = array();
120 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
122 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
124 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
127 $sCountryCodesSQL = join(',', $aCountryCodes);
131 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
132 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
134 $sQuery = substr($_SERVER['PATH_INFO'], 1);
136 // reverse order of '/' separated string
137 $aPhrases = explode('/', $sQuery);
138 $aPhrases = array_reverse($aPhrases);
139 $sQuery = join(', ',$aPhrases);
142 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
144 if (!isset($_GET[$sKey])) return false;
145 $sValue = trim($_GET[$sKey]);
146 if (!$sValue) return false;
147 $aStructuredQuery[$sKey] = $sValue;
148 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30)
150 $iMinAddressRank = $iNewMinAddressRank;
151 $iMaxAddressRank = $iNewMaxAddressRank;
157 $aStructuredOptions = array(
158 array('amenity', 26, 30),
159 array('street', 26, 30),
160 array('city', 14, 24),
161 array('county', 9, 13),
162 array('state', 8, 8),
163 array('country', 4, 4),
164 array('postalcode', 5, 11),
166 $aStructuredQuery = array();
167 $sAllowedTypesSQLList = '';
168 foreach($aStructuredOptions as $aStructuredOption)
170 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
172 if (sizeof($aStructuredQuery) > 0)
174 $sQuery = join(', ', $aStructuredQuery);
175 if ($iMaxAddressRank < 30)
177 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
183 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
185 // Hack to make it handle "new york, ny" (and variants) correctly
186 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
187 if (isset($aLangPrefOrder['name:en']))
189 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
190 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
191 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
194 // If we have a view box create the SQL
195 // Small is the actual view box, Large is double (on each axis) that
196 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
197 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
199 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
200 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
202 if (isset($_GET['viewbox']) && $_GET['viewbox'])
204 $aCoOrdinates = explode(',',$_GET['viewbox']);
205 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
206 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
207 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
208 $aCoOrdinates[0] += $fHeight;
209 $aCoOrdinates[2] -= $fHeight;
210 $aCoOrdinates[1] += $fWidth;
211 $aCoOrdinates[3] -= $fWidth;
212 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
216 $bBoundingBoxSearch = false;
218 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
220 $aPoints = explode(',',$_GET['route']);
221 if (sizeof($aPoints) % 2 != 0)
223 userError("Uneven number of points");
226 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
228 foreach($aPoints as $i => $fPoint)
232 if ($i != 1) $sViewboxCentreSQL .= ",";
233 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
237 $fPrevCoord = (float)$fPoint;
240 $sViewboxCentreSQL .= ")'::geometry,4326)";
242 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
243 $sViewboxSmallSQL = $oDB->getOne($sSQL);
244 if (PEAR::isError($sViewboxSmallSQL))
246 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
248 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
250 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
251 $sViewboxLargeSQL = $oDB->getOne($sSQL);
252 if (PEAR::isError($sViewboxLargeSQL))
254 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
256 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
257 $bBoundingBoxSearch = true;
260 // Do we have anything that looks like a lat/lon pair?
261 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
263 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
264 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
265 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
267 $_GET['nearlat'] = $fQueryLat;
268 $_GET['nearlon'] = $fQueryLon;
269 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
272 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
274 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
275 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
276 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
278 $_GET['nearlat'] = $fQueryLat;
279 $_GET['nearlon'] = $fQueryLon;
280 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
283 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
285 $fQueryLat = $aData[2];
286 $fQueryLon = $aData[3];
287 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
289 $_GET['nearlat'] = $fQueryLat;
290 $_GET['nearlon'] = $fQueryLon;
291 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
295 if ($sQuery || $aStructuredQuery)
297 // Start with a blank search
299 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
300 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
301 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
304 $sNearPointSQL = false;
305 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
307 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".(float)$_GET['nearlat']."),4326)";
308 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
309 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
310 $aSearches[0]['fRadius'] = 0.1;
313 $bSpecialTerms = false;
314 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
315 $aSpecialTerms = array();
316 foreach($aSpecialTermsRaw as $aSpecialTerm)
318 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
319 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
322 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
323 $aSpecialTerms = array();
324 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
326 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
327 unset($aStructuredQuery['amenity']);
329 foreach($aSpecialTermsRaw as $aSpecialTerm)
331 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
332 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
333 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
334 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null';
335 if (CONST_Debug) var_Dump($sSQL);
336 $aSearchWords = $oDB->getAll($sSQL);
337 $aNewSearches = array();
338 foreach($aSearches as $aSearch)
340 foreach($aSearchWords as $aSearchTerm)
342 $aNewSearch = $aSearch;
343 if ($aSearchTerm['country_code'])
345 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
346 $aNewSearches[] = $aNewSearch;
347 $bSpecialTerms = true;
349 if ($aSearchTerm['class'])
351 $aNewSearch['sClass'] = $aSearchTerm['class'];
352 $aNewSearch['sType'] = $aSearchTerm['type'];
353 $aNewSearches[] = $aNewSearch;
354 $bSpecialTerms = true;
358 $aSearches = $aNewSearches;
361 // Split query into phrases
362 // Commas are used to reduce the search space by indicating where phrases split
363 if (sizeof($aStructuredQuery) > 0)
365 $aPhrases = $aStructuredQuery;
366 $bStructuredPhrases = true;
370 $aPhrases = explode(',',$sQuery);
371 $bStructuredPhrases = false;
375 // Convert each phrase to standard form
376 // Create a list of standard words
377 // Get all 'sets' of words
378 // Generate a complete list of all
380 foreach($aPhrases as $iPhrase => $sPhrase)
382 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
383 if (PEAR::isError($aPhrase))
385 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
386 if (CONST_Debug) var_dump($aPhrase);
389 if (trim($aPhrase['string']))
391 $aPhrases[$iPhrase] = $aPhrase;
392 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
393 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
394 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
398 unset($aPhrases[$iPhrase]);
402 // reindex phrases - we make assumptions later on
403 $aPhraseTypes = array_keys($aPhrases);
404 $aPhrases = array_values($aPhrases);
406 if (sizeof($aTokens))
409 // Check which tokens we have, get the ID numbers
410 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
411 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
412 //$sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
413 //$sSQL .= ' group by word_token, word, class, type, country_code';
415 if (CONST_Debug) var_Dump($sSQL);
417 $aValidTokens = array();
418 if (sizeof($aTokens)) $aDatabaseWords = $oDB->getAll($sSQL);
419 else $aDatabaseWords = array();
420 if (PEAR::IsError($aDatabaseWords))
422 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
424 $aPossibleMainWordIDs = array();
425 $aWordFrequencyScores = array();
426 foreach($aDatabaseWords as $aToken)
428 // Very special case - require 2 letter country param to match the country code found
429 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
430 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
435 if (isset($aValidTokens[$aToken['word_token']]))
437 $aValidTokens[$aToken['word_token']][] = $aToken;
441 $aValidTokens[$aToken['word_token']] = array($aToken);
443 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
444 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
446 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
448 // Try and calculate GB postcodes we might be missing
449 foreach($aTokens as $sToken)
451 // Source of gb postcodes is now definitive - always use
452 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
454 if (substr($aData[1],-2,1) != ' ')
456 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
457 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
459 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
460 if ($aGBPostcodeLocation)
462 $aValidTokens[$sToken] = $aGBPostcodeLocation;
467 foreach($aTokens as $sToken)
469 // Unknown single word token with a number - assume it is a house number
470 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
472 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
476 // Any words that have failed completely?
479 // Start the search process
480 $aResultPlaceIDs = array();
483 Calculate all searches using aValidTokens i.e.
485 'Wodsworth Road, Sheffield' =>
489 0 1 (wodsworth)(road)
492 Score how good the search is so they can be ordered
494 foreach($aPhrases as $iPhrase => $sPhrase)
496 $aNewPhraseSearches = array();
497 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
498 else $sPhraseType = '';
500 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
502 $aWordsetSearches = $aSearches;
504 // Add all words from this wordset
505 foreach($aWordset as $iToken => $sToken)
507 //echo "<br><b>$sToken</b>";
508 $aNewWordsetSearches = array();
510 foreach($aWordsetSearches as $aCurrentSearch)
513 //var_dump($aCurrentSearch);
516 // If the token is valid
517 if (isset($aValidTokens[' '.$sToken]))
519 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
521 $aSearch = $aCurrentSearch;
522 $aSearch['iSearchRank']++;
523 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
525 if ($aSearch['sCountryCode'] === false)
527 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
528 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
529 // If reverse order is enabled, it may appear at the beginning as well.
530 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
531 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
533 $aSearch['iSearchRank'] += 5;
535 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
538 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
540 if ($aSearch['fLat'] === '')
542 $aSearch['fLat'] = $aSearchTerm['lat'];
543 $aSearch['fLon'] = $aSearchTerm['lon'];
544 $aSearch['fRadius'] = $aSearchTerm['radius'];
545 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
548 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
550 if ($aSearch['sHouseNumber'] === '')
552 $aSearch['sHouseNumber'] = $sToken;
553 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
555 // Fall back to not searching for this item (better than nothing)
556 $aSearch = $aCurrentSearch;
557 $aSearch['iSearchRank'] += 1;
558 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
562 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
564 if ($aSearch['sClass'] === '')
566 $aSearch['sOperator'] = $aSearchTerm['operator'];
567 $aSearch['sClass'] = $aSearchTerm['class'];
568 $aSearch['sType'] = $aSearchTerm['type'];
569 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
570 else $aSearch['sOperator'] = 'near'; // near = in for the moment
572 // Do we have a shortcut id?
573 if ($aSearch['sOperator'] == 'name')
575 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
576 if ($iAmenityID = $oDB->getOne($sSQL))
578 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
579 $aSearch['aName'][$iAmenityID] = $iAmenityID;
580 $aSearch['sClass'] = '';
581 $aSearch['sType'] = '';
584 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
587 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
589 if (sizeof($aSearch['aName']))
591 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
593 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
597 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
598 $aSearch['iSearchRank'] += 1000; // skip;
603 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
604 //$aSearch['iNamePhrase'] = $iPhrase;
606 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
610 if (isset($aValidTokens[$sToken]))
612 // Allow searching for a word - but at extra cost
613 foreach($aValidTokens[$sToken] as $aSearchTerm)
615 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
617 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
619 $aSearch = $aCurrentSearch;
620 $aSearch['iSearchRank'] += 1;
621 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
623 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
624 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
626 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
628 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
630 if (empty($aSearchTermToken['country_code'])
631 && empty($aSearchTermToken['lat'])
632 && empty($aSearchTermToken['class']))
634 $aSearch = $aCurrentSearch;
635 $aSearch['iSearchRank'] += 1;
636 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
637 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
643 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
644 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
648 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
650 $aSearch = $aCurrentSearch;
651 $aSearch['iSearchRank'] += 2;
652 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
653 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
654 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
656 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
657 $aSearch['iNamePhrase'] = $iPhrase;
658 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
665 // Allow skipping a word - but at EXTREAM cost
666 //$aSearch = $aCurrentSearch;
667 //$aSearch['iSearchRank']+=100;
668 //$aNewWordsetSearches[] = $aSearch;
672 usort($aNewWordsetSearches, 'bySearchRank');
673 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
675 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
677 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
678 usort($aNewPhraseSearches, 'bySearchRank');
680 $aSearchHash = array();
681 foreach($aNewPhraseSearches as $iSearch => $aSearch)
683 $sHash = serialize($aSearch);
684 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
685 else $aSearchHash[$sHash] = 1;
688 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
691 // Re-group the searches by their score, junk anything over 20 as just not worth trying
692 $aGroupedSearches = array();
693 foreach($aNewPhraseSearches as $aSearch)
695 if ($aSearch['iSearchRank'] < $iMaxRank)
697 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
698 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
701 ksort($aGroupedSearches);
704 $aSearches = array();
705 foreach($aGroupedSearches as $iScore => $aNewSearches)
707 $iSearchCount += sizeof($aNewSearches);
708 $aSearches = array_merge($aSearches, $aNewSearches);
709 if ($iSearchCount > 50) break;
712 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
718 // Re-group the searches by their score, junk anything over 20 as just not worth trying
719 $aGroupedSearches = array();
720 foreach($aSearches as $aSearch)
722 if ($aSearch['iSearchRank'] < $iMaxRank)
724 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
725 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
728 ksort($aGroupedSearches);
731 if (CONST_Debug) var_Dump($aGroupedSearches);
735 $aCopyGroupedSearches = $aGroupedSearches;
736 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
738 foreach($aSearches as $iSearch => $aSearch)
740 if (sizeof($aSearch['aAddress']))
742 $iReverseItem = array_pop($aSearch['aAddress']);
743 if (isset($aPossibleMainWordIDs[$iReverseItem]))
745 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
746 $aSearch['aName'] = array($iReverseItem);
747 $aGroupedSearches[$iGroup][] = $aSearch;
749 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
750 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
756 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
758 $aCopyGroupedSearches = $aGroupedSearches;
759 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
761 foreach($aSearches as $iSearch => $aSearch)
763 $aReductionsList = array($aSearch['aAddress']);
764 $iSearchRank = $aSearch['iSearchRank'];
765 while(sizeof($aReductionsList) > 0)
768 if ($iSearchRank > iMaxRank) break 3;
769 $aNewReductionsList = array();
770 foreach($aReductionsList as $aReductionsWordList)
772 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
774 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
775 $aReverseSearch = $aSearch;
776 $aSearch['aAddress'] = $aReductionsWordListResult;
777 $aSearch['iSearchRank'] = $iSearchRank;
778 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
779 if (sizeof($aReductionsWordListResult) > 0)
781 $aNewReductionsList[] = $aReductionsWordListResult;
785 $aReductionsList = $aNewReductionsList;
789 ksort($aGroupedSearches);
792 // Filter out duplicate searches
793 $aSearchHash = array();
794 foreach($aGroupedSearches as $iGroup => $aSearches)
796 foreach($aSearches as $iSearch => $aSearch)
798 $sHash = serialize($aSearch);
799 if (isset($aSearchHash[$sHash]))
801 unset($aGroupedSearches[$iGroup][$iSearch]);
802 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
806 $aSearchHash[$sHash] = 1;
811 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
815 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
818 foreach($aSearches as $aSearch)
822 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
823 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
826 // Must have a location term
827 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
829 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
831 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
833 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
834 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
835 $sSQL .= " order by st_area(geometry) desc limit 1";
836 if (CONST_Debug) var_dump($sSQL);
837 $aPlaceIDs = $oDB->getCol($sSQL);
842 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
843 if (!$aSearch['sClass']) continue;
844 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
845 if ($oDB->getOne($sSQL))
847 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
848 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
849 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
850 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
851 if (sizeof($aExcludePlaceIDs))
853 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
855 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
856 $sSQL .= " limit $iLimit";
857 if (CONST_Debug) var_dump($sSQL);
858 $aPlaceIDs = $oDB->getCol($sSQL);
860 // If excluded place IDs are given, it is fair to assume that
861 // there have been results in the small box, so no further
862 // expansion in that case.
863 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
865 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
866 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
867 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
868 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
869 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
870 $sSQL .= " limit $iLimit";
871 if (CONST_Debug) var_dump($sSQL);
872 $aPlaceIDs = $oDB->getCol($sSQL);
877 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
878 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
879 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
880 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
881 $sSQL .= " limit $iLimit";
882 if (CONST_Debug) var_dump($sSQL);
883 $aPlaceIDs = $oDB->getCol($sSQL);
889 $aPlaceIDs = array();
891 // First we need a position, either aName or fLat or both
895 // TODO: filter out the pointless search terms (2 letter name tokens and less)
896 // they might be right - but they are just too darned expensive to run
897 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
898 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
899 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
901 // For infrequent name terms disable index usage for address
902 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
903 sizeof($aSearch['aName']) == 1 &&
904 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
906 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
910 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
911 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
914 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
915 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
916 if ($aSearch['fLon'] && $aSearch['fLat'])
918 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
919 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
921 if (sizeof($aExcludePlaceIDs))
923 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
925 if ($sCountryCodesSQL)
927 $aTerms[] = "country_code in ($sCountryCodesSQL)";
930 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
931 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
933 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
934 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
935 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
936 $aOrder[] = "$sImportanceSQL DESC";
937 if (sizeof($aSearch['aFullNameAddress']))
938 $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
942 $sSQL = "select place_id";
943 $sSQL .= " from search_name";
944 $sSQL .= " where ".join(' and ',$aTerms);
945 $sSQL .= " order by ".join(', ',$aOrder);
946 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
947 $sSQL .= " limit 50";
948 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
951 $sSQL .= " limit ".$iLimit;
953 if (CONST_Debug) { var_dump($sSQL); }
954 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
955 if (PEAR::IsError($aViewBoxPlaceIDs))
957 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
959 //var_dump($aViewBoxPlaceIDs);
960 // Did we have an viewbox matches?
961 $aPlaceIDs = array();
962 $bViewBoxMatch = false;
963 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
965 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
966 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
967 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
968 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
969 $aPlaceIDs[] = $aViewBoxRow['place_id'];
972 //var_Dump($aPlaceIDs);
975 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
977 $aRoadPlaceIDs = $aPlaceIDs;
978 $sPlaceIDs = join(',',$aPlaceIDs);
980 // Now they are indexed look for a house attached to a street we found
981 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
982 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
983 if (sizeof($aExcludePlaceIDs))
985 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
987 $sSQL .= " limit $iLimit";
988 if (CONST_Debug) var_dump($sSQL);
989 $aPlaceIDs = $oDB->getCol($sSQL);
991 // If not try the aux fallback table
993 if (!sizeof($aPlaceIDs))
995 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
996 if (sizeof($aExcludePlaceIDs))
998 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1000 //$sSQL .= " limit $iLimit";
1001 if (CONST_Debug) var_dump($sSQL);
1002 $aPlaceIDs = $oDB->getCol($sSQL);
1006 if (!sizeof($aPlaceIDs))
1008 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1009 if (sizeof($aExcludePlaceIDs))
1011 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1013 //$sSQL .= " limit $iLimit";
1014 if (CONST_Debug) var_dump($sSQL);
1015 $aPlaceIDs = $oDB->getCol($sSQL);
1018 // Fallback to the road
1019 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1021 $aPlaceIDs = $aRoadPlaceIDs;
1026 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1028 $sPlaceIDs = join(',',$aPlaceIDs);
1029 $aClassPlaceIDs = array();
1031 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1033 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1034 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1035 $sSQL .= " and linked_place_id is null";
1036 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1037 $sSQL .= " order by rank_search asc limit $iLimit";
1038 if (CONST_Debug) var_dump($sSQL);
1039 $aClassPlaceIDs = $oDB->getCol($sSQL);
1042 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1044 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1045 $bCacheTable = $oDB->getOne($sSQL);
1047 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1049 if (CONST_Debug) var_dump($sSQL);
1050 $iMaxRank = ((int)$oDB->getOne($sSQL));
1052 // For state / country level searches the normal radius search doesn't work very well
1053 $sPlaceGeom = false;
1054 if ($iMaxRank < 9 && $bCacheTable)
1056 // Try and get a polygon to search in instead
1057 $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";
1058 if (CONST_Debug) var_dump($sSQL);
1059 $sPlaceGeom = $oDB->getOne($sSQL);
1069 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1070 if (CONST_Debug) var_dump($sSQL);
1071 $aPlaceIDs = $oDB->getCol($sSQL);
1072 $sPlaceIDs = join(',',$aPlaceIDs);
1075 if ($sPlaceIDs || $sPlaceGeom)
1081 // More efficient - can make the range bigger
1085 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1086 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1087 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1089 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1090 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1093 $sSQL .= ",placex as f where ";
1094 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1099 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1101 if (sizeof($aExcludePlaceIDs))
1103 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1105 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1106 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1107 if ($iOffset) $sSQL .= " offset $iOffset";
1108 $sSQL .= " limit $iLimit";
1109 if (CONST_Debug) var_dump($sSQL);
1110 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1114 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1117 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1118 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1120 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1121 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1122 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1123 if (sizeof($aExcludePlaceIDs))
1125 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1127 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1128 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1129 if ($iOffset) $sSQL .= " offset $iOffset";
1130 $sSQL .= " limit $iLimit";
1131 if (CONST_Debug) var_dump($sSQL);
1132 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1137 $aPlaceIDs = $aClassPlaceIDs;
1143 if (PEAR::IsError($aPlaceIDs))
1145 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1148 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1150 foreach($aPlaceIDs as $iPlaceID)
1152 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1154 if ($iQueryLoop > 20) break;
1158 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1159 if ($iGroupLoop > 4) break;
1160 if ($iQueryLoop > 30) break;
1163 // Did we find anything?
1164 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1166 //var_Dump($aResultPlaceIDs);exit;
1167 // Get the details for display (is this a redundant extra step?)
1168 $sPlaceIDs = join(',',$aResultPlaceIDs);
1169 $sImportanceSQL = '';
1170 if ($sViewboxSmallSQL) $sImportanceSQL .= " case when ST_Contains($sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
1171 if ($sViewboxLargeSQL) $sImportanceSQL .= " case when ST_Contains($sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
1173 $sOrderSQL = 'CASE ';
1174 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1176 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1178 $sOrderSQL .= ' ELSE 10000000 END';
1179 $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,";
1180 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1181 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1182 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1183 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1184 //$sSQL .= $sOrderSQL." as porder, ";
1185 $sSQL .= $sImportanceSQL."coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1186 $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, ";
1187 $sSQL .= "(extratags->'place') as extra_place ";
1188 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1189 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1190 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1192 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1193 $sSQL .= "and linked_place_id is null ";
1194 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1195 if (!$bDeDupe) $sSQL .= ",place_id";
1196 $sSQL .= ",langaddress ";
1197 $sSQL .= ",placename ";
1199 $sSQL .= ",extratags->'place' ";
1201 $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,";
1202 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1203 $sSQL .= "null as placename,";
1204 $sSQL .= "null as ref,";
1205 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1206 //$sSQL .= $sOrderSQL." as porder, ";
1207 $sSQL .= $sImportanceSQL."0.015 as importance, ";
1208 $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, ";
1209 $sSQL .= "null as extra_place ";
1210 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1211 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1212 $sSQL .= "group by place_id";
1213 if (!$bDeDupe) $sSQL .= ",place_id";
1216 $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,";
1217 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1218 $sSQL .= "null as placename,";
1219 $sSQL .= "null as ref,";
1220 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1221 //$sSQL .= $sOrderSQL." as porder, ";
1222 $sSQL .= $sImportanceSQL."0.01 as importance, ";
1223 $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, ";
1224 $sSQL .= "null as extra_place ";
1225 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1226 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1227 $sSQL .= "group by place_id";
1228 if (!$bDeDupe) $sSQL .= ",place_id";
1229 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1230 $sSQL .= "order by importance desc";
1231 //$sSQL .= "order by rank_search,rank_address,porder asc";
1233 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1234 $aSearchResults = $oDB->getAll($sSQL);
1235 //var_dump($sSQL,$aSearchResults);exit;
1237 if (PEAR::IsError($aSearchResults))
1239 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1242 } // end if ($sQuery)
1245 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1247 $iPlaceID = geocodeReverse((float)$_GET['nearlat'], (float)$_GET['nearlon']);
1251 $aResultPlaceIDs = array($iPlaceID);
1252 // TODO: this needs refactoring!
1254 // Get the details for display (is this a redundant extra step?)
1255 $sPlaceIDs = join(',',$aResultPlaceIDs);
1256 $sOrderSQL = 'CASE ';
1257 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1259 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1261 $sOrderSQL .= ' ELSE 10000000 END';
1262 $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,";
1263 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1264 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1265 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1266 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1267 //$sSQL .= $sOrderSQL." as porder, ";
1268 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1269 $sSQL .= "(extratags->'place') as extra_place ";
1270 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1271 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1272 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1274 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1275 if (!$bDeDupe) $sSQL .= ",place_id";
1276 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1277 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1278 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1279 $sSQL .= ",extratags->'place' ";
1281 $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,";
1282 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1283 $sSQL .= "null as placename,";
1284 $sSQL .= "null as ref,";
1285 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1286 //$sSQL .= $sOrderSQL." as porder, ";
1287 $sSQL .= "-0.15 as importance, ";
1288 $sSQL .= "null as extra_place ";
1289 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1290 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1291 $sSQL .= "group by place_id";
1292 if (!$bDeDupe) $sSQL .= ",place_id";
1295 $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,";
1296 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1297 $sSQL .= "null as placename,";
1298 $sSQL .= "null as ref,";
1299 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1300 //$sSQL .= $sOrderSQL." as porder, ";
1301 $sSQL .= "-0.10 as importance, ";
1302 $sSQL .= "null as extra_place ";
1303 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1304 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1305 $sSQL .= "group by place_id";
1307 if (!$bDeDupe) $sSQL .= ",place_id";
1308 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1309 $sSQL .= "order by importance desc";
1310 //$sSQL .= "order by rank_search,rank_address,porder asc";
1311 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1312 $aSearchResults = $oDB->getAll($sSQL);
1313 //var_dump($sSQL,$aSearchResults);exit;
1315 if (PEAR::IsError($aSearchResults))
1317 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1322 $aSearchResults = array();
1328 $sSearchResult = '';
1329 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1331 $sSearchResult = 'No Results Found';
1333 //var_Dump($aSearchResults);
1335 $aClassType = getClassTypesWithImportance();
1336 $aRecheckWords = preg_split('/\b/u',$sQuery);
1337 foreach($aRecheckWords as $i => $sWord)
1339 if (!$sWord) unset($aRecheckWords[$i]);
1341 foreach($aSearchResults as $iResNum => $aResult)
1343 if (CONST_Search_AreaPolygons)
1345 // Get the bounding box and outline polygon
1346 $sSQL = "select place_id,numfeatures,area,outline,";
1347 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1348 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1349 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1351 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1352 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1353 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1354 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1355 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1356 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1357 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1358 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1359 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1360 $aPointPolygon = $oDB->getRow($sSQL);
1361 if (PEAR::IsError($aPointPolygon))
1363 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1365 if ($aPointPolygon['place_id'])
1367 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1368 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1369 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1370 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1372 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1374 $aResult['lat'] = $aPointPolygon['centrelat'];
1375 $aResult['lon'] = $aPointPolygon['centrelon'];
1379 // Translate geometary string to point array
1380 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1382 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1384 /*elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1386 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1388 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1391 $iSteps = ($fRadius * 40000)^2;
1392 $fStepSize = (2*pi())/$iSteps;
1393 $aPolyPoints = array();
1394 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1396 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1398 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1399 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1400 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1401 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1405 // Output data suitable for display (points and a bounding box)
1406 if ($bShowPolygons && isset($aPolyPoints))
1408 $aResult['aPolyPoints'] = array();
1409 foreach($aPolyPoints as $aPoint)
1411 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1414 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1418 if ($aResult['extra_place'] == 'city')
1420 $aResult['class'] = 'place';
1421 $aResult['type'] = 'city';
1422 $aResult['rank_search'] = 16;
1425 if (!isset($aResult['aBoundingBox']))
1428 $fDiameter = 0.0001;
1430 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1431 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1433 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1435 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1436 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1438 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1440 $fRadius = $fDiameter / 2;
1442 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1443 $fStepSize = (2*pi())/$iSteps;
1444 $aPolyPoints = array();
1445 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1447 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1449 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1450 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1451 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1452 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1454 // Output data suitable for display (points and a bounding box)
1457 $aResult['aPolyPoints'] = array();
1458 foreach($aPolyPoints as $aPoint)
1460 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1463 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1466 // Is there an icon set for this type of result?
1467 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1468 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1470 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1473 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1474 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1476 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1479 if ($bShowAddressDetails)
1481 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1482 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1484 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1487 //var_dump($aResult['address']);
1491 // Adjust importance for the number of exact string matches in the result
1492 $aResult['importance'] = max(0.001,$aResult['importance']);
1494 $sAddress = $aResult['langaddress'];
1495 foreach($aRecheckWords as $i => $sWord)
1497 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1500 $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
1502 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1504 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1505 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1507 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1509 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1510 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1512 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1516 $aResult['importance'] = 1000000000000000;
1519 $aResult['name'] = $aResult['langaddress'];
1520 $aResult['foundorder'] = -$aResult['addressimportance'];
1521 $aSearchResults[$iResNum] = $aResult;
1523 uasort($aSearchResults, 'byImportance');
1525 $aOSMIDDone = array();
1526 $aClassTypeNameDone = array();
1527 $aToFilter = $aSearchResults;
1528 $aSearchResults = array();
1531 foreach($aToFilter as $iResNum => $aResult)
1533 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1534 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1537 $fLat = $aResult['lat'];
1538 $fLon = $aResult['lon'];
1539 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1542 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1543 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1545 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1546 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1547 $aSearchResults[] = $aResult;
1550 // Absolute limit on number of results
1551 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1554 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1556 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1558 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1563 logEnd($oDB, $hLog, sizeof($aToFilter));
1565 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1566 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1567 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1568 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1569 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1570 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1571 $sMoreURL .= '&q='.urlencode($sQuery);
1573 if (CONST_Debug) exit;
1575 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');