2 @define('CONST_ConnectionBucket_PageType', 'Search');
4 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
5 require_once(CONST_BasePath.'/lib/log.php');
7 ini_set('memory_limit', '200M');
12 $fLat = CONST_Default_Lat;
13 $fLon = CONST_Default_Lon;
14 $iZoom = CONST_Default_Zoom;
15 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
16 $sOutputFormat = 'html';
17 $aSearchResults = array();
18 $aExcludePlaceIDs = array();
19 $sCountryCodesSQL = false;
20 $sSuggestion = $sSuggestionURL = false;
21 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
22 $bReverseInPlan = false;
23 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
24 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
26 if ($iFinalLimit > 50) $iFinalLimit = 50;
27 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
29 $iMaxAddressRank = 30;
30 $sAllowedTypesSQLList = false;
33 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
35 $sOutputFormat = $_GET['format'];
38 // Show / use polygons
39 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
40 if ($sOutputFormat == 'html') {
41 $bAsText = $bShowPolygons;
42 $bShowPolygons = false;
47 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
48 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
49 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
50 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
51 if ((($bShowPolygons?1:0)
56 ) > CONST_PolygonOutput_MaximumTypes) {
57 if (CONST_PolygonOutput_MaximumTypes) {
58 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
60 userError("Polygon output is disabled");
66 // Show address breakdown
67 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
70 $aLangPrefOrder = getPreferredLanguages();
71 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
72 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
73 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
75 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
77 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
79 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
81 $iExcludedPlaceID = (int)$iExcludedPlaceID;
82 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
86 // Only certain ranks of feature
87 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
89 if (isset($_GET['featuretype']))
91 switch($_GET['featuretype'])
94 $iMinAddressRank = $iMaxAddressRank = 4;
97 $iMinAddressRank = $iMaxAddressRank = 8;
100 $iMinAddressRank = 14;
101 $iMaxAddressRank = 16;
104 $iMinAddressRank = 8;
105 $iMaxAddressRank = 20;
110 if (isset($_GET['countrycodes']))
112 $aCountryCodes = array();
113 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
115 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
117 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
120 $sCountryCodesSQL = join(',', $aCountryCodes);
124 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
125 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
127 $sQuery = substr($_SERVER['PATH_INFO'], 1);
129 // reverse order of '/' separated string
130 $aPhrases = explode('/', $sQuery);
131 $aPhrases = array_reverse($aPhrases);
132 $sQuery = join(', ',$aPhrases);
135 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
137 if (!isset($_GET[$sKey])) return false;
138 $sValue = trim($_GET[$sKey]);
139 if (!$sValue) return false;
140 $aStructuredQuery[$sKey] = $sValue;
141 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
142 $iMinAddressRank = $iNewMinAddressRank;
143 $iMaxAddressRank = $iNewMaxAddressRank;
149 $aStructuredOptions = array(
150 array('amenity', 26, 30),
151 array('street', 26, 30),
152 array('city', 14, 24),
153 array('county', 9, 13),
154 array('state', 8, 8),
155 array('country', 4, 4),
156 array('postalcode', 16, 25),
158 $aStructuredQuery = array();
159 $sAllowedTypesSQLList = '';
160 foreach($aStructuredOptions as $aStructuredOption)
162 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
164 if (sizeof($aStructuredQuery) > 0) {
165 $sQuery = join(', ', $aStructuredQuery);
166 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
171 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
173 // Hack to make it handle "new york, ny" (and variants) correctly
174 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
175 if (isset($aLangPrefOrder['name:en']))
177 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
178 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
179 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
182 // If we have a view box create the SQL
183 // Small is the actual view box, Large is double (on each axis) that
184 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
185 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
187 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
188 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
190 if (isset($_GET['viewbox']) && $_GET['viewbox'])
192 $aCoOrdinates = explode(',',$_GET['viewbox']);
193 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
194 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
195 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
196 $aCoOrdinates[0] += $fHeight;
197 $aCoOrdinates[2] -= $fHeight;
198 $aCoOrdinates[1] += $fWidth;
199 $aCoOrdinates[3] -= $fWidth;
200 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
202 $bBoundingBoxSearch = false;
204 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
206 $aPoints = explode(',',$_GET['route']);
207 if (sizeof($aPoints) % 2 != 0)
209 userError("Uneven number of points");
212 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
214 foreach($aPoints as $i => $fPoint)
218 if ($i != 1) $sViewboxCentreSQL .= ",";
219 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
223 $fPrevCoord = (float)$fPoint;
226 $sViewboxCentreSQL .= ")'::geometry,4326)";
228 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
229 $sViewboxSmallSQL = $oDB->getOne($sSQL);
230 if (PEAR::isError($sViewboxSmallSQL))
232 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
234 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
236 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
237 $sViewboxLargeSQL = $oDB->getOne($sSQL);
238 if (PEAR::isError($sViewboxLargeSQL))
240 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
242 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
243 $bBoundingBoxSearch = true;
246 // Do we have anything that looks like a lat/lon pair?
247 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
249 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
250 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
251 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
253 $_GET['nearlat'] = $fQueryLat;
254 $_GET['nearlon'] = $fQueryLon;
255 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
258 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
260 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
261 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
262 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
264 $_GET['nearlat'] = $fQueryLat;
265 $_GET['nearlon'] = $fQueryLon;
266 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
269 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
271 $fQueryLat = $aData[2];
272 $fQueryLon = $aData[3];
273 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
275 $_GET['nearlat'] = $fQueryLat;
276 $_GET['nearlon'] = $fQueryLon;
277 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
281 if ($sQuery || $aStructuredQuery)
283 // Start with a blank search
285 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
286 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
289 $sNearPointSQL = false;
290 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
292 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
293 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
294 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
295 $aSearches[0]['fRadius'] = 0.1;
298 $bSpecialTerms = false;
299 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
300 $aSpecialTerms = array();
301 foreach($aSpecialTermsRaw as $aSpecialTerm)
303 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
304 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
307 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
308 $aSpecialTerms = array();
309 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
311 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
312 unset($aStructuredQuery['amenity']);
314 foreach($aSpecialTermsRaw as $aSpecialTerm)
316 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
317 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
318 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
319 $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';
320 if (CONST_Debug) var_Dump($sSQL);
321 $aSearchWords = $oDB->getAll($sSQL);
322 $aNewSearches = array();
323 foreach($aSearches as $aSearch)
325 foreach($aSearchWords as $aSearchTerm)
327 $aNewSearch = $aSearch;
328 if ($aSearchTerm['country_code'])
330 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
331 $aNewSearches[] = $aNewSearch;
332 $bSpecialTerms = true;
334 if ($aSearchTerm['class'])
336 $aNewSearch['sClass'] = $aSearchTerm['class'];
337 $aNewSearch['sType'] = $aSearchTerm['type'];
338 $aNewSearches[] = $aNewSearch;
339 $bSpecialTerms = true;
343 $aSearches = $aNewSearches;
346 // Split query into phrases
347 // Commas are used to reduce the search space by indicating where phrases split
348 if (sizeof($aStructuredQuery) > 0)
350 $aPhrases = $aStructuredQuery;
351 $bStructuredPhrases = true;
355 $aPhrases = explode(',',$sQuery);
356 $bStructuredPhrases = false;
360 // Convert each phrase to standard form
361 // Create a list of standard words
362 // Get all 'sets' of words
363 // Generate a complete list of all
365 foreach($aPhrases as $iPhrase => $sPhrase)
367 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
368 if (PEAR::isError($aPhrase))
370 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
371 if (CONST_Debug) var_dump($aPhrase);
374 if (trim($aPhrase['string']))
376 $aPhrases[$iPhrase] = $aPhrase;
377 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
378 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
379 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
383 unset($aPhrases[$iPhrase]);
387 // reindex phrases - we make assumptions later on
388 $aPhraseTypes = array_keys($aPhrases);
389 $aPhrases = array_values($aPhrases);
391 if (sizeof($aTokens))
394 // Check which tokens we have, get the ID numbers
395 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator, search_name_count';
396 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
397 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
398 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
400 if (CONST_Debug) var_Dump($sSQL);
402 $aValidTokens = array();
403 if (sizeof($aTokens))
404 $aDatabaseWords = $oDB->getAll($sSQL);
406 $aDatabaseWords = array();
407 if (PEAR::IsError($aDatabaseWords))
409 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
411 $aPossibleMainWordIDs = array();
412 foreach($aDatabaseWords as $aToken)
414 if (isset($aValidTokens[$aToken['word_token']]))
416 $aValidTokens[$aToken['word_token']][] = $aToken;
420 $aValidTokens[$aToken['word_token']] = array($aToken);
422 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1 + $aToken['search_name_count'];
424 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
426 $aSuggestion = array();
427 $bSuggestion = false;
428 if (CONST_Suggestions_Enabled)
430 foreach($aPhrases as $iPhrase => $aPhrase)
432 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
434 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
435 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
436 $aRow = $aSuggestionWords[0];
437 if ($aRow && $aRow['word'])
439 $aSuggestion[] = $aRow['word'];
444 $aSuggestion[] = $aPhrase['string'];
449 $aSuggestion[] = $aPhrase['string'];
453 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
455 // Try and calculate GB postcodes we might be missing
456 foreach($aTokens as $sToken)
458 // Source of gb postcodes is now definitive - always use
459 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
461 if (substr($aData[1],-2,1) != ' ')
463 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
464 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
466 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
467 if ($aGBPostcodeLocation)
469 $aValidTokens[$sToken] = $aGBPostcodeLocation;
474 foreach($aTokens as $sToken)
476 // Unknown single word token with a number - assume it is a house number
477 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
479 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
483 // Any words that have failed completely?
486 // Start the search process
487 $aResultPlaceIDs = array();
490 Calculate all searches using aValidTokens i.e.
492 'Wodsworth Road, Sheffield' =>
496 0 1 (wodsworth)(road)
499 Score how good the search is so they can be ordered
501 foreach($aPhrases as $iPhrase => $sPhrase)
503 $aNewPhraseSearches = array();
504 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
505 else $sPhraseType = '';
507 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
509 $aWordsetSearches = $aSearches;
511 // Add all words from this wordset
512 foreach($aWordset as $iToken => $sToken)
514 //echo "<br><b>$sToken</b>";
515 $aNewWordsetSearches = array();
517 foreach($aWordsetSearches as $aCurrentSearch)
520 //var_dump($aCurrentSearch);
523 // If the token is valid
524 if (isset($aValidTokens[' '.$sToken]))
526 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
528 $aSearch = $aCurrentSearch;
529 $aSearch['iSearchRank']++;
530 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
532 if ($aSearch['sCountryCode'] === false)
534 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
535 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
536 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
537 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
540 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
542 if ($aSearch['fLat'] === '')
544 $aSearch['fLat'] = $aSearchTerm['lat'];
545 $aSearch['fLon'] = $aSearchTerm['lon'];
546 $aSearch['fRadius'] = $aSearchTerm['radius'];
547 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
550 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
552 if ($aSearch['sHouseNumber'] === '')
554 $aSearch['sHouseNumber'] = $sToken;
555 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
557 // Fall back to not searching for this item (better than nothing)
558 $aSearch = $aCurrentSearch;
559 $aSearch['iSearchRank'] += 1;
560 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
564 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
566 if ($aSearch['sClass'] === '')
568 $aSearch['sOperator'] = $aSearchTerm['operator'];
569 $aSearch['sClass'] = $aSearchTerm['class'];
570 $aSearch['sType'] = $aSearchTerm['type'];
571 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
572 else $aSearch['sOperator'] = 'near'; // near = in for the moment
574 // Do we have a shortcut id?
575 if ($aSearch['sOperator'] == 'name')
577 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
578 if ($iAmenityID = $oDB->getOne($sSQL))
580 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
581 $aSearch['aName'][$iAmenityID] = $iAmenityID;
582 $aSearch['sClass'] = '';
583 $aSearch['sType'] = '';
586 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
589 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
591 if (sizeof($aSearch['aName']))
593 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
595 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
599 $aSearch['iSearchRank'] += 1000; // skip;
604 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
605 // $aSearch['iNamePhrase'] = $iPhrase;
607 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
611 if (isset($aValidTokens[$sToken]))
613 // Allow searching for a word - but at extra cost
614 foreach($aValidTokens[$sToken] as $aSearchTerm)
616 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
618 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
620 $aSearch = $aCurrentSearch;
621 $aSearch['iSearchRank'] += 1;
622 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
623 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
626 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
628 $aSearch = $aCurrentSearch;
629 $aSearch['iSearchRank'] += 2;
630 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
631 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
632 $aSearch['iNamePhrase'] = $iPhrase;
633 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
640 // Allow skipping a word - but at EXTREAM cost
641 //$aSearch = $aCurrentSearch;
642 //$aSearch['iSearchRank']+=100;
643 //$aNewWordsetSearches[] = $aSearch;
647 usort($aNewWordsetSearches, 'bySearchRank');
648 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
650 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
652 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
653 usort($aNewPhraseSearches, 'bySearchRank');
655 $aSearchHash = array();
656 foreach($aNewPhraseSearches as $iSearch => $aSearch)
658 $sHash = serialize($aSearch);
659 if (isset($aSearchHash[$sHash]))
661 unset($aNewPhraseSearches[$iSearch]);
665 $aSearchHash[$sHash] = 1;
669 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
672 // Re-group the searches by their score, junk anything over 20 as just not worth trying
673 $aGroupedSearches = array();
674 foreach($aNewPhraseSearches as $aSearch)
676 if ($aSearch['iSearchRank'] < $iMaxRank)
678 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
679 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
682 ksort($aGroupedSearches);
685 $aSearches = array();
686 foreach($aGroupedSearches as $iScore => $aNewSearches)
688 $iSearchCount += sizeof($aNewSearches);
689 $aSearches = array_merge($aSearches, $aNewSearches);
690 if ($iSearchCount > 50) break;
693 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
699 // Re-group the searches by their score, junk anything over 20 as just not worth trying
700 $aGroupedSearches = array();
701 foreach($aSearches as $aSearch)
703 if ($aSearch['iSearchRank'] < $iMaxRank)
705 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
706 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
709 ksort($aGroupedSearches);
712 if (CONST_Debug) var_Dump($aGroupedSearches);
716 $aCopyGroupedSearches = $aGroupedSearches;
717 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
719 foreach($aSearches as $iSearch => $aSearch)
721 if (sizeof($aSearch['aAddress']))
723 $iReverseItem = array_pop($aSearch['aAddress']);
724 if (isset($aPossibleMainWordIDs[$iReverseItem]))
726 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
727 $aSearch['aName'] = array($iReverseItem);
728 $aGroupedSearches[$iGroup][] = $aSearch;
730 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
731 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
737 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
739 $aCopyGroupedSearches = $aGroupedSearches;
740 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
742 foreach($aSearches as $iSearch => $aSearch)
744 $aReductionsList = array($aSearch['aAddress']);
745 $iSearchRank = $aSearch['iSearchRank'];
746 while(sizeof($aReductionsList) > 0)
749 if ($iSearchRank > iMaxRank) break 3;
750 $aNewReductionsList = array();
751 foreach($aReductionsList as $aReductionsWordList)
753 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
755 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
756 $aReverseSearch = $aSearch;
757 $aSearch['aAddress'] = $aReductionsWordListResult;
758 $aSearch['iSearchRank'] = $iSearchRank;
759 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
760 if (sizeof($aReductionsWordListResult) > 0)
762 $aNewReductionsList[] = $aReductionsWordListResult;
766 $aReductionsList = $aNewReductionsList;
770 ksort($aGroupedSearches);
773 // Filter out duplicate searches
774 $aSearchHash = array();
775 foreach($aGroupedSearches as $iGroup => $aSearches)
777 foreach($aSearches as $iSearch => $aSearch)
779 $sHash = serialize($aSearch);
780 if (isset($aSearchHash[$sHash]))
782 unset($aGroupedSearches[$iGroup][$iSearch]);
783 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
787 $aSearchHash[$sHash] = 1;
792 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
796 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
799 foreach($aSearches as $aSearch)
803 // Must have a location term
804 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
806 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
808 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
810 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
811 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
812 $sSQL .= " order by st_area(geometry) desc limit 1";
813 $aPlaceIDs = $oDB->getCol($sSQL);
818 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
819 if (!$aSearch['sClass']) continue;
820 if (CONST_Debug) var_dump('<hr>',$aSearch);
821 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
822 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
823 if ($oDB->getOne($sSQL))
825 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
826 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
827 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
828 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
829 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
830 $sSQL .= " limit $iLimit";
831 if (CONST_Debug) var_dump($sSQL);
832 $aPlaceIDs = $oDB->getCol($sSQL);
834 if (!sizeof($aPlaceIDs))
836 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
837 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
838 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
839 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
840 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
841 $sSQL .= " limit $iLimit";
842 if (CONST_Debug) var_dump($sSQL);
843 $aPlaceIDs = $oDB->getCol($sSQL);
848 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
849 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
850 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
851 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
852 $sSQL .= " limit $iLimit";
853 if (CONST_Debug) var_dump($sSQL);
854 $aPlaceIDs = $oDB->getCol($sSQL);
860 if (CONST_Debug) var_dump('<hr>',$aSearch);
861 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
862 $aPlaceIDs = array();
864 // First we need a position, either aName or fLat or both
868 // TODO: filter out the pointless search terms (2 letter name tokens and less)
869 // they might be right - but they are just too darned expensive to run
870 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
871 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
873 // For infrequent name terms disable index usage for address
874 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
875 sizeof($aSearch['aName']) == 1 &&
876 $aPossibleMainWordIDs[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
878 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
882 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
885 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
886 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
887 if ($aSearch['fLon'] && $aSearch['fLat'])
889 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
890 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
892 if (sizeof($aExcludePlaceIDs))
894 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
896 if ($sCountryCodesSQL)
898 $aTerms[] = "country_code in ($sCountryCodesSQL)";
901 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
902 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
904 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end';
906 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
907 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
908 $aOrder[] = "$sImportanceSQL DESC";
912 $sSQL = "select place_id";
913 $sSQL .= " from search_name";
914 $sSQL .= " where ".join(' and ',$aTerms);
915 $sSQL .= " order by ".join(', ',$aOrder);
916 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
917 $sSQL .= " limit 50";
918 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
921 $sSQL .= " limit ".$iLimit;
923 if (CONST_Debug) { var_dump($sSQL); }
924 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
925 if (PEAR::IsError($aViewBoxPlaceIDs))
927 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
929 //var_dump($aViewBoxPlaceIDs);
930 // Did we have an viewbox matches?
931 $aPlaceIDs = array();
932 $bViewBoxMatch = false;
933 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
935 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
936 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
937 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
938 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
939 $aPlaceIDs[] = $aViewBoxRow['place_id'];
942 //var_Dump($aPlaceIDs);
945 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
947 $aRoadPlaceIDs = $aPlaceIDs;
948 $sPlaceIDs = join(',',$aPlaceIDs);
950 // Now they are indexed look for a house attached to a street we found
951 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
952 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
953 if (sizeof($aExcludePlaceIDs))
955 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
957 $sSQL .= " limit $iLimit";
958 if (CONST_Debug) var_dump($sSQL);
959 $aPlaceIDs = $oDB->getCol($sSQL);
961 // If not try the aux fallback table
962 if (!sizeof($aPlaceIDs))
964 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
965 if (sizeof($aExcludePlaceIDs))
967 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
969 // $sSQL .= " limit $iLimit";
970 if (CONST_Debug) var_dump($sSQL);
971 $aPlaceIDs = $oDB->getCol($sSQL);
974 if (!sizeof($aPlaceIDs))
976 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
977 if (sizeof($aExcludePlaceIDs))
979 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
981 // $sSQL .= " limit $iLimit";
982 if (CONST_Debug) var_dump($sSQL);
983 $aPlaceIDs = $oDB->getCol($sSQL);
986 // Fallback to the road
987 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
989 $aPlaceIDs = $aRoadPlaceIDs;
994 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
996 $sPlaceIDs = join(',',$aPlaceIDs);
998 $aClassPlaceIDs = array();
1000 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1002 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1003 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1004 $sSQL .= " and linked_place_id is null";
1005 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
1006 $sSQL .= " order by rank_search asc limit $iLimit";
1007 if (CONST_Debug) var_dump($sSQL);
1008 $aClassPlaceIDs = $oDB->getCol($sSQL);
1011 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1013 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1014 $bCacheTable = $oDB->getOne($sSQL);
1016 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1018 if (CONST_Debug) var_dump($sSQL);
1019 $iMaxRank = ((int)$oDB->getOne($sSQL));
1021 // For state / country level searches the normal radius search doesn't work very well
1022 $sPlaceGeom = false;
1023 if ($iMaxRank < 9 && $bCacheTable)
1025 // Try and get a polygon to search in instead
1026 $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";
1027 if (CONST_Debug) var_dump($sSQL);
1028 $sPlaceGeom = $oDB->getOne($sSQL);
1038 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1039 if (CONST_Debug) var_dump($sSQL);
1040 $aPlaceIDs = $oDB->getCol($sSQL);
1041 $sPlaceIDs = join(',',$aPlaceIDs);
1044 if ($sPlaceIDs || $sPlaceGeom)
1050 // More efficient - can make the range bigger
1054 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1055 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1056 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1058 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1059 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1062 $sSQL .= ",placex as f where ";
1063 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1068 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1070 if (sizeof($aExcludePlaceIDs))
1072 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1074 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1075 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1076 if ($iOffset) $sSQL .= " offset $iOffset";
1077 $sSQL .= " limit $iLimit";
1078 if (CONST_Debug) var_dump($sSQL);
1079 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1083 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1086 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1087 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1089 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1090 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1091 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1092 if (sizeof($aExcludePlaceIDs))
1094 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1096 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1097 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1098 if ($iOffset) $sSQL .= " offset $iOffset";
1099 $sSQL .= " limit $iLimit";
1100 if (CONST_Debug) var_dump($sSQL);
1101 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1106 $aPlaceIDs = $aClassPlaceIDs;
1112 if (PEAR::IsError($aPlaceIDs))
1114 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1117 if (CONST_Debug) var_Dump($aPlaceIDs);
1119 foreach($aPlaceIDs as $iPlaceID)
1121 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1123 if ($iQueryLoop > 20) break;
1127 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1128 if ($iGroupLoop > 4) break;
1129 if ($iQueryLoop > 30) break;
1132 // Did we find anything?
1133 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1135 //var_Dump($aResultPlaceIDs);exit;
1136 // Get the details for display (is this a redundant extra step?)
1137 $sPlaceIDs = join(',',$aResultPlaceIDs);
1138 $sOrderSQL = 'CASE ';
1139 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1141 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1143 $sOrderSQL .= ' ELSE 10000000 END';
1144 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1145 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1146 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1147 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1148 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1149 // $sSQL .= $sOrderSQL." as porder, ";
1150 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1151 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1152 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1153 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1154 $sSQL .= "and linked_place_id is null ";
1155 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1156 if (!$bDeDupe) $sSQL .= ",place_id";
1157 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1158 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1159 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1161 $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,";
1162 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1163 $sSQL .= "null as placename,";
1164 $sSQL .= "null as ref,";
1165 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1166 // $sSQL .= $sOrderSQL." as porder, ";
1167 $sSQL .= "-0.15 as importance ";
1168 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1169 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1170 $sSQL .= "group by place_id";
1171 if (!$bDeDupe) $sSQL .= ",place_id";
1173 $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,";
1174 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1175 $sSQL .= "null as placename,";
1176 $sSQL .= "null as ref,";
1177 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1178 // $sSQL .= $sOrderSQL." as porder, ";
1179 $sSQL .= "-0.10 as importance ";
1180 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1181 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1182 $sSQL .= "group by place_id";
1183 if (!$bDeDupe) $sSQL .= ",place_id";
1184 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1185 $sSQL .= "order by importance desc";
1186 // $sSQL .= "order by rank_search,rank_address,porder asc";
1187 if (CONST_Debug) var_dump('<hr>',$sSQL);
1188 $aSearchResults = $oDB->getAll($sSQL);
1189 //var_dump($sSQL,$aSearchResults);exit;
1191 if (PEAR::IsError($aSearchResults))
1193 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1196 } // end if ($sQuery)
1199 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1201 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1202 $aResultPlaceIDs = array($iPlaceID);
1204 // TODO: this needs refactoring!
1206 // Get the details for display (is this a redundant extra step?)
1207 $sPlaceIDs = join(',',$aResultPlaceIDs);
1208 $sOrderSQL = 'CASE ';
1209 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1211 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1213 $sOrderSQL .= ' ELSE 10000000 END';
1214 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1215 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1216 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1217 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1218 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1219 // $sSQL .= $sOrderSQL." as porder, ";
1220 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1221 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1222 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1223 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1224 if (!$bDeDupe) $sSQL .= ",place_id";
1225 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1226 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1227 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1229 $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1230 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1231 $sSQL .= "null as placename,";
1232 $sSQL .= "null as ref,";
1233 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1234 // $sSQL .= $sOrderSQL." as porder, ";
1235 $sSQL .= "-0.15 as importance ";
1236 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1237 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1238 $sSQL .= "group by place_id";
1239 if (!$bDeDupe) $sSQL .= ",place_id";
1241 $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,";
1242 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1243 $sSQL .= "null as placename,";
1244 $sSQL .= "null as ref,";
1245 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1246 // $sSQL .= $sOrderSQL." as porder, ";
1247 $sSQL .= "-0.10 as importance ";
1248 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1249 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1250 $sSQL .= "group by place_id";
1251 if (!$bDeDupe) $sSQL .= ",place_id";
1252 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1253 $sSQL .= "order by importance desc";
1254 // $sSQL .= "order by rank_search,rank_address,porder asc";
1255 if (CONST_Debug) var_dump('<hr>',$sSQL);
1256 $aSearchResults = $oDB->getAll($sSQL);
1257 //var_dump($sSQL,$aSearchResults);exit;
1259 if (PEAR::IsError($aSearchResults))
1261 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1267 $sSearchResult = '';
1268 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1270 $sSearchResult = 'No Results Found';
1272 //var_Dump($aSearchResults);
1274 $aClassType = getClassTypesWithImportance();
1275 $aRecheckWords = preg_split('/\b/',$sQuery);
1276 foreach($aRecheckWords as $i => $sWord)
1278 if (!$sWord) unset($aRecheckWords[$i]);
1280 foreach($aSearchResults as $iResNum => $aResult)
1282 if (CONST_Search_AreaPolygons)
1284 // Get the bounding box and outline polygon
1285 $sSQL = "select place_id,numfeatures,area,outline,";
1286 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1287 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1288 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1290 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1291 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1292 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1293 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1294 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1295 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1296 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1297 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1298 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1299 $aPointPolygon = $oDB->getRow($sSQL);
1300 if (PEAR::IsError($aPointPolygon))
1302 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1304 if ($aPointPolygon['place_id'])
1306 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1307 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1308 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1309 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1311 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1312 $aResult['lat'] = $aPointPolygon['centrelat'];
1313 $aResult['lon'] = $aPointPolygon['centrelon'];
1317 // Translate geometary string to point array
1318 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1320 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1322 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1324 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1326 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1329 $iSteps = ($fRadius * 40000)^2;
1330 $fStepSize = (2*pi())/$iSteps;
1331 $aPolyPoints = array();
1332 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1334 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1336 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1337 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1338 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1339 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1343 // Output data suitable for display (points and a bounding box)
1344 if ($bShowPolygons && isset($aPolyPoints))
1346 $aResult['aPolyPoints'] = array();
1347 foreach($aPolyPoints as $aPoint)
1349 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1352 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1356 if (!isset($aResult['aBoundingBox']))
1359 $fDiameter = 0.0001;
1361 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1362 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1364 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1366 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1367 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1369 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1371 $fRadius = $fDiameter / 2;
1373 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1374 $fStepSize = (2*pi())/$iSteps;
1375 $aPolyPoints = array();
1376 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1378 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1380 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1381 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1382 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1383 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1385 // Output data suitable for display (points and a bounding box)
1388 $aResult['aPolyPoints'] = array();
1389 foreach($aPolyPoints as $aPoint)
1391 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1394 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1397 // Is there an icon set for this type of result?
1398 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1399 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1401 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1404 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1405 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1407 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1410 if ($bShowAddressDetails)
1412 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1413 //var_dump($aResult['address']);
1417 // Adjust importance for the number of exact string matches in the result
1418 $aResult['importance'] = max(0.001,$aResult['importance']);
1420 $sAddress = $aResult['langaddress'];
1421 foreach($aRecheckWords as $i => $sWord)
1423 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1425 $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
1427 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1429 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1430 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1432 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1434 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1435 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1437 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1441 $aResult['importance'] = 1000000000000000;
1444 $aResult['name'] = $aResult['langaddress'];
1445 $aResult['foundorder'] = $iResNum;
1446 $aSearchResults[$iResNum] = $aResult;
1448 uasort($aSearchResults, 'byImportance');
1450 $aOSMIDDone = array();
1451 $aClassTypeNameDone = array();
1452 $aToFilter = $aSearchResults;
1453 $aSearchResults = array();
1456 foreach($aToFilter as $iResNum => $aResult)
1458 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1459 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1462 $fLat = $aResult['lat'];
1463 $fLon = $aResult['lon'];
1464 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1467 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1468 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1470 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1471 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1472 $aSearchResults[] = $aResult;
1475 // Absolute limit on number of results
1476 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1479 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1481 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1483 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1488 logEnd($oDB, $hLog, sizeof($aToFilter));
1490 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1491 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1492 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1493 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1494 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1495 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1498 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1500 $sMoreURL .= '&q='.urlencode($sQuery);
1502 if (CONST_Debug) exit;
1504 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');