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;
74 if (isset($aLangPrefOrder['name:pl'])) $bReverseInPlan = true;
76 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
78 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
80 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
82 $iExcludedPlaceID = (int)$iExcludedPlaceID;
83 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
87 // Only certain ranks of feature
88 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
90 if (isset($_GET['featuretype']))
92 switch($_GET['featuretype'])
95 $iMinAddressRank = $iMaxAddressRank = 4;
98 $iMinAddressRank = $iMaxAddressRank = 8;
101 $iMinAddressRank = 14;
102 $iMaxAddressRank = 16;
105 $iMinAddressRank = 8;
106 $iMaxAddressRank = 20;
111 if (isset($_GET['countrycodes']))
113 $aCountryCodes = array();
114 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
116 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
118 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
121 $sCountryCodesSQL = join(',', $aCountryCodes);
125 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
126 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
128 $sQuery = substr($_SERVER['PATH_INFO'], 1);
130 // reverse order of '/' separated string
131 $aPhrases = explode('/', $sQuery);
132 $aPhrases = array_reverse($aPhrases);
133 $sQuery = join(', ',$aPhrases);
136 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
138 if (!isset($_GET[$sKey])) return false;
139 $sValue = trim($_GET[$sKey]);
140 if (!$sValue) return false;
141 $aStructuredQuery[$sKey] = $sValue;
142 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
143 $iMinAddressRank = $iNewMinAddressRank;
144 $iMaxAddressRank = $iNewMaxAddressRank;
150 $aStructuredOptions = array(
151 array('amenity', 26, 30),
152 array('street', 26, 30),
153 array('city', 14, 24),
154 array('county', 9, 13),
155 array('state', 8, 8),
156 array('country', 4, 4),
157 array('postalcode', 16, 25),
159 $aStructuredQuery = array();
160 $sAllowedTypesSQLList = '';
161 foreach($aStructuredOptions as $aStructuredOption)
163 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
165 if (sizeof($aStructuredQuery) > 0) {
166 $sQuery = join(', ', $aStructuredQuery);
167 if ($iMaxAddressRank < 30)
169 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
175 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
177 // Hack to make it handle "new york, ny" (and variants) correctly
178 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
179 if (isset($aLangPrefOrder['name:en']))
181 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
182 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
183 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
186 // If we have a view box create the SQL
187 // Small is the actual view box, Large is double (on each axis) that
188 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
189 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
191 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
192 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
194 if (isset($_GET['viewbox']) && $_GET['viewbox'])
196 $aCoOrdinates = explode(',',$_GET['viewbox']);
197 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
198 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
199 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
200 $aCoOrdinates[0] += $fHeight;
201 $aCoOrdinates[2] -= $fHeight;
202 $aCoOrdinates[1] += $fWidth;
203 $aCoOrdinates[3] -= $fWidth;
204 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
206 $bBoundingBoxSearch = false;
208 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
210 $aPoints = explode(',',$_GET['route']);
211 if (sizeof($aPoints) % 2 != 0)
213 userError("Uneven number of points");
216 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
218 foreach($aPoints as $i => $fPoint)
222 if ($i != 1) $sViewboxCentreSQL .= ",";
223 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
227 $fPrevCoord = (float)$fPoint;
230 $sViewboxCentreSQL .= ")'::geometry,4326)";
232 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
233 $sViewboxSmallSQL = $oDB->getOne($sSQL);
234 if (PEAR::isError($sViewboxSmallSQL))
236 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
238 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
240 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
241 $sViewboxLargeSQL = $oDB->getOne($sSQL);
242 if (PEAR::isError($sViewboxLargeSQL))
244 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
246 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
247 $bBoundingBoxSearch = true;
250 // Do we have anything that looks like a lat/lon pair?
251 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
253 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
254 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
255 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
257 $_GET['nearlat'] = $fQueryLat;
258 $_GET['nearlon'] = $fQueryLon;
259 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
262 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
264 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
265 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
266 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
268 $_GET['nearlat'] = $fQueryLat;
269 $_GET['nearlon'] = $fQueryLon;
270 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
273 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
275 $fQueryLat = $aData[2];
276 $fQueryLon = $aData[3];
277 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
279 $_GET['nearlat'] = $fQueryLat;
280 $_GET['nearlon'] = $fQueryLon;
281 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
285 if ($sQuery || $aStructuredQuery)
287 // Start with a blank search
289 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
290 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
293 $sNearPointSQL = false;
294 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
296 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
297 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
298 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
299 $aSearches[0]['fRadius'] = 0.1;
302 $bSpecialTerms = false;
303 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
304 $aSpecialTerms = array();
305 foreach($aSpecialTermsRaw as $aSpecialTerm)
307 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
308 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
311 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
312 $aSpecialTerms = array();
313 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
315 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
316 unset($aStructuredQuery['amenity']);
318 foreach($aSpecialTermsRaw as $aSpecialTerm)
320 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
321 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
322 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
323 $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';
324 if (CONST_Debug) var_Dump($sSQL);
325 $aSearchWords = $oDB->getAll($sSQL);
326 $aNewSearches = array();
327 foreach($aSearches as $aSearch)
329 foreach($aSearchWords as $aSearchTerm)
331 $aNewSearch = $aSearch;
332 if ($aSearchTerm['country_code'])
334 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
335 $aNewSearches[] = $aNewSearch;
336 $bSpecialTerms = true;
338 if ($aSearchTerm['class'])
340 $aNewSearch['sClass'] = $aSearchTerm['class'];
341 $aNewSearch['sType'] = $aSearchTerm['type'];
342 $aNewSearches[] = $aNewSearch;
343 $bSpecialTerms = true;
347 $aSearches = $aNewSearches;
350 // Split query into phrases
351 // Commas are used to reduce the search space by indicating where phrases split
352 if (sizeof($aStructuredQuery) > 0)
354 $aPhrases = $aStructuredQuery;
355 $bStructuredPhrases = true;
359 $aPhrases = explode(',',$sQuery);
360 $bStructuredPhrases = false;
364 // Convert each phrase to standard form
365 // Create a list of standard words
366 // Get all 'sets' of words
367 // Generate a complete list of all
369 foreach($aPhrases as $iPhrase => $sPhrase)
371 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
372 if (PEAR::isError($aPhrase))
374 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
375 if (CONST_Debug) var_dump($aPhrase);
378 if (trim($aPhrase['string']))
380 $aPhrases[$iPhrase] = $aPhrase;
381 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
382 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
383 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
387 unset($aPhrases[$iPhrase]);
391 // reindex phrases - we make assumptions later on
392 $aPhraseTypes = array_keys($aPhrases);
393 $aPhrases = array_values($aPhrases);
395 if (sizeof($aTokens))
398 // Check which tokens we have, get the ID numbers
399 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator, search_name_count';
400 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
401 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
402 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
404 if (CONST_Debug) var_Dump($sSQL);
406 $aValidTokens = array();
407 if (sizeof($aTokens))
408 $aDatabaseWords = $oDB->getAll($sSQL);
410 $aDatabaseWords = array();
411 if (PEAR::IsError($aDatabaseWords))
413 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
415 $aPossibleMainWordIDs = array();
416 foreach($aDatabaseWords as $aToken)
418 if (isset($aValidTokens[$aToken['word_token']]))
420 $aValidTokens[$aToken['word_token']][] = $aToken;
424 $aValidTokens[$aToken['word_token']] = array($aToken);
426 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1 + $aToken['search_name_count'];
428 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
430 $aSuggestion = array();
431 $bSuggestion = false;
432 if (CONST_Suggestions_Enabled)
434 foreach($aPhrases as $iPhrase => $aPhrase)
436 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
438 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
439 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
440 $aRow = $aSuggestionWords[0];
441 if ($aRow && $aRow['word'])
443 $aSuggestion[] = $aRow['word'];
448 $aSuggestion[] = $aPhrase['string'];
453 $aSuggestion[] = $aPhrase['string'];
457 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
459 // Try and calculate GB postcodes we might be missing
460 foreach($aTokens as $sToken)
462 // Source of gb postcodes is now definitive - always use
463 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
465 if (substr($aData[1],-2,1) != ' ')
467 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
468 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
470 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
471 if ($aGBPostcodeLocation)
473 $aValidTokens[$sToken] = $aGBPostcodeLocation;
478 foreach($aTokens as $sToken)
480 // Unknown single word token with a number - assume it is a house number
481 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
483 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
487 // Any words that have failed completely?
490 // Start the search process
491 $aResultPlaceIDs = array();
494 Calculate all searches using aValidTokens i.e.
496 'Wodsworth Road, Sheffield' =>
500 0 1 (wodsworth)(road)
503 Score how good the search is so they can be ordered
505 foreach($aPhrases as $iPhrase => $sPhrase)
507 $aNewPhraseSearches = array();
508 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
509 else $sPhraseType = '';
511 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
513 $aWordsetSearches = $aSearches;
515 // Add all words from this wordset
516 foreach($aWordset as $iToken => $sToken)
518 //echo "<br><b>$sToken</b>";
519 $aNewWordsetSearches = array();
521 foreach($aWordsetSearches as $aCurrentSearch)
524 //var_dump($aCurrentSearch);
527 // If the token is valid
528 if (isset($aValidTokens[' '.$sToken]))
530 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
532 $aSearch = $aCurrentSearch;
533 $aSearch['iSearchRank']++;
534 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
536 if ($aSearch['sCountryCode'] === false)
538 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
539 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
540 // If reverse order is enabled, it may appear at the beginning as well.
541 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
542 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
544 $aSearch['iSearchRank'] += 5;
546 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
549 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
551 if ($aSearch['fLat'] === '')
553 $aSearch['fLat'] = $aSearchTerm['lat'];
554 $aSearch['fLon'] = $aSearchTerm['lon'];
555 $aSearch['fRadius'] = $aSearchTerm['radius'];
556 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
559 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
561 if ($aSearch['sHouseNumber'] === '')
563 $aSearch['sHouseNumber'] = $sToken;
564 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
566 // Fall back to not searching for this item (better than nothing)
567 $aSearch = $aCurrentSearch;
568 $aSearch['iSearchRank'] += 1;
569 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
573 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
575 if ($aSearch['sClass'] === '')
577 $aSearch['sOperator'] = $aSearchTerm['operator'];
578 $aSearch['sClass'] = $aSearchTerm['class'];
579 $aSearch['sType'] = $aSearchTerm['type'];
580 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
581 else $aSearch['sOperator'] = 'near'; // near = in for the moment
583 // Do we have a shortcut id?
584 if ($aSearch['sOperator'] == 'name')
586 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
587 if ($iAmenityID = $oDB->getOne($sSQL))
589 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
590 $aSearch['aName'][$iAmenityID] = $iAmenityID;
591 $aSearch['sClass'] = '';
592 $aSearch['sType'] = '';
595 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
598 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
600 if (sizeof($aSearch['aName']))
602 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
604 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
608 $aSearch['iSearchRank'] += 1000; // skip;
613 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
614 // $aSearch['iNamePhrase'] = $iPhrase;
616 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
620 if (isset($aValidTokens[$sToken]))
622 // Allow searching for a word - but at extra cost
623 foreach($aValidTokens[$sToken] as $aSearchTerm)
625 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
627 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
629 $aSearch = $aCurrentSearch;
630 $aSearch['iSearchRank'] += 1;
631 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
632 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
635 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
637 $aSearch = $aCurrentSearch;
638 $aSearch['iSearchRank'] += 2;
639 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
640 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
641 $aSearch['iNamePhrase'] = $iPhrase;
642 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
649 // Allow skipping a word - but at EXTREAM cost
650 //$aSearch = $aCurrentSearch;
651 //$aSearch['iSearchRank']+=100;
652 //$aNewWordsetSearches[] = $aSearch;
656 usort($aNewWordsetSearches, 'bySearchRank');
657 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
659 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
661 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
662 usort($aNewPhraseSearches, 'bySearchRank');
664 $aSearchHash = array();
665 foreach($aNewPhraseSearches as $iSearch => $aSearch)
667 $sHash = serialize($aSearch);
668 if (isset($aSearchHash[$sHash]))
670 unset($aNewPhraseSearches[$iSearch]);
674 $aSearchHash[$sHash] = 1;
678 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
681 // Re-group the searches by their score, junk anything over 20 as just not worth trying
682 $aGroupedSearches = array();
683 foreach($aNewPhraseSearches as $aSearch)
685 if ($aSearch['iSearchRank'] < $iMaxRank)
687 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
688 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
691 ksort($aGroupedSearches);
694 $aSearches = array();
695 foreach($aGroupedSearches as $iScore => $aNewSearches)
697 $iSearchCount += sizeof($aNewSearches);
698 $aSearches = array_merge($aSearches, $aNewSearches);
699 if ($iSearchCount > 50) break;
702 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
708 // Re-group the searches by their score, junk anything over 20 as just not worth trying
709 $aGroupedSearches = array();
710 foreach($aSearches as $aSearch)
712 if ($aSearch['iSearchRank'] < $iMaxRank)
714 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
715 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
718 ksort($aGroupedSearches);
721 if (CONST_Debug) var_Dump($aGroupedSearches);
725 $aCopyGroupedSearches = $aGroupedSearches;
726 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
728 foreach($aSearches as $iSearch => $aSearch)
730 if (sizeof($aSearch['aAddress']))
732 $iReverseItem = array_pop($aSearch['aAddress']);
733 if (isset($aPossibleMainWordIDs[$iReverseItem]))
735 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
736 $aSearch['aName'] = array($iReverseItem);
737 $aGroupedSearches[$iGroup][] = $aSearch;
739 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
740 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
746 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
748 $aCopyGroupedSearches = $aGroupedSearches;
749 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
751 foreach($aSearches as $iSearch => $aSearch)
753 $aReductionsList = array($aSearch['aAddress']);
754 $iSearchRank = $aSearch['iSearchRank'];
755 while(sizeof($aReductionsList) > 0)
758 if ($iSearchRank > iMaxRank) break 3;
759 $aNewReductionsList = array();
760 foreach($aReductionsList as $aReductionsWordList)
762 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
764 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
765 $aReverseSearch = $aSearch;
766 $aSearch['aAddress'] = $aReductionsWordListResult;
767 $aSearch['iSearchRank'] = $iSearchRank;
768 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
769 if (sizeof($aReductionsWordListResult) > 0)
771 $aNewReductionsList[] = $aReductionsWordListResult;
775 $aReductionsList = $aNewReductionsList;
779 ksort($aGroupedSearches);
782 // Filter out duplicate searches
783 $aSearchHash = array();
784 foreach($aGroupedSearches as $iGroup => $aSearches)
786 foreach($aSearches as $iSearch => $aSearch)
788 $sHash = serialize($aSearch);
789 if (isset($aSearchHash[$sHash]))
791 unset($aGroupedSearches[$iGroup][$iSearch]);
792 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
796 $aSearchHash[$sHash] = 1;
801 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
805 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
808 foreach($aSearches as $aSearch)
812 // Must have a location term
813 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
815 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
817 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
819 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
820 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
821 $sSQL .= " order by st_area(geometry) desc limit 1";
822 $aPlaceIDs = $oDB->getCol($sSQL);
827 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
828 if (!$aSearch['sClass']) continue;
829 if (CONST_Debug) var_dump('<hr>',$aSearch);
830 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
831 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
832 if ($oDB->getOne($sSQL))
834 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
835 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
836 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
837 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
838 if (sizeof($aExcludePlaceIDs))
840 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
842 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
843 $sSQL .= " limit $iLimit";
844 if (CONST_Debug) var_dump($sSQL);
845 $aPlaceIDs = $oDB->getCol($sSQL);
847 // If excluded place IDs are given, it is fair to assume that
848 // there have been results in the small box, so no further
849 // expansion in that case.
850 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
852 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
853 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
854 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
855 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
856 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
857 $sSQL .= " limit $iLimit";
858 if (CONST_Debug) var_dump($sSQL);
859 $aPlaceIDs = $oDB->getCol($sSQL);
864 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
865 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
866 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
867 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
868 $sSQL .= " limit $iLimit";
869 if (CONST_Debug) var_dump($sSQL);
870 $aPlaceIDs = $oDB->getCol($sSQL);
876 if (CONST_Debug) var_dump('<hr>',$aSearch);
877 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
878 $aPlaceIDs = array();
880 // First we need a position, either aName or fLat or both
884 // TODO: filter out the pointless search terms (2 letter name tokens and less)
885 // they might be right - but they are just too darned expensive to run
886 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
887 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
889 // For infrequent name terms disable index usage for address
890 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
891 sizeof($aSearch['aName']) == 1 &&
892 $aPossibleMainWordIDs[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
894 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
898 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
901 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
902 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
903 if ($aSearch['fLon'] && $aSearch['fLat'])
905 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
906 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
908 if (sizeof($aExcludePlaceIDs))
910 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
912 if ($sCountryCodesSQL)
914 $aTerms[] = "country_code in ($sCountryCodesSQL)";
917 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
918 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
920 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end';
922 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
923 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
924 $aOrder[] = "$sImportanceSQL DESC";
928 $sSQL = "select place_id";
929 $sSQL .= " from search_name";
930 $sSQL .= " where ".join(' and ',$aTerms);
931 $sSQL .= " order by ".join(', ',$aOrder);
932 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
933 $sSQL .= " limit 50";
934 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
937 $sSQL .= " limit ".$iLimit;
939 if (CONST_Debug) var_dump($sSQL);
940 $iStartTime = time();
941 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
942 if (PEAR::IsError($aViewBoxPlaceIDs))
944 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
946 if (time() - $iStartTime > 60) {
947 file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
950 //var_dump($aViewBoxPlaceIDs);
951 // Did we have an viewbox matches?
952 $aPlaceIDs = array();
953 $bViewBoxMatch = false;
954 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
956 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
957 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
958 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
959 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
960 $aPlaceIDs[] = $aViewBoxRow['place_id'];
963 //var_Dump($aPlaceIDs);
966 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
968 $aRoadPlaceIDs = $aPlaceIDs;
969 $sPlaceIDs = join(',',$aPlaceIDs);
971 // Now they are indexed look for a house attached to a street we found
972 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
973 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
974 if (sizeof($aExcludePlaceIDs))
976 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
978 $sSQL .= " limit $iLimit";
979 if (CONST_Debug) var_dump($sSQL);
980 $aPlaceIDs = $oDB->getCol($sSQL);
982 // If not try the aux fallback table
983 if (!sizeof($aPlaceIDs))
985 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
986 if (sizeof($aExcludePlaceIDs))
988 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
990 // $sSQL .= " limit $iLimit";
991 if (CONST_Debug) var_dump($sSQL);
992 $aPlaceIDs = $oDB->getCol($sSQL);
995 if (!sizeof($aPlaceIDs))
997 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
998 if (sizeof($aExcludePlaceIDs))
1000 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1002 // $sSQL .= " limit $iLimit";
1003 if (CONST_Debug) var_dump($sSQL);
1004 $aPlaceIDs = $oDB->getCol($sSQL);
1007 // Fallback to the road
1008 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1010 $aPlaceIDs = $aRoadPlaceIDs;
1015 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1017 $sPlaceIDs = join(',',$aPlaceIDs);
1019 $aClassPlaceIDs = array();
1021 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1023 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1024 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1025 $sSQL .= " and linked_place_id is null";
1026 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
1027 $sSQL .= " order by rank_search asc limit $iLimit";
1028 if (CONST_Debug) var_dump($sSQL);
1029 $aClassPlaceIDs = $oDB->getCol($sSQL);
1032 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1034 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1035 $bCacheTable = $oDB->getOne($sSQL);
1037 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1039 if (CONST_Debug) var_dump($sSQL);
1040 $iMaxRank = ((int)$oDB->getOne($sSQL));
1042 // For state / country level searches the normal radius search doesn't work very well
1043 $sPlaceGeom = false;
1044 if ($iMaxRank < 9 && $bCacheTable)
1046 // Try and get a polygon to search in instead
1047 $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";
1048 if (CONST_Debug) var_dump($sSQL);
1049 $sPlaceGeom = $oDB->getOne($sSQL);
1059 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1060 if (CONST_Debug) var_dump($sSQL);
1061 $aPlaceIDs = $oDB->getCol($sSQL);
1062 $sPlaceIDs = join(',',$aPlaceIDs);
1065 if ($sPlaceIDs || $sPlaceGeom)
1071 // More efficient - can make the range bigger
1075 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1076 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1077 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1079 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1080 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1083 $sSQL .= ",placex as f where ";
1084 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1089 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1091 if (sizeof($aExcludePlaceIDs))
1093 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1095 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1096 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1097 if ($iOffset) $sSQL .= " offset $iOffset";
1098 $sSQL .= " limit $iLimit";
1099 if (CONST_Debug) var_dump($sSQL);
1100 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1104 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1107 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1108 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1110 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1111 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1112 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1113 if (sizeof($aExcludePlaceIDs))
1115 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1117 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1118 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1119 if ($iOffset) $sSQL .= " offset $iOffset";
1120 $sSQL .= " limit $iLimit";
1121 if (CONST_Debug) var_dump($sSQL);
1122 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1127 $aPlaceIDs = $aClassPlaceIDs;
1133 if (PEAR::IsError($aPlaceIDs))
1135 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1138 if (CONST_Debug) var_Dump($aPlaceIDs);
1140 foreach($aPlaceIDs as $iPlaceID)
1142 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1144 if ($iQueryLoop > 20) break;
1148 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1149 if ($iGroupLoop > 4) break;
1150 if ($iQueryLoop > 30) break;
1153 // Did we find anything?
1154 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1156 //var_Dump($aResultPlaceIDs);exit;
1157 // Get the details for display (is this a redundant extra step?)
1158 $sPlaceIDs = join(',',$aResultPlaceIDs);
1159 $sOrderSQL = 'CASE ';
1160 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1162 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1164 $sOrderSQL .= ' ELSE 10000000 END';
1165 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1166 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1167 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1168 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1169 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1170 // $sSQL .= $sOrderSQL." as porder, ";
1171 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1172 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1173 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1174 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1175 $sSQL .= "and linked_place_id is null ";
1176 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1177 if (!$bDeDupe) $sSQL .= ",place_id";
1178 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1179 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1180 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1182 $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,";
1183 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1184 $sSQL .= "null as placename,";
1185 $sSQL .= "null as ref,";
1186 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1187 // $sSQL .= $sOrderSQL." as porder, ";
1188 $sSQL .= "-0.15 as importance ";
1189 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1190 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1191 $sSQL .= "group by place_id";
1192 if (!$bDeDupe) $sSQL .= ",place_id";
1194 $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,";
1195 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1196 $sSQL .= "null as placename,";
1197 $sSQL .= "null as ref,";
1198 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1199 // $sSQL .= $sOrderSQL." as porder, ";
1200 $sSQL .= "-0.10 as importance ";
1201 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1202 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1203 $sSQL .= "group by place_id";
1204 if (!$bDeDupe) $sSQL .= ",place_id";
1205 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1206 $sSQL .= "order by importance desc";
1207 // $sSQL .= "order by rank_search,rank_address,porder asc";
1208 if (CONST_Debug) var_dump('<hr>',$sSQL);
1209 $aSearchResults = $oDB->getAll($sSQL);
1210 //var_dump($sSQL,$aSearchResults);exit;
1212 if (PEAR::IsError($aSearchResults))
1214 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1217 } // end if ($sQuery)
1220 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1222 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1223 $aResultPlaceIDs = array($iPlaceID);
1225 // TODO: this needs refactoring!
1227 // Get the details for display (is this a redundant extra step?)
1228 $sPlaceIDs = join(',',$aResultPlaceIDs);
1229 $sOrderSQL = 'CASE ';
1230 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1232 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1234 $sOrderSQL .= ' ELSE 10000000 END';
1235 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1236 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1237 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1238 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1239 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1240 // $sSQL .= $sOrderSQL." as porder, ";
1241 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1242 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1243 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1244 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1245 if (!$bDeDupe) $sSQL .= ",place_id";
1246 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1247 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1248 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1250 $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,";
1251 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1252 $sSQL .= "null as placename,";
1253 $sSQL .= "null as ref,";
1254 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1255 // $sSQL .= $sOrderSQL." as porder, ";
1256 $sSQL .= "-0.15 as importance ";
1257 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1258 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1259 $sSQL .= "group by place_id";
1260 if (!$bDeDupe) $sSQL .= ",place_id";
1262 $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,";
1263 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1264 $sSQL .= "null as placename,";
1265 $sSQL .= "null as ref,";
1266 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1267 // $sSQL .= $sOrderSQL." as porder, ";
1268 $sSQL .= "-0.10 as importance ";
1269 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1270 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1271 $sSQL .= "group by place_id";
1272 if (!$bDeDupe) $sSQL .= ",place_id";
1273 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1274 $sSQL .= "order by importance desc";
1275 // $sSQL .= "order by rank_search,rank_address,porder asc";
1276 if (CONST_Debug) var_dump('<hr>',$sSQL);
1277 $aSearchResults = $oDB->getAll($sSQL);
1278 //var_dump($sSQL,$aSearchResults);exit;
1280 if (PEAR::IsError($aSearchResults))
1282 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1288 $sSearchResult = '';
1289 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1291 $sSearchResult = 'No Results Found';
1293 //var_Dump($aSearchResults);
1295 $aClassType = getClassTypesWithImportance();
1296 $aRecheckWords = preg_split('/\b/',$sQuery);
1297 foreach($aRecheckWords as $i => $sWord)
1299 if (!$sWord) unset($aRecheckWords[$i]);
1301 foreach($aSearchResults as $iResNum => $aResult)
1303 if (CONST_Search_AreaPolygons)
1305 // Get the bounding box and outline polygon
1306 $sSQL = "select place_id,numfeatures,area,outline,";
1307 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1308 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1309 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1311 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1312 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1313 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1314 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1315 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1316 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1317 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1318 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1319 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1320 $aPointPolygon = $oDB->getRow($sSQL);
1321 if (PEAR::IsError($aPointPolygon))
1323 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1325 if ($aPointPolygon['place_id'])
1327 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1328 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1329 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1330 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1332 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1333 $aResult['lat'] = $aPointPolygon['centrelat'];
1334 $aResult['lon'] = $aPointPolygon['centrelon'];
1338 // Translate geometary string to point array
1339 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1341 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1343 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1345 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1347 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1350 $iSteps = ($fRadius * 40000)^2;
1351 $fStepSize = (2*pi())/$iSteps;
1352 $aPolyPoints = array();
1353 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1355 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1357 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1358 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1359 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1360 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1364 // Output data suitable for display (points and a bounding box)
1365 if ($bShowPolygons && isset($aPolyPoints))
1367 $aResult['aPolyPoints'] = array();
1368 foreach($aPolyPoints as $aPoint)
1370 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1373 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1377 if (!isset($aResult['aBoundingBox']))
1380 $fDiameter = 0.0001;
1382 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1383 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1385 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1387 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1388 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1390 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1392 $fRadius = $fDiameter / 2;
1394 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1395 $fStepSize = (2*pi())/$iSteps;
1396 $aPolyPoints = array();
1397 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1399 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1401 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1402 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1403 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1404 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1406 // Output data suitable for display (points and a bounding box)
1409 $aResult['aPolyPoints'] = array();
1410 foreach($aPolyPoints as $aPoint)
1412 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1415 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1418 // Is there an icon set for this type of result?
1419 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1420 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1422 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1425 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1426 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1428 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1431 if ($bShowAddressDetails)
1433 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1434 //var_dump($aResult['address']);
1438 // Adjust importance for the number of exact string matches in the result
1439 $aResult['importance'] = max(0.001,$aResult['importance']);
1441 $sAddress = $aResult['langaddress'];
1442 foreach($aRecheckWords as $i => $sWord)
1444 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1446 $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
1448 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1450 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1451 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1453 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1455 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1456 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1458 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1462 $aResult['importance'] = 1000000000000000;
1465 $aResult['name'] = $aResult['langaddress'];
1466 $aResult['foundorder'] = $iResNum;
1467 $aSearchResults[$iResNum] = $aResult;
1469 uasort($aSearchResults, 'byImportance');
1471 $aOSMIDDone = array();
1472 $aClassTypeNameDone = array();
1473 $aToFilter = $aSearchResults;
1474 $aSearchResults = array();
1477 foreach($aToFilter as $iResNum => $aResult)
1479 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1480 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1483 $fLat = $aResult['lat'];
1484 $fLon = $aResult['lon'];
1485 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1488 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1489 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1491 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1492 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1493 $aSearchResults[] = $aResult;
1496 // Absolute limit on number of results
1497 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1500 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1502 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1504 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1509 logEnd($oDB, $hLog, sizeof($aToFilter));
1511 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1512 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1513 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1514 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1515 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1516 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1519 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1521 $sMoreURL .= '&q='.urlencode($sQuery);
1523 if (CONST_Debug) exit;
1525 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');