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 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
813 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
816 // Must have a location term
817 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
819 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
821 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
823 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
824 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
825 $sSQL .= " order by st_area(geometry) desc limit 1";
826 if (CONST_Debug) var_dump($sSQL);
827 $aPlaceIDs = $oDB->getCol($sSQL);
832 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
833 if (!$aSearch['sClass']) continue;
834 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
835 if ($oDB->getOne($sSQL))
837 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
838 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
839 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
840 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
841 if (sizeof($aExcludePlaceIDs))
843 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
845 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
846 $sSQL .= " limit $iLimit";
847 if (CONST_Debug) var_dump($sSQL);
848 $aPlaceIDs = $oDB->getCol($sSQL);
850 // If excluded place IDs are given, it is fair to assume that
851 // there have been results in the small box, so no further
852 // expansion in that case.
853 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
855 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
856 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
857 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
858 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
859 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
860 $sSQL .= " limit $iLimit";
861 if (CONST_Debug) var_dump($sSQL);
862 $aPlaceIDs = $oDB->getCol($sSQL);
867 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
868 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
869 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
870 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
871 $sSQL .= " limit $iLimit";
872 if (CONST_Debug) var_dump($sSQL);
873 $aPlaceIDs = $oDB->getCol($sSQL);
879 $aPlaceIDs = array();
881 // First we need a position, either aName or fLat or both
885 // TODO: filter out the pointless search terms (2 letter name tokens and less)
886 // they might be right - but they are just too darned expensive to run
887 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
888 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
890 // For infrequent name terms disable index usage for address
891 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
892 sizeof($aSearch['aName']) == 1 &&
893 $aPossibleMainWordIDs[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
895 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
899 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
902 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
903 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
904 if ($aSearch['fLon'] && $aSearch['fLat'])
906 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
907 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
909 if (sizeof($aExcludePlaceIDs))
911 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
913 if ($sCountryCodesSQL)
915 $aTerms[] = "country_code in ($sCountryCodesSQL)";
918 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
919 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
921 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end';
923 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
924 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
925 $aOrder[] = "$sImportanceSQL DESC";
929 $sSQL = "select place_id";
930 $sSQL .= " from search_name";
931 $sSQL .= " where ".join(' and ',$aTerms);
932 $sSQL .= " order by ".join(', ',$aOrder);
933 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
934 $sSQL .= " limit 50";
935 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
938 $sSQL .= " limit ".$iLimit;
940 if (CONST_Debug) var_dump($sSQL);
941 $iStartTime = time();
942 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
943 if (PEAR::IsError($aViewBoxPlaceIDs))
945 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
947 if (time() - $iStartTime > 60) {
948 file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
951 //var_dump($aViewBoxPlaceIDs);
952 // Did we have an viewbox matches?
953 $aPlaceIDs = array();
954 $bViewBoxMatch = false;
955 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
957 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
958 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
959 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
960 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
961 $aPlaceIDs[] = $aViewBoxRow['place_id'];
964 //var_Dump($aPlaceIDs);
967 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
969 $aRoadPlaceIDs = $aPlaceIDs;
970 $sPlaceIDs = join(',',$aPlaceIDs);
972 // Now they are indexed look for a house attached to a street we found
973 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
974 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
975 if (sizeof($aExcludePlaceIDs))
977 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
979 $sSQL .= " limit $iLimit";
980 if (CONST_Debug) var_dump($sSQL);
981 $aPlaceIDs = $oDB->getCol($sSQL);
983 // If not try the aux fallback table
984 if (!sizeof($aPlaceIDs))
986 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
987 if (sizeof($aExcludePlaceIDs))
989 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
991 // $sSQL .= " limit $iLimit";
992 if (CONST_Debug) var_dump($sSQL);
993 $aPlaceIDs = $oDB->getCol($sSQL);
996 if (!sizeof($aPlaceIDs))
998 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
999 if (sizeof($aExcludePlaceIDs))
1001 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1003 // $sSQL .= " limit $iLimit";
1004 if (CONST_Debug) var_dump($sSQL);
1005 $aPlaceIDs = $oDB->getCol($sSQL);
1008 // Fallback to the road
1009 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1011 $aPlaceIDs = $aRoadPlaceIDs;
1016 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1018 $sPlaceIDs = join(',',$aPlaceIDs);
1020 $aClassPlaceIDs = array();
1022 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1024 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1025 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1026 $sSQL .= " and linked_place_id is null";
1027 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1028 $sSQL .= " order by rank_search asc limit $iLimit";
1029 if (CONST_Debug) var_dump($sSQL);
1030 $aClassPlaceIDs = $oDB->getCol($sSQL);
1033 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1035 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1036 $bCacheTable = $oDB->getOne($sSQL);
1038 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1040 if (CONST_Debug) var_dump($sSQL);
1041 $iMaxRank = ((int)$oDB->getOne($sSQL));
1043 // For state / country level searches the normal radius search doesn't work very well
1044 $sPlaceGeom = false;
1045 if ($iMaxRank < 9 && $bCacheTable)
1047 // Try and get a polygon to search in instead
1048 $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";
1049 if (CONST_Debug) var_dump($sSQL);
1050 $sPlaceGeom = $oDB->getOne($sSQL);
1060 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1061 if (CONST_Debug) var_dump($sSQL);
1062 $aPlaceIDs = $oDB->getCol($sSQL);
1063 $sPlaceIDs = join(',',$aPlaceIDs);
1066 if ($sPlaceIDs || $sPlaceGeom)
1072 // More efficient - can make the range bigger
1076 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1077 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1078 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1080 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1081 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1084 $sSQL .= ",placex as f where ";
1085 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1090 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1092 if (sizeof($aExcludePlaceIDs))
1094 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1096 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1097 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1098 if ($iOffset) $sSQL .= " offset $iOffset";
1099 $sSQL .= " limit $iLimit";
1100 if (CONST_Debug) var_dump($sSQL);
1101 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1105 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1108 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1109 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1111 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1112 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1113 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1114 if (sizeof($aExcludePlaceIDs))
1116 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1118 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1119 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1120 if ($iOffset) $sSQL .= " offset $iOffset";
1121 $sSQL .= " limit $iLimit";
1122 if (CONST_Debug) var_dump($sSQL);
1123 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1128 $aPlaceIDs = $aClassPlaceIDs;
1134 if (PEAR::IsError($aPlaceIDs))
1136 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1139 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1141 foreach($aPlaceIDs as $iPlaceID)
1143 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1145 if ($iQueryLoop > 20) break;
1149 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1150 if ($iGroupLoop > 4) break;
1151 if ($iQueryLoop > 30) break;
1154 // Did we find anything?
1155 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1157 //var_Dump($aResultPlaceIDs);exit;
1158 // Get the details for display (is this a redundant extra step?)
1159 $sPlaceIDs = join(',',$aResultPlaceIDs);
1160 $sOrderSQL = 'CASE ';
1161 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1163 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1165 $sOrderSQL .= ' ELSE 10000000 END';
1166 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,calculated_country_code as country_code,";
1167 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1168 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1169 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1170 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1171 // $sSQL .= $sOrderSQL." as porder, ";
1172 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1173 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1174 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1175 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1176 $sSQL .= "and linked_place_id is null ";
1177 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1178 if (!$bDeDupe) $sSQL .= ",place_id";
1179 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1180 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1181 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1183 $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,";
1184 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1185 $sSQL .= "null as placename,";
1186 $sSQL .= "null as ref,";
1187 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1188 // $sSQL .= $sOrderSQL." as porder, ";
1189 $sSQL .= "-0.15 as importance ";
1190 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1191 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1192 $sSQL .= "group by place_id";
1193 if (!$bDeDupe) $sSQL .= ",place_id";
1195 $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,";
1196 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1197 $sSQL .= "null as placename,";
1198 $sSQL .= "null as ref,";
1199 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1200 // $sSQL .= $sOrderSQL." as porder, ";
1201 $sSQL .= "-0.10 as importance ";
1202 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1203 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1204 $sSQL .= "group by place_id";
1205 if (!$bDeDupe) $sSQL .= ",place_id";
1206 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1207 $sSQL .= "order by importance desc";
1208 // $sSQL .= "order by rank_search,rank_address,porder asc";
1209 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1210 $aSearchResults = $oDB->getAll($sSQL);
1211 //var_dump($sSQL,$aSearchResults);exit;
1213 if (PEAR::IsError($aSearchResults))
1215 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1218 } // end if ($sQuery)
1221 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1223 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1224 $aResultPlaceIDs = array($iPlaceID);
1226 // TODO: this needs refactoring!
1228 // Get the details for display (is this a redundant extra step?)
1229 $sPlaceIDs = join(',',$aResultPlaceIDs);
1230 $sOrderSQL = 'CASE ';
1231 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1233 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1235 $sOrderSQL .= ' ELSE 10000000 END';
1236 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,calculated_country_code as country_code,";
1237 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1238 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1239 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1240 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1241 // $sSQL .= $sOrderSQL." as porder, ";
1242 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1243 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1244 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1245 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1246 if (!$bDeDupe) $sSQL .= ",place_id";
1247 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1248 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1249 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1251 $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,";
1252 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1253 $sSQL .= "null as placename,";
1254 $sSQL .= "null as ref,";
1255 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1256 // $sSQL .= $sOrderSQL." as porder, ";
1257 $sSQL .= "-0.15 as importance ";
1258 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1259 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1260 $sSQL .= "group by place_id";
1261 if (!$bDeDupe) $sSQL .= ",place_id";
1263 $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,";
1264 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1265 $sSQL .= "null as placename,";
1266 $sSQL .= "null as ref,";
1267 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1268 // $sSQL .= $sOrderSQL." as porder, ";
1269 $sSQL .= "-0.10 as importance ";
1270 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1271 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1272 $sSQL .= "group by place_id";
1273 if (!$bDeDupe) $sSQL .= ",place_id";
1274 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1275 $sSQL .= "order by importance desc";
1276 // $sSQL .= "order by rank_search,rank_address,porder asc";
1277 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1278 $aSearchResults = $oDB->getAll($sSQL);
1279 //var_dump($sSQL,$aSearchResults);exit;
1281 if (PEAR::IsError($aSearchResults))
1283 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1289 $sSearchResult = '';
1290 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1292 $sSearchResult = 'No Results Found';
1294 //var_Dump($aSearchResults);
1296 $aClassType = getClassTypesWithImportance();
1297 $aRecheckWords = preg_split('/\b/',$sQuery);
1298 foreach($aRecheckWords as $i => $sWord)
1300 if (!$sWord) unset($aRecheckWords[$i]);
1302 foreach($aSearchResults as $iResNum => $aResult)
1304 if (CONST_Search_AreaPolygons)
1306 // Get the bounding box and outline polygon
1307 $sSQL = "select place_id,numfeatures,area,outline,";
1308 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1309 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1310 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1312 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1313 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1314 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1315 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1316 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1317 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1318 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1319 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1320 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1321 $aPointPolygon = $oDB->getRow($sSQL);
1322 if (PEAR::IsError($aPointPolygon))
1324 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1326 if ($aPointPolygon['place_id'])
1328 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1329 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1330 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1331 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1333 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1334 $aResult['lat'] = $aPointPolygon['centrelat'];
1335 $aResult['lon'] = $aPointPolygon['centrelon'];
1339 // Translate geometary string to point array
1340 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1342 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1344 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1346 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1348 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1351 $iSteps = ($fRadius * 40000)^2;
1352 $fStepSize = (2*pi())/$iSteps;
1353 $aPolyPoints = array();
1354 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1356 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1358 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1359 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1360 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1361 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1365 // Output data suitable for display (points and a bounding box)
1366 if ($bShowPolygons && isset($aPolyPoints))
1368 $aResult['aPolyPoints'] = array();
1369 foreach($aPolyPoints as $aPoint)
1371 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1374 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1378 if (!isset($aResult['aBoundingBox']))
1381 $fDiameter = 0.0001;
1383 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1384 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1386 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1388 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1389 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1391 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1393 $fRadius = $fDiameter / 2;
1395 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1396 $fStepSize = (2*pi())/$iSteps;
1397 $aPolyPoints = array();
1398 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1400 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1402 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1403 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1404 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1405 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1407 // Output data suitable for display (points and a bounding box)
1410 $aResult['aPolyPoints'] = array();
1411 foreach($aPolyPoints as $aPoint)
1413 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1416 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1419 // Is there an icon set for this type of result?
1420 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1421 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1423 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1426 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1427 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1429 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1432 if ($bShowAddressDetails)
1434 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1435 //var_dump($aResult['address']);
1439 // Adjust importance for the number of exact string matches in the result
1440 $aResult['importance'] = max(0.001,$aResult['importance']);
1442 $sAddress = $aResult['langaddress'];
1443 foreach($aRecheckWords as $i => $sWord)
1445 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1447 $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
1449 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1451 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1452 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1454 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1456 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1457 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1459 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1463 $aResult['importance'] = 1000000000000000;
1466 $aResult['name'] = $aResult['langaddress'];
1467 $aResult['foundorder'] = $iResNum;
1468 $aSearchResults[$iResNum] = $aResult;
1470 uasort($aSearchResults, 'byImportance');
1472 $aOSMIDDone = array();
1473 $aClassTypeNameDone = array();
1474 $aToFilter = $aSearchResults;
1475 $aSearchResults = array();
1478 foreach($aToFilter as $iResNum => $aResult)
1480 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1481 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1484 $fLat = $aResult['lat'];
1485 $fLon = $aResult['lon'];
1486 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1489 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1490 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1492 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1493 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1494 $aSearchResults[] = $aResult;
1497 // Absolute limit on number of results
1498 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1501 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1503 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1505 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1510 logEnd($oDB, $hLog, sizeof($aToFilter));
1512 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1513 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1514 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1515 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1516 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1517 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1520 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1522 $sMoreURL .= '&q='.urlencode($sQuery);
1524 if (CONST_Debug) exit;
1526 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');