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 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
172 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
174 // Hack to make it handle "new york, ny" (and variants) correctly
175 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
176 if (isset($aLangPrefOrder['name:en']))
178 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
179 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
180 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
183 // If we have a view box create the SQL
184 // Small is the actual view box, Large is double (on each axis) that
185 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
186 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
188 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
189 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
191 if (isset($_GET['viewbox']) && $_GET['viewbox'])
193 $aCoOrdinates = explode(',',$_GET['viewbox']);
194 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
195 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
196 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
197 $aCoOrdinates[0] += $fHeight;
198 $aCoOrdinates[2] -= $fHeight;
199 $aCoOrdinates[1] += $fWidth;
200 $aCoOrdinates[3] -= $fWidth;
201 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
203 $bBoundingBoxSearch = false;
205 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
207 $aPoints = explode(',',$_GET['route']);
208 if (sizeof($aPoints) % 2 != 0)
210 userError("Uneven number of points");
213 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
215 foreach($aPoints as $i => $fPoint)
219 if ($i != 1) $sViewboxCentreSQL .= ",";
220 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
224 $fPrevCoord = (float)$fPoint;
227 $sViewboxCentreSQL .= ")'::geometry,4326)";
229 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
230 $sViewboxSmallSQL = $oDB->getOne($sSQL);
231 if (PEAR::isError($sViewboxSmallSQL))
233 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
235 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
237 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
238 $sViewboxLargeSQL = $oDB->getOne($sSQL);
239 if (PEAR::isError($sViewboxLargeSQL))
241 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
243 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
244 $bBoundingBoxSearch = true;
247 // Do we have anything that looks like a lat/lon pair?
248 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
250 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
251 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
252 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
254 $_GET['nearlat'] = $fQueryLat;
255 $_GET['nearlon'] = $fQueryLon;
256 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
259 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
261 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
262 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
263 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
265 $_GET['nearlat'] = $fQueryLat;
266 $_GET['nearlon'] = $fQueryLon;
267 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
270 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
272 $fQueryLat = $aData[2];
273 $fQueryLon = $aData[3];
274 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
276 $_GET['nearlat'] = $fQueryLat;
277 $_GET['nearlon'] = $fQueryLon;
278 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
282 if ($sQuery || $aStructuredQuery)
284 // Start with a blank search
286 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
287 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
290 $sNearPointSQL = false;
291 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
293 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
294 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
295 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
296 $aSearches[0]['fRadius'] = 0.1;
299 $bSpecialTerms = false;
300 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
301 $aSpecialTerms = array();
302 foreach($aSpecialTermsRaw as $aSpecialTerm)
304 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
305 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
308 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
309 $aSpecialTerms = array();
310 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
312 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
313 unset($aStructuredQuery['amenity']);
315 foreach($aSpecialTermsRaw as $aSpecialTerm)
317 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
318 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
319 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
320 $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';
321 if (CONST_Debug) var_Dump($sSQL);
322 $aSearchWords = $oDB->getAll($sSQL);
323 $aNewSearches = array();
324 foreach($aSearches as $aSearch)
326 foreach($aSearchWords as $aSearchTerm)
328 $aNewSearch = $aSearch;
329 if ($aSearchTerm['country_code'])
331 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
332 $aNewSearches[] = $aNewSearch;
333 $bSpecialTerms = true;
335 if ($aSearchTerm['class'])
337 $aNewSearch['sClass'] = $aSearchTerm['class'];
338 $aNewSearch['sType'] = $aSearchTerm['type'];
339 $aNewSearches[] = $aNewSearch;
340 $bSpecialTerms = true;
344 $aSearches = $aNewSearches;
347 // Split query into phrases
348 // Commas are used to reduce the search space by indicating where phrases split
349 if (sizeof($aStructuredQuery) > 0)
351 $aPhrases = $aStructuredQuery;
352 $bStructuredPhrases = true;
356 $aPhrases = explode(',',$sQuery);
357 $bStructuredPhrases = false;
361 // Convert each phrase to standard form
362 // Create a list of standard words
363 // Get all 'sets' of words
364 // Generate a complete list of all
366 foreach($aPhrases as $iPhrase => $sPhrase)
368 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
369 if (PEAR::isError($aPhrase))
371 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
372 if (CONST_Debug) var_dump($aPhrase);
375 if (trim($aPhrase['string']))
377 $aPhrases[$iPhrase] = $aPhrase;
378 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
379 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
380 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
384 unset($aPhrases[$iPhrase]);
388 // reindex phrases - we make assumptions later on
389 $aPhraseTypes = array_keys($aPhrases);
390 $aPhrases = array_values($aPhrases);
392 if (sizeof($aTokens))
395 // Check which tokens we have, get the ID numbers
396 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator, search_name_count';
397 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
398 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
399 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
401 if (CONST_Debug) var_Dump($sSQL);
403 $aValidTokens = array();
404 if (sizeof($aTokens))
405 $aDatabaseWords = $oDB->getAll($sSQL);
407 $aDatabaseWords = array();
408 if (PEAR::IsError($aDatabaseWords))
410 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
412 $aPossibleMainWordIDs = array();
413 foreach($aDatabaseWords as $aToken)
415 if (isset($aValidTokens[$aToken['word_token']]))
417 $aValidTokens[$aToken['word_token']][] = $aToken;
421 $aValidTokens[$aToken['word_token']] = array($aToken);
423 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1 + $aToken['search_name_count'];
425 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
427 $aSuggestion = array();
428 $bSuggestion = false;
429 if (CONST_Suggestions_Enabled)
431 foreach($aPhrases as $iPhrase => $aPhrase)
433 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
435 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
436 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
437 $aRow = $aSuggestionWords[0];
438 if ($aRow && $aRow['word'])
440 $aSuggestion[] = $aRow['word'];
445 $aSuggestion[] = $aPhrase['string'];
450 $aSuggestion[] = $aPhrase['string'];
454 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
456 // Try and calculate GB postcodes we might be missing
457 foreach($aTokens as $sToken)
459 // Source of gb postcodes is now definitive - always use
460 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
462 if (substr($aData[1],-2,1) != ' ')
464 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
465 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
467 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
468 if ($aGBPostcodeLocation)
470 $aValidTokens[$sToken] = $aGBPostcodeLocation;
475 foreach($aTokens as $sToken)
477 // Unknown single word token with a number - assume it is a house number
478 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
480 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
484 // Any words that have failed completely?
487 // Start the search process
488 $aResultPlaceIDs = array();
491 Calculate all searches using aValidTokens i.e.
493 'Wodsworth Road, Sheffield' =>
497 0 1 (wodsworth)(road)
500 Score how good the search is so they can be ordered
502 foreach($aPhrases as $iPhrase => $sPhrase)
504 $aNewPhraseSearches = array();
505 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
506 else $sPhraseType = '';
508 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
510 $aWordsetSearches = $aSearches;
512 // Add all words from this wordset
513 foreach($aWordset as $iToken => $sToken)
515 //echo "<br><b>$sToken</b>";
516 $aNewWordsetSearches = array();
518 foreach($aWordsetSearches as $aCurrentSearch)
521 //var_dump($aCurrentSearch);
524 // If the token is valid
525 if (isset($aValidTokens[' '.$sToken]))
527 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
529 $aSearch = $aCurrentSearch;
530 $aSearch['iSearchRank']++;
531 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
533 if ($aSearch['sCountryCode'] === false)
535 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
536 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
537 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
538 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
541 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
543 if ($aSearch['fLat'] === '')
545 $aSearch['fLat'] = $aSearchTerm['lat'];
546 $aSearch['fLon'] = $aSearchTerm['lon'];
547 $aSearch['fRadius'] = $aSearchTerm['radius'];
548 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
551 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
553 if ($aSearch['sHouseNumber'] === '')
555 $aSearch['sHouseNumber'] = $sToken;
556 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
558 // Fall back to not searching for this item (better than nothing)
559 $aSearch = $aCurrentSearch;
560 $aSearch['iSearchRank'] += 1;
561 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
565 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
567 if ($aSearch['sClass'] === '')
569 $aSearch['sOperator'] = $aSearchTerm['operator'];
570 $aSearch['sClass'] = $aSearchTerm['class'];
571 $aSearch['sType'] = $aSearchTerm['type'];
572 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
573 else $aSearch['sOperator'] = 'near'; // near = in for the moment
575 // Do we have a shortcut id?
576 if ($aSearch['sOperator'] == 'name')
578 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
579 if ($iAmenityID = $oDB->getOne($sSQL))
581 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
582 $aSearch['aName'][$iAmenityID] = $iAmenityID;
583 $aSearch['sClass'] = '';
584 $aSearch['sType'] = '';
587 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
590 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
592 if (sizeof($aSearch['aName']))
594 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
596 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
600 $aSearch['iSearchRank'] += 1000; // skip;
605 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
606 // $aSearch['iNamePhrase'] = $iPhrase;
608 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
612 if (isset($aValidTokens[$sToken]))
614 // Allow searching for a word - but at extra cost
615 foreach($aValidTokens[$sToken] as $aSearchTerm)
617 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
619 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
621 $aSearch = $aCurrentSearch;
622 $aSearch['iSearchRank'] += 1;
623 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
624 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
627 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
629 $aSearch = $aCurrentSearch;
630 $aSearch['iSearchRank'] += 2;
631 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
632 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
633 $aSearch['iNamePhrase'] = $iPhrase;
634 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
641 // Allow skipping a word - but at EXTREAM cost
642 //$aSearch = $aCurrentSearch;
643 //$aSearch['iSearchRank']+=100;
644 //$aNewWordsetSearches[] = $aSearch;
648 usort($aNewWordsetSearches, 'bySearchRank');
649 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
651 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
653 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
654 usort($aNewPhraseSearches, 'bySearchRank');
656 $aSearchHash = array();
657 foreach($aNewPhraseSearches as $iSearch => $aSearch)
659 $sHash = serialize($aSearch);
660 if (isset($aSearchHash[$sHash]))
662 unset($aNewPhraseSearches[$iSearch]);
666 $aSearchHash[$sHash] = 1;
670 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
673 // Re-group the searches by their score, junk anything over 20 as just not worth trying
674 $aGroupedSearches = array();
675 foreach($aNewPhraseSearches as $aSearch)
677 if ($aSearch['iSearchRank'] < $iMaxRank)
679 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
680 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
683 ksort($aGroupedSearches);
686 $aSearches = array();
687 foreach($aGroupedSearches as $iScore => $aNewSearches)
689 $iSearchCount += sizeof($aNewSearches);
690 $aSearches = array_merge($aSearches, $aNewSearches);
691 if ($iSearchCount > 50) break;
694 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
700 // Re-group the searches by their score, junk anything over 20 as just not worth trying
701 $aGroupedSearches = array();
702 foreach($aSearches as $aSearch)
704 if ($aSearch['iSearchRank'] < $iMaxRank)
706 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
707 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
710 ksort($aGroupedSearches);
713 if (CONST_Debug) var_Dump($aGroupedSearches);
717 $aCopyGroupedSearches = $aGroupedSearches;
718 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
720 foreach($aSearches as $iSearch => $aSearch)
722 if (sizeof($aSearch['aAddress']))
724 $iReverseItem = array_pop($aSearch['aAddress']);
725 if (isset($aPossibleMainWordIDs[$iReverseItem]))
727 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
728 $aSearch['aName'] = array($iReverseItem);
729 $aGroupedSearches[$iGroup][] = $aSearch;
731 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
732 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
738 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
740 $aCopyGroupedSearches = $aGroupedSearches;
741 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
743 foreach($aSearches as $iSearch => $aSearch)
745 $aReductionsList = array($aSearch['aAddress']);
746 $iSearchRank = $aSearch['iSearchRank'];
747 while(sizeof($aReductionsList) > 0)
750 if ($iSearchRank > iMaxRank) break 3;
751 $aNewReductionsList = array();
752 foreach($aReductionsList as $aReductionsWordList)
754 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
756 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
757 $aReverseSearch = $aSearch;
758 $aSearch['aAddress'] = $aReductionsWordListResult;
759 $aSearch['iSearchRank'] = $iSearchRank;
760 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
761 if (sizeof($aReductionsWordListResult) > 0)
763 $aNewReductionsList[] = $aReductionsWordListResult;
767 $aReductionsList = $aNewReductionsList;
771 ksort($aGroupedSearches);
774 // Filter out duplicate searches
775 $aSearchHash = array();
776 foreach($aGroupedSearches as $iGroup => $aSearches)
778 foreach($aSearches as $iSearch => $aSearch)
780 $sHash = serialize($aSearch);
781 if (isset($aSearchHash[$sHash]))
783 unset($aGroupedSearches[$iGroup][$iSearch]);
784 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
788 $aSearchHash[$sHash] = 1;
793 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
797 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
800 foreach($aSearches as $aSearch)
804 // Must have a location term
805 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
807 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
809 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
811 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
812 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
813 $sSQL .= " order by st_area(geometry) desc limit 1";
814 $aPlaceIDs = $oDB->getCol($sSQL);
819 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
820 if (!$aSearch['sClass']) continue;
821 if (CONST_Debug) var_dump('<hr>',$aSearch);
822 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
823 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
824 if ($oDB->getOne($sSQL))
826 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
827 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
828 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
829 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
830 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
831 $sSQL .= " limit $iLimit";
832 if (CONST_Debug) var_dump($sSQL);
833 $aPlaceIDs = $oDB->getCol($sSQL);
835 if (!sizeof($aPlaceIDs))
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($sViewboxLargeSQL, ct.centroid)";
840 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
841 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
842 $sSQL .= " limit $iLimit";
843 if (CONST_Debug) var_dump($sSQL);
844 $aPlaceIDs = $oDB->getCol($sSQL);
849 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
850 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
851 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
852 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
853 $sSQL .= " limit $iLimit";
854 if (CONST_Debug) var_dump($sSQL);
855 $aPlaceIDs = $oDB->getCol($sSQL);
861 if (CONST_Debug) var_dump('<hr>',$aSearch);
862 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
863 $aPlaceIDs = array();
865 // First we need a position, either aName or fLat or both
869 // TODO: filter out the pointless search terms (2 letter name tokens and less)
870 // they might be right - but they are just too darned expensive to run
871 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
872 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
874 // For infrequent name terms disable index usage for address
875 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
876 sizeof($aSearch['aName']) == 1 &&
877 $aPossibleMainWordIDs[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
879 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
883 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
886 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
887 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
888 if ($aSearch['fLon'] && $aSearch['fLat'])
890 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
891 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
893 if (sizeof($aExcludePlaceIDs))
895 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
897 if ($sCountryCodesSQL)
899 $aTerms[] = "country_code in ($sCountryCodesSQL)";
902 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
903 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
905 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end';
907 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
908 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
909 $aOrder[] = "$sImportanceSQL DESC";
913 $sSQL = "select place_id";
914 $sSQL .= " from search_name";
915 $sSQL .= " where ".join(' and ',$aTerms);
916 $sSQL .= " order by ".join(', ',$aOrder);
917 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
918 $sSQL .= " limit 50";
919 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
922 $sSQL .= " limit ".$iLimit;
924 if (CONST_Debug) var_dump($sSQL);
925 $iStartTime = time();
926 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
927 if (PEAR::IsError($aViewBoxPlaceIDs))
929 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
931 if (time() - $iStartTime > 60) {
932 file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
935 //var_dump($aViewBoxPlaceIDs);
936 // Did we have an viewbox matches?
937 $aPlaceIDs = array();
938 $bViewBoxMatch = false;
939 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
941 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
942 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
943 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
944 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
945 $aPlaceIDs[] = $aViewBoxRow['place_id'];
948 //var_Dump($aPlaceIDs);
951 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
953 $aRoadPlaceIDs = $aPlaceIDs;
954 $sPlaceIDs = join(',',$aPlaceIDs);
956 // Now they are indexed look for a house attached to a street we found
957 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
958 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
959 if (sizeof($aExcludePlaceIDs))
961 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
963 $sSQL .= " limit $iLimit";
964 if (CONST_Debug) var_dump($sSQL);
965 $aPlaceIDs = $oDB->getCol($sSQL);
967 // If not try the aux fallback table
968 if (!sizeof($aPlaceIDs))
970 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
971 if (sizeof($aExcludePlaceIDs))
973 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
975 // $sSQL .= " limit $iLimit";
976 if (CONST_Debug) var_dump($sSQL);
977 $aPlaceIDs = $oDB->getCol($sSQL);
980 if (!sizeof($aPlaceIDs))
982 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
983 if (sizeof($aExcludePlaceIDs))
985 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
987 // $sSQL .= " limit $iLimit";
988 if (CONST_Debug) var_dump($sSQL);
989 $aPlaceIDs = $oDB->getCol($sSQL);
992 // Fallback to the road
993 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
995 $aPlaceIDs = $aRoadPlaceIDs;
1000 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1002 $sPlaceIDs = join(',',$aPlaceIDs);
1004 $aClassPlaceIDs = array();
1006 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1008 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1009 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1010 $sSQL .= " and linked_place_id is null";
1011 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
1012 $sSQL .= " order by rank_search asc limit $iLimit";
1013 if (CONST_Debug) var_dump($sSQL);
1014 $aClassPlaceIDs = $oDB->getCol($sSQL);
1017 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1019 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1020 $bCacheTable = $oDB->getOne($sSQL);
1022 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1024 if (CONST_Debug) var_dump($sSQL);
1025 $iMaxRank = ((int)$oDB->getOne($sSQL));
1027 // For state / country level searches the normal radius search doesn't work very well
1028 $sPlaceGeom = false;
1029 if ($iMaxRank < 9 && $bCacheTable)
1031 // Try and get a polygon to search in instead
1032 $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";
1033 if (CONST_Debug) var_dump($sSQL);
1034 $sPlaceGeom = $oDB->getOne($sSQL);
1044 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1045 if (CONST_Debug) var_dump($sSQL);
1046 $aPlaceIDs = $oDB->getCol($sSQL);
1047 $sPlaceIDs = join(',',$aPlaceIDs);
1050 if ($sPlaceIDs || $sPlaceGeom)
1056 // More efficient - can make the range bigger
1060 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1061 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1062 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1064 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1065 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1068 $sSQL .= ",placex as f where ";
1069 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1074 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1076 if (sizeof($aExcludePlaceIDs))
1078 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1080 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1081 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1082 if ($iOffset) $sSQL .= " offset $iOffset";
1083 $sSQL .= " limit $iLimit";
1084 if (CONST_Debug) var_dump($sSQL);
1085 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1089 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1092 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1093 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1095 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1096 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1097 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1098 if (sizeof($aExcludePlaceIDs))
1100 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1102 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1103 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1104 if ($iOffset) $sSQL .= " offset $iOffset";
1105 $sSQL .= " limit $iLimit";
1106 if (CONST_Debug) var_dump($sSQL);
1107 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1112 $aPlaceIDs = $aClassPlaceIDs;
1118 if (PEAR::IsError($aPlaceIDs))
1120 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1123 if (CONST_Debug) var_Dump($aPlaceIDs);
1125 foreach($aPlaceIDs as $iPlaceID)
1127 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1129 if ($iQueryLoop > 20) break;
1133 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1134 if ($iGroupLoop > 4) break;
1135 if ($iQueryLoop > 30) break;
1138 // Did we find anything?
1139 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1141 //var_Dump($aResultPlaceIDs);exit;
1142 // Get the details for display (is this a redundant extra step?)
1143 $sPlaceIDs = join(',',$aResultPlaceIDs);
1144 $sOrderSQL = 'CASE ';
1145 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1147 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1149 $sOrderSQL .= ' ELSE 10000000 END';
1150 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1151 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1152 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1153 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1154 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1155 // $sSQL .= $sOrderSQL." as porder, ";
1156 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1157 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1158 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1159 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1160 $sSQL .= "and linked_place_id is null ";
1161 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1162 if (!$bDeDupe) $sSQL .= ",place_id";
1163 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1164 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1165 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1167 $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,";
1168 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1169 $sSQL .= "null as placename,";
1170 $sSQL .= "null as ref,";
1171 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1172 // $sSQL .= $sOrderSQL." as porder, ";
1173 $sSQL .= "-0.15 as importance ";
1174 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1175 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1176 $sSQL .= "group by place_id";
1177 if (!$bDeDupe) $sSQL .= ",place_id";
1179 $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,";
1180 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1181 $sSQL .= "null as placename,";
1182 $sSQL .= "null as ref,";
1183 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1184 // $sSQL .= $sOrderSQL." as porder, ";
1185 $sSQL .= "-0.10 as importance ";
1186 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1187 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1188 $sSQL .= "group by place_id";
1189 if (!$bDeDupe) $sSQL .= ",place_id";
1190 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1191 $sSQL .= "order by importance desc";
1192 // $sSQL .= "order by rank_search,rank_address,porder asc";
1193 if (CONST_Debug) var_dump('<hr>',$sSQL);
1194 $aSearchResults = $oDB->getAll($sSQL);
1195 //var_dump($sSQL,$aSearchResults);exit;
1197 if (PEAR::IsError($aSearchResults))
1199 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1202 } // end if ($sQuery)
1205 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1207 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1208 $aResultPlaceIDs = array($iPlaceID);
1210 // TODO: this needs refactoring!
1212 // Get the details for display (is this a redundant extra step?)
1213 $sPlaceIDs = join(',',$aResultPlaceIDs);
1214 $sOrderSQL = 'CASE ';
1215 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1217 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1219 $sOrderSQL .= ' ELSE 10000000 END';
1220 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1221 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1222 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1223 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1224 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1225 // $sSQL .= $sOrderSQL." as porder, ";
1226 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1227 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1228 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1229 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1230 if (!$bDeDupe) $sSQL .= ",place_id";
1231 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1232 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1233 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1235 $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,";
1236 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1237 $sSQL .= "null as placename,";
1238 $sSQL .= "null as ref,";
1239 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1240 // $sSQL .= $sOrderSQL." as porder, ";
1241 $sSQL .= "-0.15 as importance ";
1242 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1243 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1244 $sSQL .= "group by place_id";
1245 if (!$bDeDupe) $sSQL .= ",place_id";
1247 $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,";
1248 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1249 $sSQL .= "null as placename,";
1250 $sSQL .= "null as ref,";
1251 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1252 // $sSQL .= $sOrderSQL." as porder, ";
1253 $sSQL .= "-0.10 as importance ";
1254 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1255 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1256 $sSQL .= "group by place_id";
1257 if (!$bDeDupe) $sSQL .= ",place_id";
1258 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1259 $sSQL .= "order by importance desc";
1260 // $sSQL .= "order by rank_search,rank_address,porder asc";
1261 if (CONST_Debug) var_dump('<hr>',$sSQL);
1262 $aSearchResults = $oDB->getAll($sSQL);
1263 //var_dump($sSQL,$aSearchResults);exit;
1265 if (PEAR::IsError($aSearchResults))
1267 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1273 $sSearchResult = '';
1274 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1276 $sSearchResult = 'No Results Found';
1278 //var_Dump($aSearchResults);
1280 $aClassType = getClassTypesWithImportance();
1281 $aRecheckWords = preg_split('/\b/',$sQuery);
1282 foreach($aRecheckWords as $i => $sWord)
1284 if (!$sWord) unset($aRecheckWords[$i]);
1286 foreach($aSearchResults as $iResNum => $aResult)
1288 if (CONST_Search_AreaPolygons)
1290 // Get the bounding box and outline polygon
1291 $sSQL = "select place_id,numfeatures,area,outline,";
1292 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1293 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1294 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1296 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1297 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1298 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1299 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1300 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1301 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1302 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1303 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1304 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1305 $aPointPolygon = $oDB->getRow($sSQL);
1306 if (PEAR::IsError($aPointPolygon))
1308 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1310 if ($aPointPolygon['place_id'])
1312 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1313 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1314 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1315 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1317 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1318 $aResult['lat'] = $aPointPolygon['centrelat'];
1319 $aResult['lon'] = $aPointPolygon['centrelon'];
1323 // Translate geometary string to point array
1324 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1326 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1328 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1330 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1332 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1335 $iSteps = ($fRadius * 40000)^2;
1336 $fStepSize = (2*pi())/$iSteps;
1337 $aPolyPoints = array();
1338 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1340 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1342 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1343 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1344 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1345 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1349 // Output data suitable for display (points and a bounding box)
1350 if ($bShowPolygons && isset($aPolyPoints))
1352 $aResult['aPolyPoints'] = array();
1353 foreach($aPolyPoints as $aPoint)
1355 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1358 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1362 if (!isset($aResult['aBoundingBox']))
1365 $fDiameter = 0.0001;
1367 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1368 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1370 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1372 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1373 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1375 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1377 $fRadius = $fDiameter / 2;
1379 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1380 $fStepSize = (2*pi())/$iSteps;
1381 $aPolyPoints = array();
1382 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1384 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1386 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1387 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1388 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1389 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1391 // Output data suitable for display (points and a bounding box)
1394 $aResult['aPolyPoints'] = array();
1395 foreach($aPolyPoints as $aPoint)
1397 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1400 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1403 // Is there an icon set for this type of result?
1404 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1405 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1407 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1410 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1411 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1413 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1416 if ($bShowAddressDetails)
1418 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1419 //var_dump($aResult['address']);
1423 // Adjust importance for the number of exact string matches in the result
1424 $aResult['importance'] = max(0.001,$aResult['importance']);
1426 $sAddress = $aResult['langaddress'];
1427 foreach($aRecheckWords as $i => $sWord)
1429 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1431 $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
1433 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1435 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1436 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1438 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1440 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1441 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1443 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1447 $aResult['importance'] = 1000000000000000;
1450 $aResult['name'] = $aResult['langaddress'];
1451 $aResult['foundorder'] = $iResNum;
1452 $aSearchResults[$iResNum] = $aResult;
1454 uasort($aSearchResults, 'byImportance');
1456 $aOSMIDDone = array();
1457 $aClassTypeNameDone = array();
1458 $aToFilter = $aSearchResults;
1459 $aSearchResults = array();
1462 foreach($aToFilter as $iResNum => $aResult)
1464 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1465 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1468 $fLat = $aResult['lat'];
1469 $fLon = $aResult['lon'];
1470 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1473 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1474 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1476 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1477 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1478 $aSearchResults[] = $aResult;
1481 // Absolute limit on number of results
1482 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1485 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1487 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1489 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1494 logEnd($oDB, $hLog, sizeof($aToFilter));
1496 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1497 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1498 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1499 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1500 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1501 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1504 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1506 $sMoreURL .= '&q='.urlencode($sQuery);
1508 if (CONST_Debug) exit;
1510 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');