2 @define('CONST_ConnectionBucket_PageType', 'Search');
4 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
5 require_once(CONST_BasePath.'/lib/log.php');
7 ini_set('memory_limit', '200M');
12 $fLat = CONST_Default_Lat;
13 $fLon = CONST_Default_Lon;
14 $iZoom = CONST_Default_Zoom;
15 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
16 $sOutputFormat = 'html';
17 $aSearchResults = array();
18 $aExcludePlaceIDs = array();
19 $sCountryCodesSQL = false;
20 $sSuggestion = $sSuggestionURL = false;
21 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
22 $bReverseInPlan = false;
23 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
24 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
26 if ($iFinalLimit > 50) $iFinalLimit = 50;
27 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
29 $iMaxAddressRank = 30;
30 $sAllowedTypesSQLList = false;
33 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
35 $sOutputFormat = $_GET['format'];
38 // Show / use polygons
39 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
40 if ($sOutputFormat == 'html') {
41 $bAsText = $bShowPolygons;
42 $bShowPolygons = false;
47 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
48 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
49 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
50 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
51 if ((($bShowPolygons?1:0)
56 ) > CONST_PolygonOutput_MaximumTypes) {
57 if (CONST_PolygonOutput_MaximumTypes) {
58 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
60 userError("Polygon output is disabled");
66 // Show address breakdown
67 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
70 $aLangPrefOrder = getPreferredLanguages();
71 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
72 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
73 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
75 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
77 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
79 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
81 $iExcludedPlaceID = (int)$iExcludedPlaceID;
82 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
86 // Only certain ranks of feature
87 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
89 if (isset($_GET['featuretype']))
91 switch($_GET['featuretype'])
94 $iMinAddressRank = $iMaxAddressRank = 4;
97 $iMinAddressRank = $iMaxAddressRank = 8;
100 $iMinAddressRank = 14;
101 $iMaxAddressRank = 16;
104 $iMinAddressRank = 8;
105 $iMaxAddressRank = 20;
110 if (isset($_GET['countrycodes']))
112 $aCountryCodes = array();
113 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
115 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
117 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
120 $sCountryCodesSQL = join(',', $aCountryCodes);
124 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
125 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
127 $sQuery = substr($_SERVER['PATH_INFO'], 1);
129 // reverse order of '/' separated string
130 $aPhrases = explode('/', $sQuery);
131 $aPhrases = array_reverse($aPhrases);
132 $sQuery = join(', ',$aPhrases);
135 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
137 if (!isset($_GET[$sKey])) return false;
138 $sValue = trim($_GET[$sKey]);
139 if (!$sValue) return false;
140 $aStructuredQuery[$sKey] = $sValue;
141 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
142 $iMinAddressRank = $iNewMinAddressRank;
143 $iMaxAddressRank = $iNewMaxAddressRank;
149 $aStructuredOptions = array(
150 array('amenity', 26, 30),
151 array('street', 26, 30),
152 array('city', 14, 24),
153 array('county', 9, 13),
154 array('state', 8, 8),
155 array('country', 4, 4),
156 array('postalcode', 16, 25),
158 $aStructuredQuery = array();
159 $sAllowedTypesSQLList = '';
160 foreach($aStructuredOptions as $aStructuredOption)
162 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
164 if (sizeof($aStructuredQuery) > 0) {
165 $sQuery = join(', ', $aStructuredQuery);
166 if ($iMaxAddressRank < 30)
168 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
174 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
176 // Hack to make it handle "new york, ny" (and variants) correctly
177 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
178 if (isset($aLangPrefOrder['name:en']))
180 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
181 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
182 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
185 // If we have a view box create the SQL
186 // Small is the actual view box, Large is double (on each axis) that
187 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
188 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
190 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
191 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
193 if (isset($_GET['viewbox']) && $_GET['viewbox'])
195 $aCoOrdinates = explode(',',$_GET['viewbox']);
196 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
197 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
198 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
199 $aCoOrdinates[0] += $fHeight;
200 $aCoOrdinates[2] -= $fHeight;
201 $aCoOrdinates[1] += $fWidth;
202 $aCoOrdinates[3] -= $fWidth;
203 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
205 $bBoundingBoxSearch = false;
207 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
209 $aPoints = explode(',',$_GET['route']);
210 if (sizeof($aPoints) % 2 != 0)
212 userError("Uneven number of points");
215 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
217 foreach($aPoints as $i => $fPoint)
221 if ($i != 1) $sViewboxCentreSQL .= ",";
222 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
226 $fPrevCoord = (float)$fPoint;
229 $sViewboxCentreSQL .= ")'::geometry,4326)";
231 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
232 $sViewboxSmallSQL = $oDB->getOne($sSQL);
233 if (PEAR::isError($sViewboxSmallSQL))
235 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
237 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
239 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
240 $sViewboxLargeSQL = $oDB->getOne($sSQL);
241 if (PEAR::isError($sViewboxLargeSQL))
243 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
245 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
246 $bBoundingBoxSearch = true;
249 // Do we have anything that looks like a lat/lon pair?
250 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
252 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
253 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
254 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
256 $_GET['nearlat'] = $fQueryLat;
257 $_GET['nearlon'] = $fQueryLon;
258 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
261 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
263 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
264 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
265 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
267 $_GET['nearlat'] = $fQueryLat;
268 $_GET['nearlon'] = $fQueryLon;
269 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
272 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
274 $fQueryLat = $aData[2];
275 $fQueryLon = $aData[3];
276 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
278 $_GET['nearlat'] = $fQueryLat;
279 $_GET['nearlon'] = $fQueryLon;
280 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
284 if ($sQuery || $aStructuredQuery)
286 // Start with a blank search
288 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
289 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>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 $aWordFrequencyScores = array();
417 foreach($aDatabaseWords as $aToken)
419 // Very special case - require 2 letter country param to match the country code found
420 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
421 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
426 if (isset($aValidTokens[$aToken['word_token']]))
428 $aValidTokens[$aToken['word_token']][] = $aToken;
432 $aValidTokens[$aToken['word_token']] = array($aToken);
434 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
435 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
437 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
439 $aSuggestion = array();
440 $bSuggestion = false;
441 if (CONST_Suggestions_Enabled)
443 foreach($aPhrases as $iPhrase => $aPhrase)
445 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
447 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
448 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
449 $aRow = $aSuggestionWords[0];
450 if ($aRow && $aRow['word'])
452 $aSuggestion[] = $aRow['word'];
457 $aSuggestion[] = $aPhrase['string'];
462 $aSuggestion[] = $aPhrase['string'];
466 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
468 // Try and calculate GB postcodes we might be missing
469 foreach($aTokens as $sToken)
471 // Source of gb postcodes is now definitive - always use
472 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
474 if (substr($aData[1],-2,1) != ' ')
476 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
477 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
479 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
480 if ($aGBPostcodeLocation)
482 $aValidTokens[$sToken] = $aGBPostcodeLocation;
487 foreach($aTokens as $sToken)
489 // Unknown single word token with a number - assume it is a house number
490 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
492 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
496 // Any words that have failed completely?
499 // Start the search process
500 $aResultPlaceIDs = array();
503 Calculate all searches using aValidTokens i.e.
505 'Wodsworth Road, Sheffield' =>
509 0 1 (wodsworth)(road)
512 Score how good the search is so they can be ordered
514 foreach($aPhrases as $iPhrase => $sPhrase)
516 $aNewPhraseSearches = array();
517 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
518 else $sPhraseType = '';
520 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
522 $aWordsetSearches = $aSearches;
524 // Add all words from this wordset
525 foreach($aWordset as $iToken => $sToken)
527 //echo "<br><b>$sToken</b>";
528 $aNewWordsetSearches = array();
530 foreach($aWordsetSearches as $aCurrentSearch)
533 //var_dump($aCurrentSearch);
536 // If the token is valid
537 if (isset($aValidTokens[' '.$sToken]))
539 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
541 $aSearch = $aCurrentSearch;
542 $aSearch['iSearchRank']++;
543 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
545 if ($aSearch['sCountryCode'] === false)
547 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
548 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
549 // If reverse order is enabled, it may appear at the beginning as well.
550 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
551 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
553 $aSearch['iSearchRank'] += 5;
555 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
558 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
560 if ($aSearch['fLat'] === '')
562 $aSearch['fLat'] = $aSearchTerm['lat'];
563 $aSearch['fLon'] = $aSearchTerm['lon'];
564 $aSearch['fRadius'] = $aSearchTerm['radius'];
565 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
568 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
570 if ($aSearch['sHouseNumber'] === '')
572 $aSearch['sHouseNumber'] = $sToken;
573 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
575 // Fall back to not searching for this item (better than nothing)
576 $aSearch = $aCurrentSearch;
577 $aSearch['iSearchRank'] += 1;
578 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
582 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
584 if ($aSearch['sClass'] === '')
586 $aSearch['sOperator'] = $aSearchTerm['operator'];
587 $aSearch['sClass'] = $aSearchTerm['class'];
588 $aSearch['sType'] = $aSearchTerm['type'];
589 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
590 else $aSearch['sOperator'] = 'near'; // near = in for the moment
592 // Do we have a shortcut id?
593 if ($aSearch['sOperator'] == 'name')
595 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
596 if ($iAmenityID = $oDB->getOne($sSQL))
598 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
599 $aSearch['aName'][$iAmenityID] = $iAmenityID;
600 $aSearch['sClass'] = '';
601 $aSearch['sType'] = '';
604 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
607 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
609 if (sizeof($aSearch['aName']))
611 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
613 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
617 $aSearch['iSearchRank'] += 1000; // skip;
622 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
623 // $aSearch['iNamePhrase'] = $iPhrase;
625 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
629 if (isset($aValidTokens[$sToken]))
631 // Allow searching for a word - but at extra cost
632 foreach($aValidTokens[$sToken] as $aSearchTerm)
634 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
636 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
638 $aSearch = $aCurrentSearch;
639 $aSearch['iSearchRank'] += 1;
640 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
641 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
643 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
644 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
647 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
649 $aSearch = $aCurrentSearch;
650 $aSearch['iSearchRank'] += 2;
651 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
652 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
653 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
655 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
656 $aSearch['iNamePhrase'] = $iPhrase;
657 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
664 // Allow skipping a word - but at EXTREAM cost
665 //$aSearch = $aCurrentSearch;
666 //$aSearch['iSearchRank']+=100;
667 //$aNewWordsetSearches[] = $aSearch;
671 usort($aNewWordsetSearches, 'bySearchRank');
672 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
674 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
676 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
677 usort($aNewPhraseSearches, 'bySearchRank');
679 $aSearchHash = array();
680 foreach($aNewPhraseSearches as $iSearch => $aSearch)
682 $sHash = serialize($aSearch);
683 if (isset($aSearchHash[$sHash]))
685 unset($aNewPhraseSearches[$iSearch]);
689 $aSearchHash[$sHash] = 1;
693 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
696 // Re-group the searches by their score, junk anything over 20 as just not worth trying
697 $aGroupedSearches = array();
698 foreach($aNewPhraseSearches as $aSearch)
700 if ($aSearch['iSearchRank'] < $iMaxRank)
702 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
703 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
706 ksort($aGroupedSearches);
709 $aSearches = array();
710 foreach($aGroupedSearches as $iScore => $aNewSearches)
712 $iSearchCount += sizeof($aNewSearches);
713 $aSearches = array_merge($aSearches, $aNewSearches);
714 if ($iSearchCount > 50) break;
717 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
723 // Re-group the searches by their score, junk anything over 20 as just not worth trying
724 $aGroupedSearches = array();
725 foreach($aSearches as $aSearch)
727 if ($aSearch['iSearchRank'] < $iMaxRank)
729 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
730 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
733 ksort($aGroupedSearches);
736 if (CONST_Debug) var_Dump($aGroupedSearches);
740 $aCopyGroupedSearches = $aGroupedSearches;
741 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
743 foreach($aSearches as $iSearch => $aSearch)
745 if (sizeof($aSearch['aAddress']))
747 $iReverseItem = array_pop($aSearch['aAddress']);
748 if (isset($aPossibleMainWordIDs[$iReverseItem]))
750 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
751 $aSearch['aName'] = array($iReverseItem);
752 $aGroupedSearches[$iGroup][] = $aSearch;
754 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
755 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
761 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
763 $aCopyGroupedSearches = $aGroupedSearches;
764 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
766 foreach($aSearches as $iSearch => $aSearch)
768 $aReductionsList = array($aSearch['aAddress']);
769 $iSearchRank = $aSearch['iSearchRank'];
770 while(sizeof($aReductionsList) > 0)
773 if ($iSearchRank > iMaxRank) break 3;
774 $aNewReductionsList = array();
775 foreach($aReductionsList as $aReductionsWordList)
777 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
779 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
780 $aReverseSearch = $aSearch;
781 $aSearch['aAddress'] = $aReductionsWordListResult;
782 $aSearch['iSearchRank'] = $iSearchRank;
783 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
784 if (sizeof($aReductionsWordListResult) > 0)
786 $aNewReductionsList[] = $aReductionsWordListResult;
790 $aReductionsList = $aNewReductionsList;
794 ksort($aGroupedSearches);
797 // Filter out duplicate searches
798 $aSearchHash = array();
799 foreach($aGroupedSearches as $iGroup => $aSearches)
801 foreach($aSearches as $iSearch => $aSearch)
803 $sHash = serialize($aSearch);
804 if (isset($aSearchHash[$sHash]))
806 unset($aGroupedSearches[$iGroup][$iSearch]);
807 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
811 $aSearchHash[$sHash] = 1;
816 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
820 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
823 foreach($aSearches as $aSearch)
827 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
828 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
831 // Must have a location term
832 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
834 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
836 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
838 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
839 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
840 $sSQL .= " order by st_area(geometry) desc limit 1";
841 if (CONST_Debug) var_dump($sSQL);
842 $aPlaceIDs = $oDB->getCol($sSQL);
847 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
848 if (!$aSearch['sClass']) continue;
849 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
850 if ($oDB->getOne($sSQL))
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($sViewboxSmallSQL, ct.centroid)";
855 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
856 if (sizeof($aExcludePlaceIDs))
858 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
860 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
861 $sSQL .= " limit $iLimit";
862 if (CONST_Debug) var_dump($sSQL);
863 $aPlaceIDs = $oDB->getCol($sSQL);
865 // If excluded place IDs are given, it is fair to assume that
866 // there have been results in the small box, so no further
867 // expansion in that case.
868 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
870 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
871 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
872 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
873 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
874 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
875 $sSQL .= " limit $iLimit";
876 if (CONST_Debug) var_dump($sSQL);
877 $aPlaceIDs = $oDB->getCol($sSQL);
882 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
883 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
884 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
885 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
886 $sSQL .= " limit $iLimit";
887 if (CONST_Debug) var_dump($sSQL);
888 $aPlaceIDs = $oDB->getCol($sSQL);
894 $aPlaceIDs = array();
896 // First we need a position, either aName or fLat or both
900 // TODO: filter out the pointless search terms (2 letter name tokens and less)
901 // they might be right - but they are just too darned expensive to run
902 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
903 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
905 // For infrequent name terms disable index usage for address
906 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
907 sizeof($aSearch['aName']) == 1 &&
908 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
910 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
914 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
917 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
918 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
919 if ($aSearch['fLon'] && $aSearch['fLat'])
921 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
922 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
924 if (sizeof($aExcludePlaceIDs))
926 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
928 if ($sCountryCodesSQL)
930 $aTerms[] = "country_code in ($sCountryCodesSQL)";
933 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
934 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
936 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end';
938 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
939 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
940 $aOrder[] = "$sImportanceSQL DESC";
944 $sSQL = "select place_id";
945 $sSQL .= " from search_name";
946 $sSQL .= " where ".join(' and ',$aTerms);
947 $sSQL .= " order by ".join(', ',$aOrder);
948 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
949 $sSQL .= " limit 50";
950 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
953 $sSQL .= " limit ".$iLimit;
955 if (CONST_Debug) { var_dump($sSQL); }
956 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
957 if (PEAR::IsError($aViewBoxPlaceIDs))
959 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
961 //var_dump($aViewBoxPlaceIDs);
962 // Did we have an viewbox matches?
963 $aPlaceIDs = array();
964 $bViewBoxMatch = false;
965 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
967 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
968 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
969 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
970 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
971 $aPlaceIDs[] = $aViewBoxRow['place_id'];
974 //var_Dump($aPlaceIDs);
977 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
979 $aRoadPlaceIDs = $aPlaceIDs;
980 $sPlaceIDs = join(',',$aPlaceIDs);
982 // Now they are indexed look for a house attached to a street we found
983 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
984 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
985 if (sizeof($aExcludePlaceIDs))
987 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
989 $sSQL .= " limit $iLimit";
990 if (CONST_Debug) var_dump($sSQL);
991 $aPlaceIDs = $oDB->getCol($sSQL);
993 // If not try the aux fallback table
994 if (!sizeof($aPlaceIDs))
996 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
997 if (sizeof($aExcludePlaceIDs))
999 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1001 // $sSQL .= " limit $iLimit";
1002 if (CONST_Debug) var_dump($sSQL);
1003 $aPlaceIDs = $oDB->getCol($sSQL);
1006 if (!sizeof($aPlaceIDs))
1008 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1009 if (sizeof($aExcludePlaceIDs))
1011 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1013 // $sSQL .= " limit $iLimit";
1014 if (CONST_Debug) var_dump($sSQL);
1015 $aPlaceIDs = $oDB->getCol($sSQL);
1018 // Fallback to the road
1019 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1021 $aPlaceIDs = $aRoadPlaceIDs;
1026 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1028 $sPlaceIDs = join(',',$aPlaceIDs);
1030 $aClassPlaceIDs = array();
1032 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1034 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1035 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1036 $sSQL .= " and linked_place_id is null";
1037 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1038 $sSQL .= " order by rank_search asc limit $iLimit";
1039 if (CONST_Debug) var_dump($sSQL);
1040 $aClassPlaceIDs = $oDB->getCol($sSQL);
1043 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1045 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1046 $bCacheTable = $oDB->getOne($sSQL);
1048 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1050 if (CONST_Debug) var_dump($sSQL);
1051 $iMaxRank = ((int)$oDB->getOne($sSQL));
1053 // For state / country level searches the normal radius search doesn't work very well
1054 $sPlaceGeom = false;
1055 if ($iMaxRank < 9 && $bCacheTable)
1057 // Try and get a polygon to search in instead
1058 $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";
1059 if (CONST_Debug) var_dump($sSQL);
1060 $sPlaceGeom = $oDB->getOne($sSQL);
1070 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1071 if (CONST_Debug) var_dump($sSQL);
1072 $aPlaceIDs = $oDB->getCol($sSQL);
1073 $sPlaceIDs = join(',',$aPlaceIDs);
1076 if ($sPlaceIDs || $sPlaceGeom)
1082 // More efficient - can make the range bigger
1086 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1087 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1088 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1090 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1091 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1094 $sSQL .= ",placex as f where ";
1095 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1100 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1102 if (sizeof($aExcludePlaceIDs))
1104 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1106 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1107 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1108 if ($iOffset) $sSQL .= " offset $iOffset";
1109 $sSQL .= " limit $iLimit";
1110 if (CONST_Debug) var_dump($sSQL);
1111 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1115 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1118 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1119 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1121 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1122 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1123 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1124 if (sizeof($aExcludePlaceIDs))
1126 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1128 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1129 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1130 if ($iOffset) $sSQL .= " offset $iOffset";
1131 $sSQL .= " limit $iLimit";
1132 if (CONST_Debug) var_dump($sSQL);
1133 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1138 $aPlaceIDs = $aClassPlaceIDs;
1144 if (PEAR::IsError($aPlaceIDs))
1146 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1149 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1151 foreach($aPlaceIDs as $iPlaceID)
1153 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1155 if ($iQueryLoop > 20) break;
1159 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1160 if ($iGroupLoop > 4) break;
1161 if ($iQueryLoop > 30) break;
1164 // Did we find anything?
1165 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1167 //var_Dump($aResultPlaceIDs);exit;
1168 // Get the details for display (is this a redundant extra step?)
1169 $sPlaceIDs = join(',',$aResultPlaceIDs);
1170 $sOrderSQL = 'CASE ';
1171 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1173 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1175 $sOrderSQL .= ' ELSE 10000000 END';
1176 $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,";
1177 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1178 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1179 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1180 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1181 // $sSQL .= $sOrderSQL." as porder, ";
1182 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1183 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1184 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1185 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1186 $sSQL .= "and linked_place_id is null ";
1187 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1188 if (!$bDeDupe) $sSQL .= ",place_id";
1189 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1190 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1191 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1193 $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,";
1194 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1195 $sSQL .= "null as placename,";
1196 $sSQL .= "null as ref,";
1197 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1198 // $sSQL .= $sOrderSQL." as porder, ";
1199 $sSQL .= "-0.15 as importance ";
1200 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1201 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1202 $sSQL .= "group by place_id";
1203 if (!$bDeDupe) $sSQL .= ",place_id";
1205 $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,";
1206 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1207 $sSQL .= "null as placename,";
1208 $sSQL .= "null as ref,";
1209 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1210 // $sSQL .= $sOrderSQL." as porder, ";
1211 $sSQL .= "-0.10 as importance ";
1212 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1213 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1214 $sSQL .= "group by place_id";
1215 if (!$bDeDupe) $sSQL .= ",place_id";
1216 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1217 $sSQL .= "order by importance desc";
1218 // $sSQL .= "order by rank_search,rank_address,porder asc";
1219 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1220 $aSearchResults = $oDB->getAll($sSQL);
1221 //var_dump($sSQL,$aSearchResults);exit;
1223 if (PEAR::IsError($aSearchResults))
1225 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1228 } // end if ($sQuery)
1231 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1233 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1234 $aResultPlaceIDs = array($iPlaceID);
1236 // TODO: this needs refactoring!
1238 // Get the details for display (is this a redundant extra step?)
1239 $sPlaceIDs = join(',',$aResultPlaceIDs);
1240 $sOrderSQL = 'CASE ';
1241 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1243 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1245 $sOrderSQL .= ' ELSE 10000000 END';
1246 $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,";
1247 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1248 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1249 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1250 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1251 // $sSQL .= $sOrderSQL." as porder, ";
1252 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1253 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1254 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1255 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1256 if (!$bDeDupe) $sSQL .= ",place_id";
1257 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1258 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1259 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1261 $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,";
1262 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1263 $sSQL .= "null as placename,";
1264 $sSQL .= "null as ref,";
1265 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1266 // $sSQL .= $sOrderSQL." as porder, ";
1267 $sSQL .= "-0.15 as importance ";
1268 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1269 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1270 $sSQL .= "group by place_id";
1271 if (!$bDeDupe) $sSQL .= ",place_id";
1273 $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,";
1274 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1275 $sSQL .= "null as placename,";
1276 $sSQL .= "null as ref,";
1277 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1278 // $sSQL .= $sOrderSQL." as porder, ";
1279 $sSQL .= "-0.10 as importance ";
1280 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1281 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1282 $sSQL .= "group by place_id";
1283 if (!$bDeDupe) $sSQL .= ",place_id";
1284 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1285 $sSQL .= "order by importance desc";
1286 // $sSQL .= "order by rank_search,rank_address,porder asc";
1287 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1288 $aSearchResults = $oDB->getAll($sSQL);
1289 //var_dump($sSQL,$aSearchResults);exit;
1291 if (PEAR::IsError($aSearchResults))
1293 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1299 $sSearchResult = '';
1300 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1302 $sSearchResult = 'No Results Found';
1304 //var_Dump($aSearchResults);
1306 $aClassType = getClassTypesWithImportance();
1307 $aRecheckWords = preg_split('/\b/',$sQuery);
1308 foreach($aRecheckWords as $i => $sWord)
1310 if (!$sWord) unset($aRecheckWords[$i]);
1312 foreach($aSearchResults as $iResNum => $aResult)
1314 if (CONST_Search_AreaPolygons)
1316 // Get the bounding box and outline polygon
1317 $sSQL = "select place_id,numfeatures,area,outline,";
1318 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1319 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1320 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1322 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1323 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1324 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1325 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1326 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1327 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1328 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1329 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1330 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1331 $aPointPolygon = $oDB->getRow($sSQL);
1332 if (PEAR::IsError($aPointPolygon))
1334 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1336 if ($aPointPolygon['place_id'])
1338 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1339 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1340 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1341 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1343 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1344 $aResult['lat'] = $aPointPolygon['centrelat'];
1345 $aResult['lon'] = $aPointPolygon['centrelon'];
1349 // Translate geometary string to point array
1350 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1352 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1354 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1356 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1358 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1361 $iSteps = ($fRadius * 40000)^2;
1362 $fStepSize = (2*pi())/$iSteps;
1363 $aPolyPoints = array();
1364 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1366 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1368 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1369 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1370 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1371 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1375 // Output data suitable for display (points and a bounding box)
1376 if ($bShowPolygons && isset($aPolyPoints))
1378 $aResult['aPolyPoints'] = array();
1379 foreach($aPolyPoints as $aPoint)
1381 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1384 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1388 if (!isset($aResult['aBoundingBox']))
1391 $fDiameter = 0.0001;
1393 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1394 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1396 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1398 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1399 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1401 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1403 $fRadius = $fDiameter / 2;
1405 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1406 $fStepSize = (2*pi())/$iSteps;
1407 $aPolyPoints = array();
1408 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1410 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1412 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1413 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1414 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1415 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1417 // Output data suitable for display (points and a bounding box)
1420 $aResult['aPolyPoints'] = array();
1421 foreach($aPolyPoints as $aPoint)
1423 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1426 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1429 // Is there an icon set for this type of result?
1430 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1431 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1433 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1436 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1437 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1439 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1442 if ($bShowAddressDetails)
1444 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1445 //var_dump($aResult['address']);
1449 // Adjust importance for the number of exact string matches in the result
1450 $aResult['importance'] = max(0.001,$aResult['importance']);
1452 $sAddress = $aResult['langaddress'];
1453 foreach($aRecheckWords as $i => $sWord)
1455 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1457 $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
1459 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1461 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1462 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1464 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1466 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1467 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1469 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1473 $aResult['importance'] = 1000000000000000;
1476 $aResult['name'] = $aResult['langaddress'];
1477 $aResult['foundorder'] = $iResNum;
1478 $aSearchResults[$iResNum] = $aResult;
1480 uasort($aSearchResults, 'byImportance');
1482 $aOSMIDDone = array();
1483 $aClassTypeNameDone = array();
1484 $aToFilter = $aSearchResults;
1485 $aSearchResults = array();
1488 foreach($aToFilter as $iResNum => $aResult)
1490 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1491 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1494 $fLat = $aResult['lat'];
1495 $fLon = $aResult['lon'];
1496 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1499 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1500 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1502 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1503 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1504 $aSearchResults[] = $aResult;
1507 // Absolute limit on number of results
1508 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1511 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1513 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1515 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1520 logEnd($oDB, $hLog, sizeof($aToFilter));
1522 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1523 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1524 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1525 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1526 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1527 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1530 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1532 $sMoreURL .= '&q='.urlencode($sQuery);
1534 if (CONST_Debug) exit;
1536 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');