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';
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;
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') && $aSearchTerm['country_code'] !== null && $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']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
872 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
873 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
874 if ($aSearch['fLon'] && $aSearch['fLat'])
876 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
877 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
879 if (sizeof($aExcludePlaceIDs))
881 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
883 if ($sCountryCodesSQL)
885 $aTerms[] = "country_code in ($sCountryCodesSQL)";
888 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
889 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
891 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end';
893 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
894 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
895 $aOrder[] = "$sImportanceSQL DESC";
899 $sSQL = "select place_id";
900 $sSQL .= " from search_name";
901 $sSQL .= " where ".join(' and ',$aTerms);
902 $sSQL .= " order by ".join(', ',$aOrder);
903 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
904 $sSQL .= " limit 50";
905 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
908 $sSQL .= " limit ".$iLimit;
910 if (CONST_Debug) { var_dump($sSQL); }
911 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
912 if (PEAR::IsError($aViewBoxPlaceIDs))
914 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
916 //var_dump($aViewBoxPlaceIDs);
917 // Did we have an viewbox matches?
918 $aPlaceIDs = array();
919 $bViewBoxMatch = false;
920 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
922 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
923 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
924 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
925 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
926 $aPlaceIDs[] = $aViewBoxRow['place_id'];
929 //var_Dump($aPlaceIDs);
932 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
934 $aRoadPlaceIDs = $aPlaceIDs;
935 $sPlaceIDs = join(',',$aPlaceIDs);
937 // Now they are indexed look for a house attached to a street we found
938 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
939 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
940 if (sizeof($aExcludePlaceIDs))
942 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
944 $sSQL .= " limit $iLimit";
945 if (CONST_Debug) var_dump($sSQL);
946 $aPlaceIDs = $oDB->getCol($sSQL);
948 // If not try the aux fallback table
949 if (!sizeof($aPlaceIDs))
951 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
952 if (sizeof($aExcludePlaceIDs))
954 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
956 // $sSQL .= " limit $iLimit";
957 if (CONST_Debug) var_dump($sSQL);
958 $aPlaceIDs = $oDB->getCol($sSQL);
961 if (!sizeof($aPlaceIDs))
963 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
964 if (sizeof($aExcludePlaceIDs))
966 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
968 // $sSQL .= " limit $iLimit";
969 if (CONST_Debug) var_dump($sSQL);
970 $aPlaceIDs = $oDB->getCol($sSQL);
973 // Fallback to the road
974 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
976 $aPlaceIDs = $aRoadPlaceIDs;
981 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
983 $sPlaceIDs = join(',',$aPlaceIDs);
985 $aClassPlaceIDs = array();
987 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
989 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
990 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
991 $sSQL .= " and linked_place_id is null";
992 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
993 $sSQL .= " order by rank_search asc limit $iLimit";
994 if (CONST_Debug) var_dump($sSQL);
995 $aClassPlaceIDs = $oDB->getCol($sSQL);
998 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1000 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1001 $bCacheTable = $oDB->getOne($sSQL);
1003 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1005 if (CONST_Debug) var_dump($sSQL);
1006 $iMaxRank = ((int)$oDB->getOne($sSQL));
1008 // For state / country level searches the normal radius search doesn't work very well
1009 $sPlaceGeom = false;
1010 if ($iMaxRank < 9 && $bCacheTable)
1012 // Try and get a polygon to search in instead
1013 $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";
1014 if (CONST_Debug) var_dump($sSQL);
1015 $sPlaceGeom = $oDB->getOne($sSQL);
1025 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1026 if (CONST_Debug) var_dump($sSQL);
1027 $aPlaceIDs = $oDB->getCol($sSQL);
1028 $sPlaceIDs = join(',',$aPlaceIDs);
1031 if ($sPlaceIDs || $sPlaceGeom)
1037 // More efficient - can make the range bigger
1041 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1042 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1043 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1045 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1046 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1049 $sSQL .= ",placex as f where ";
1050 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1055 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1057 if (sizeof($aExcludePlaceIDs))
1059 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1061 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1062 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1063 if ($iOffset) $sSQL .= " offset $iOffset";
1064 $sSQL .= " limit $iLimit";
1065 if (CONST_Debug) var_dump($sSQL);
1066 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1070 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1073 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1074 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1076 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1077 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1078 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1079 if (sizeof($aExcludePlaceIDs))
1081 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1083 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1084 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1085 if ($iOffset) $sSQL .= " offset $iOffset";
1086 $sSQL .= " limit $iLimit";
1087 if (CONST_Debug) var_dump($sSQL);
1088 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1093 $aPlaceIDs = $aClassPlaceIDs;
1099 if (PEAR::IsError($aPlaceIDs))
1101 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1104 if (CONST_Debug) var_Dump($aPlaceIDs);
1106 foreach($aPlaceIDs as $iPlaceID)
1108 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1110 if ($iQueryLoop > 20) break;
1114 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1115 if ($iGroupLoop > 4) break;
1116 if ($iQueryLoop > 30) break;
1119 // Did we find anything?
1120 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1122 //var_Dump($aResultPlaceIDs);exit;
1123 // Get the details for display (is this a redundant extra step?)
1124 $sPlaceIDs = join(',',$aResultPlaceIDs);
1125 $sOrderSQL = 'CASE ';
1126 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1128 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1130 $sOrderSQL .= ' ELSE 10000000 END';
1131 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1132 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1133 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1134 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1135 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1136 // $sSQL .= $sOrderSQL." as porder, ";
1137 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1138 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1139 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1140 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1141 $sSQL .= "and linked_place_id is null ";
1142 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1143 if (!$bDeDupe) $sSQL .= ",place_id";
1144 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1145 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1146 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1148 $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,";
1149 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1150 $sSQL .= "null as placename,";
1151 $sSQL .= "null as ref,";
1152 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1153 // $sSQL .= $sOrderSQL." as porder, ";
1154 $sSQL .= "-0.15 as importance ";
1155 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1156 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1157 $sSQL .= "group by place_id";
1158 if (!$bDeDupe) $sSQL .= ",place_id";
1160 $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,";
1161 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1162 $sSQL .= "null as placename,";
1163 $sSQL .= "null as ref,";
1164 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1165 // $sSQL .= $sOrderSQL." as porder, ";
1166 $sSQL .= "-0.10 as importance ";
1167 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1168 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1169 $sSQL .= "group by place_id";
1170 if (!$bDeDupe) $sSQL .= ",place_id";
1171 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1172 $sSQL .= "order by importance desc";
1173 // $sSQL .= "order by rank_search,rank_address,porder asc";
1174 if (CONST_Debug) var_dump('<hr>',$sSQL);
1175 $aSearchResults = $oDB->getAll($sSQL);
1176 //var_dump($sSQL,$aSearchResults);exit;
1178 if (PEAR::IsError($aSearchResults))
1180 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1183 } // end if ($sQuery)
1186 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1188 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1189 $aResultPlaceIDs = array($iPlaceID);
1191 // TODO: this needs refactoring!
1193 // Get the details for display (is this a redundant extra step?)
1194 $sPlaceIDs = join(',',$aResultPlaceIDs);
1195 $sOrderSQL = 'CASE ';
1196 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1198 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1200 $sOrderSQL .= ' ELSE 10000000 END';
1201 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1202 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1203 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1204 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1205 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1206 // $sSQL .= $sOrderSQL." as porder, ";
1207 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1208 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1209 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1210 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1211 if (!$bDeDupe) $sSQL .= ",place_id";
1212 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1213 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1214 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1216 $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,";
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 .= "-0.15 as importance ";
1223 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1224 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1225 $sSQL .= "group by place_id";
1226 if (!$bDeDupe) $sSQL .= ",place_id";
1228 $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,";
1229 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1230 $sSQL .= "null as placename,";
1231 $sSQL .= "null as ref,";
1232 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1233 // $sSQL .= $sOrderSQL." as porder, ";
1234 $sSQL .= "-0.10 as importance ";
1235 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1236 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1237 $sSQL .= "group by place_id";
1238 if (!$bDeDupe) $sSQL .= ",place_id";
1239 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1240 $sSQL .= "order by importance desc";
1241 // $sSQL .= "order by rank_search,rank_address,porder asc";
1242 if (CONST_Debug) var_dump('<hr>',$sSQL);
1243 $aSearchResults = $oDB->getAll($sSQL);
1244 //var_dump($sSQL,$aSearchResults);exit;
1246 if (PEAR::IsError($aSearchResults))
1248 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1254 $sSearchResult = '';
1255 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1257 $sSearchResult = 'No Results Found';
1259 //var_Dump($aSearchResults);
1261 $aClassType = getClassTypesWithImportance();
1262 $aRecheckWords = preg_split('/\b/',$sQuery);
1263 foreach($aRecheckWords as $i => $sWord)
1265 if (!$sWord) unset($aRecheckWords[$i]);
1267 foreach($aSearchResults as $iResNum => $aResult)
1269 if (CONST_Search_AreaPolygons)
1271 // Get the bounding box and outline polygon
1272 $sSQL = "select place_id,numfeatures,area,outline,";
1273 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1274 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1275 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1277 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1278 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1279 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1280 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1281 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1282 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1283 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1284 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1285 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1286 $aPointPolygon = $oDB->getRow($sSQL);
1287 if (PEAR::IsError($aPointPolygon))
1289 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1291 if ($aPointPolygon['place_id'])
1293 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1294 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1295 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1296 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1298 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1299 $aResult['lat'] = $aPointPolygon['centrelat'];
1300 $aResult['lon'] = $aPointPolygon['centrelon'];
1304 // Translate geometary string to point array
1305 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1307 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1309 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1311 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1313 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1316 $iSteps = ($fRadius * 40000)^2;
1317 $fStepSize = (2*pi())/$iSteps;
1318 $aPolyPoints = array();
1319 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1321 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1323 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1324 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1325 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1326 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1330 // Output data suitable for display (points and a bounding box)
1331 if ($bShowPolygons && isset($aPolyPoints))
1333 $aResult['aPolyPoints'] = array();
1334 foreach($aPolyPoints as $aPoint)
1336 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1339 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1343 if (!isset($aResult['aBoundingBox']))
1346 $fDiameter = 0.0001;
1348 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1349 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1351 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1353 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1354 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1356 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1358 $fRadius = $fDiameter / 2;
1360 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1361 $fStepSize = (2*pi())/$iSteps;
1362 $aPolyPoints = array();
1363 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1365 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1367 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1368 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1369 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1370 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1372 // Output data suitable for display (points and a bounding box)
1375 $aResult['aPolyPoints'] = array();
1376 foreach($aPolyPoints as $aPoint)
1378 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1381 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1384 // Is there an icon set for this type of result?
1385 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1386 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1388 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1391 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1392 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1394 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1397 if ($bShowAddressDetails)
1399 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1400 //var_dump($aResult['address']);
1404 // Adjust importance for the number of exact string matches in the result
1405 $aResult['importance'] = max(0.001,$aResult['importance']);
1407 $sAddress = $aResult['langaddress'];
1408 foreach($aRecheckWords as $i => $sWord)
1410 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1412 $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
1414 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1416 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1417 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1419 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1421 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1422 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1424 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1428 $aResult['importance'] = 1000000000000000;
1431 $aResult['name'] = $aResult['langaddress'];
1432 $aResult['foundorder'] = $iResNum;
1433 $aSearchResults[$iResNum] = $aResult;
1435 uasort($aSearchResults, 'byImportance');
1437 $aOSMIDDone = array();
1438 $aClassTypeNameDone = array();
1439 $aToFilter = $aSearchResults;
1440 $aSearchResults = array();
1443 foreach($aToFilter as $iResNum => $aResult)
1445 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1446 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1449 $fLat = $aResult['lat'];
1450 $fLon = $aResult['lon'];
1451 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1454 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1455 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1457 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1458 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1459 $aSearchResults[] = $aResult;
1462 // Absolute limit on number of results
1463 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1466 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1468 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1470 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1475 logEnd($oDB, $hLog, sizeof($aToFilter));
1477 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1478 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1479 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1480 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1481 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1482 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1485 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1487 $sMoreURL .= '&q='.urlencode($sQuery);
1489 if (CONST_Debug) exit;
1491 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');