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');
11 $fLat = CONST_Default_Lat;
12 $fLon = CONST_Default_Lon;
13 $iZoom = CONST_Default_Zoom;
14 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
15 $sOutputFormat = 'html';
16 $aSearchResults = array();
17 $aExcludePlaceIDs = array();
18 $sCountryCodesSQL = false;
19 $sSuggestion = $sSuggestionURL = false;
20 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
21 $bReverseInPlan = false;
22 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
23 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
25 if ($iFinalLimit > 50) $iFinalLimit = 50;
26 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
28 $iMaxAddressRank = 30;
31 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
33 $sOutputFormat = $_GET['format'];
36 // Show / use polygons
37 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
38 if ($sOutputFormat == 'html') {
39 $bAsText = $bShowPolygons;
40 $bShowPolygons = false;
45 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
46 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
47 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
48 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
49 if ((($bShowPolygons?1:0)
54 ) > CONST_PolygonOutput_MaximumTypes) {
55 if (CONST_PolygonOutput_MaximumTypes) {
56 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
58 userError("Polygon output is disabled");
64 // Show address breakdown
65 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
68 $aLangPrefOrder = getPreferredLanguages();
69 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
70 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
71 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
73 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
75 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
77 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
79 $iExcludedPlaceID = (int)$iExcludedPlaceID;
80 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
84 // Only certain ranks of feature
85 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
87 if (isset($_GET['featuretype']))
89 switch($_GET['featuretype'])
92 $iMinAddressRank = $iMaxAddressRank = 4;
95 $iMinAddressRank = $iMaxAddressRank = 8;
98 $iMinAddressRank = 14;
99 $iMaxAddressRank = 16;
102 $iMinAddressRank = 8;
103 $iMaxAddressRank = 20;
108 if (isset($_GET['countrycodes']))
110 $aCountryCodes = array();
111 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
113 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
115 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
118 $sCountryCodesSQL = join(',', $aCountryCodes);
122 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
123 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
125 $sQuery = substr($_SERVER['PATH_INFO'], 1);
127 // reverse order of '/' separated string
128 $aPhrases = explode('/', $sQuery);
129 $aPhrases = array_reverse($aPhrases);
130 $sQuery = join(', ',$aPhrases);
133 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
135 if (!isset($_GET[$sKey])) return false;
136 $sValue = trim($_GET[$sKey]);
137 if (!$sValue) return false;
138 $aStructuredQuery[$sKey] = $sValue;
139 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
140 $iMinAddressRank = $iNewMinAddressRank;
141 $iMaxAddressRank = $iNewMaxAddressRank;
147 $aStructuredOptions = array(
148 array('amenity', 26, 30),
149 array('street', 26, 30),
150 array('city', 14, 24),
151 array('county', 9, 13),
152 array('state', 8, 8),
153 array('country', 4, 4),
154 array('postalcode', 16, 25),
156 $aStructuredQuery = array();
157 foreach($aStructuredOptions as $aStructuredOption)
159 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
161 if (sizeof($aStructuredQuery) > 0) {
162 $sQuery = join(', ', $aStructuredQuery);
167 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
169 // Hack to make it handle "new york, ny" (and variants) correctly
170 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
171 if (isset($aLangPrefOrder['name:en']))
173 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
174 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
175 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
178 // If we have a view box create the SQL
179 // Small is the actual view box, Large is double (on each axis) that
180 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
181 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
183 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
184 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
186 if (isset($_GET['viewbox']) && $_GET['viewbox'])
188 $aCoOrdinates = explode(',',$_GET['viewbox']);
189 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
190 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
191 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
192 $aCoOrdinates[0] += $fHeight;
193 $aCoOrdinates[2] -= $fHeight;
194 $aCoOrdinates[1] += $fWidth;
195 $aCoOrdinates[3] -= $fWidth;
196 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
198 $bBoundingBoxSearch = false;
200 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
202 $aPoints = explode(',',$_GET['route']);
203 if (sizeof($aPoints) % 2 != 0)
205 userError("Uneven number of points");
208 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
210 foreach($aPoints as $i => $fPoint)
214 if ($i != 1) $sViewboxCentreSQL .= ",";
215 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
219 $fPrevCoord = (float)$fPoint;
222 $sViewboxCentreSQL .= ")'::geometry,4326)";
224 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
225 $sViewboxSmallSQL = $oDB->getOne($sSQL);
226 if (PEAR::isError($sViewboxSmallSQL))
228 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
230 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
232 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
233 $sViewboxLargeSQL = $oDB->getOne($sSQL);
234 if (PEAR::isError($sViewboxLargeSQL))
236 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
238 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
239 $bBoundingBoxSearch = true;
242 // Do we have anything that looks like a lat/lon pair?
243 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
245 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
246 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
247 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
249 $_GET['nearlat'] = $fQueryLat;
250 $_GET['nearlon'] = $fQueryLon;
251 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
254 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
256 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
257 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
258 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
260 $_GET['nearlat'] = $fQueryLat;
261 $_GET['nearlon'] = $fQueryLon;
262 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
265 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
267 $fQueryLat = $aData[2];
268 $fQueryLon = $aData[3];
269 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
271 $_GET['nearlat'] = $fQueryLat;
272 $_GET['nearlon'] = $fQueryLon;
273 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
277 if ($sQuery || $aStructuredQuery)
279 // Start with a blank search
281 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
282 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
285 $sNearPointSQL = false;
286 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
288 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
289 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
290 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
291 $aSearches[0]['fRadius'] = 0.1;
294 $bSpecialTerms = false;
295 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
296 $aSpecialTerms = array();
297 foreach($aSpecialTermsRaw as $aSpecialTerm)
299 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
300 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
303 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
304 $aSpecialTerms = array();
305 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
307 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
308 unset($aStructuredQuery['amenity']);
310 foreach($aSpecialTermsRaw as $aSpecialTerm)
312 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
313 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
314 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
315 $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';
316 if (CONST_Debug) var_Dump($sSQL);
317 $aSearchWords = $oDB->getAll($sSQL);
318 $aNewSearches = array();
319 foreach($aSearches as $aSearch)
321 foreach($aSearchWords as $aSearchTerm)
323 $aNewSearch = $aSearch;
324 if ($aSearchTerm['country_code'])
326 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
327 $aNewSearches[] = $aNewSearch;
328 $bSpecialTerms = true;
330 if ($aSearchTerm['class'])
332 $aNewSearch['sClass'] = $aSearchTerm['class'];
333 $aNewSearch['sType'] = $aSearchTerm['type'];
334 $aNewSearches[] = $aNewSearch;
335 $bSpecialTerms = true;
339 $aSearches = $aNewSearches;
342 // Split query into phrases
343 // Commas are used to reduce the search space by indicating where phrases split
344 if (sizeof($aStructuredQuery) > 0)
346 $aPhrases = $aStructuredQuery;
347 $bStructuredPhrases = true;
351 $aPhrases = explode(',',$sQuery);
352 $bStructuredPhrases = false;
356 // Convert each phrase to standard form
357 // Create a list of standard words
358 // Get all 'sets' of words
359 // Generate a complete list of all
361 foreach($aPhrases as $iPhrase => $sPhrase)
363 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
364 if (PEAR::isError($aPhrase))
366 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
367 if (CONST_Debug) var_dump($aPhrase);
370 if (trim($aPhrase['string']))
372 $aPhrases[$iPhrase] = $aPhrase;
373 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
374 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
375 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
379 unset($aPhrases[$iPhrase]);
383 // reindex phrases - we make assumptions later on
384 $aPhraseTypes = array_keys($aPhrases);
385 $aPhrases = array_values($aPhrases);
387 if (sizeof($aTokens))
390 // Check which tokens we have, get the ID numbers
391 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
392 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
393 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
394 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
396 if (CONST_Debug) var_Dump($sSQL);
398 $aValidTokens = array();
399 if (sizeof($aTokens))
400 $aDatabaseWords = $oDB->getAll($sSQL);
402 $aDatabaseWords = array();
403 if (PEAR::IsError($aDatabaseWords))
405 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
407 $aPossibleMainWordIDs = array();
408 foreach($aDatabaseWords as $aToken)
410 if (isset($aValidTokens[$aToken['word_token']]))
412 $aValidTokens[$aToken['word_token']][] = $aToken;
416 $aValidTokens[$aToken['word_token']] = array($aToken);
418 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
420 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
422 $aSuggestion = array();
423 $bSuggestion = false;
424 if (CONST_Suggestions_Enabled)
426 foreach($aPhrases as $iPhrase => $aPhrase)
428 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
430 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
431 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
432 $aRow = $aSuggestionWords[0];
433 if ($aRow && $aRow['word'])
435 $aSuggestion[] = $aRow['word'];
440 $aSuggestion[] = $aPhrase['string'];
445 $aSuggestion[] = $aPhrase['string'];
449 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
451 // Try and calculate GB postcodes we might be missing
452 foreach($aTokens as $sToken)
454 // Source of gb postcodes is now definitive - always use
455 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
457 if (substr($aData[1],-2,1) != ' ')
459 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
460 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
462 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
463 if ($aGBPostcodeLocation)
465 $aValidTokens[$sToken] = $aGBPostcodeLocation;
470 foreach($aTokens as $sToken)
472 // Unknown single word token with a number - assume it is a house number
473 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
475 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
479 // Any words that have failed completely?
482 // Start the search process
483 $aResultPlaceIDs = array();
486 Calculate all searches using aValidTokens i.e.
488 'Wodsworth Road, Sheffield' =>
492 0 1 (wodsworth)(road)
495 Score how good the search is so they can be ordered
497 foreach($aPhrases as $iPhrase => $sPhrase)
499 $aNewPhraseSearches = array();
500 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
501 else $sPhraseType = '';
503 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
505 $aWordsetSearches = $aSearches;
507 // Add all words from this wordset
508 foreach($aWordset as $iToken => $sToken)
510 //echo "<br><b>$sToken</b>";
511 $aNewWordsetSearches = array();
513 foreach($aWordsetSearches as $aCurrentSearch)
516 //var_dump($aCurrentSearch);
519 // If the token is valid
520 if (isset($aValidTokens[' '.$sToken]))
522 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
524 $aSearch = $aCurrentSearch;
525 $aSearch['iSearchRank']++;
526 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
528 if ($aSearch['sCountryCode'] === false)
530 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
531 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
532 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
533 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
536 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
538 if ($aSearch['fLat'] === '')
540 $aSearch['fLat'] = $aSearchTerm['lat'];
541 $aSearch['fLon'] = $aSearchTerm['lon'];
542 $aSearch['fRadius'] = $aSearchTerm['radius'];
543 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
546 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
548 if ($aSearch['sHouseNumber'] === '')
550 $aSearch['sHouseNumber'] = $sToken;
551 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
553 // Fall back to not searching for this item (better than nothing)
554 $aSearch = $aCurrentSearch;
555 $aSearch['iSearchRank'] += 1;
556 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
560 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
562 if ($aSearch['sClass'] === '')
564 $aSearch['sOperator'] = $aSearchTerm['operator'];
565 $aSearch['sClass'] = $aSearchTerm['class'];
566 $aSearch['sType'] = $aSearchTerm['type'];
567 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
568 else $aSearch['sOperator'] = 'near'; // near = in for the moment
570 // Do we have a shortcut id?
571 if ($aSearch['sOperator'] == 'name')
573 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
574 if ($iAmenityID = $oDB->getOne($sSQL))
576 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
577 $aSearch['aName'][$iAmenityID] = $iAmenityID;
578 $aSearch['sClass'] = '';
579 $aSearch['sType'] = '';
582 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
585 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
587 if (sizeof($aSearch['aName']))
589 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
591 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
595 $aSearch['iSearchRank'] += 1000; // skip;
600 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
601 // $aSearch['iNamePhrase'] = $iPhrase;
603 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
607 if (isset($aValidTokens[$sToken]))
609 // Allow searching for a word - but at extra cost
610 foreach($aValidTokens[$sToken] as $aSearchTerm)
612 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
614 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
616 $aSearch = $aCurrentSearch;
617 $aSearch['iSearchRank'] += 1;
618 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
619 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
622 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
624 $aSearch = $aCurrentSearch;
625 $aSearch['iSearchRank'] += 2;
626 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
627 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
628 $aSearch['iNamePhrase'] = $iPhrase;
629 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
636 // Allow skipping a word - but at EXTREAM cost
637 //$aSearch = $aCurrentSearch;
638 //$aSearch['iSearchRank']+=100;
639 //$aNewWordsetSearches[] = $aSearch;
643 usort($aNewWordsetSearches, 'bySearchRank');
644 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
646 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
648 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
649 usort($aNewPhraseSearches, 'bySearchRank');
651 $aSearchHash = array();
652 foreach($aNewPhraseSearches as $iSearch => $aSearch)
654 $sHash = serialize($aSearch);
655 if (isset($aSearchHash[$sHash]))
657 unset($aNewPhraseSearches[$iSearch]);
661 $aSearchHash[$sHash] = 1;
665 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
668 // Re-group the searches by their score, junk anything over 20 as just not worth trying
669 $aGroupedSearches = array();
670 foreach($aNewPhraseSearches as $aSearch)
672 if ($aSearch['iSearchRank'] < $iMaxRank)
674 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
675 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
678 ksort($aGroupedSearches);
681 $aSearches = array();
682 foreach($aGroupedSearches as $iScore => $aNewSearches)
684 $iSearchCount += sizeof($aNewSearches);
685 $aSearches = array_merge($aSearches, $aNewSearches);
686 if ($iSearchCount > 50) break;
689 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
695 // Re-group the searches by their score, junk anything over 20 as just not worth trying
696 $aGroupedSearches = array();
697 foreach($aSearches as $aSearch)
699 if ($aSearch['iSearchRank'] < $iMaxRank)
701 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
702 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
705 ksort($aGroupedSearches);
708 if (CONST_Debug) var_Dump($aGroupedSearches);
712 $aCopyGroupedSearches = $aGroupedSearches;
713 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
715 foreach($aSearches as $iSearch => $aSearch)
717 if (sizeof($aSearch['aAddress']))
719 $iReverseItem = array_pop($aSearch['aAddress']);
720 if (isset($aPossibleMainWordIDs[$iReverseItem]))
722 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
723 $aSearch['aName'] = array($iReverseItem);
724 $aGroupedSearches[$iGroup][] = $aSearch;
726 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
727 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
733 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
735 $aCopyGroupedSearches = $aGroupedSearches;
736 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
738 foreach($aSearches as $iSearch => $aSearch)
740 $aReductionsList = array($aSearch['aAddress']);
741 $iSearchRank = $aSearch['iSearchRank'];
742 while(sizeof($aReductionsList) > 0)
745 if ($iSearchRank > iMaxRank) break 3;
746 $aNewReductionsList = array();
747 foreach($aReductionsList as $aReductionsWordList)
749 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
751 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
752 $aReverseSearch = $aSearch;
753 $aSearch['aAddress'] = $aReductionsWordListResult;
754 $aSearch['iSearchRank'] = $iSearchRank;
755 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
756 if (sizeof($aReductionsWordListResult) > 0)
758 $aNewReductionsList[] = $aReductionsWordListResult;
762 $aReductionsList = $aNewReductionsList;
766 ksort($aGroupedSearches);
769 // Filter out duplicate searches
770 $aSearchHash = array();
771 foreach($aGroupedSearches as $iGroup => $aSearches)
773 foreach($aSearches as $iSearch => $aSearch)
775 $sHash = serialize($aSearch);
776 if (isset($aSearchHash[$sHash]))
778 unset($aGroupedSearches[$iGroup][$iSearch]);
779 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
783 $aSearchHash[$sHash] = 1;
788 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
792 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
795 foreach($aSearches as $aSearch)
799 // Must have a location term
800 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
802 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
804 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
806 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
807 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
808 $sSQL .= " order by st_area(geometry) desc limit 1";
809 $aPlaceIDs = $oDB->getCol($sSQL);
814 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
815 if (!$aSearch['sClass']) continue;
816 if (CONST_Debug) var_dump('<hr>',$aSearch);
817 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
818 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
819 if ($oDB->getOne($sSQL))
821 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
822 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
823 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
824 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
825 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
826 $sSQL .= " limit $iLimit";
827 if (CONST_Debug) var_dump($sSQL);
828 $aPlaceIDs = $oDB->getCol($sSQL);
830 if (!sizeof($aPlaceIDs))
832 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
833 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
834 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
835 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
836 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
837 $sSQL .= " limit $iLimit";
838 if (CONST_Debug) var_dump($sSQL);
839 $aPlaceIDs = $oDB->getCol($sSQL);
844 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
845 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
846 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
847 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
848 $sSQL .= " limit $iLimit";
849 if (CONST_Debug) var_dump($sSQL);
850 $aPlaceIDs = $oDB->getCol($sSQL);
856 if (CONST_Debug) var_dump('<hr>',$aSearch);
857 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
858 $aPlaceIDs = array();
860 // First we need a position, either aName or fLat or both
864 // TODO: filter out the pointless search terms (2 letter name tokens and less)
865 // they might be right - but they are just too darned expensive to run
866 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
867 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
868 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
869 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
870 if ($aSearch['fLon'] && $aSearch['fLat'])
872 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
873 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
875 if (sizeof($aExcludePlaceIDs))
877 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
879 if ($sCountryCodesSQL)
881 $aTerms[] = "country_code in ($sCountryCodesSQL)";
884 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
885 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
887 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
889 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
890 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
891 $aOrder[] = "$sImportanceSQL DESC";
895 $sSQL = "select place_id";
896 $sSQL .= " from search_name";
897 $sSQL .= " where ".join(' and ',$aTerms);
898 $sSQL .= " order by ".join(', ',$aOrder);
899 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
900 $sSQL .= " limit 50";
901 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
904 $sSQL .= " limit ".$iLimit;
906 if (CONST_Debug) { var_dump($sSQL); }
907 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
908 if (PEAR::IsError($aViewBoxPlaceIDs))
910 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
912 //var_dump($aViewBoxPlaceIDs);
913 // Did we have an viewbox matches?
914 $aPlaceIDs = array();
915 $bViewBoxMatch = false;
916 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
918 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
919 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
920 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
921 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
922 $aPlaceIDs[] = $aViewBoxRow['place_id'];
925 //var_Dump($aPlaceIDs);
928 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
930 $aRoadPlaceIDs = $aPlaceIDs;
931 $sPlaceIDs = join(',',$aPlaceIDs);
933 // Now they are indexed look for a house attached to a street we found
934 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
935 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
936 if (sizeof($aExcludePlaceIDs))
938 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
940 $sSQL .= " limit $iLimit";
941 if (CONST_Debug) var_dump($sSQL);
942 $aPlaceIDs = $oDB->getCol($sSQL);
944 // If not try the aux fallback table
945 if (!sizeof($aPlaceIDs))
947 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
948 if (sizeof($aExcludePlaceIDs))
950 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
952 // $sSQL .= " limit $iLimit";
953 if (CONST_Debug) var_dump($sSQL);
954 $aPlaceIDs = $oDB->getCol($sSQL);
957 if (!sizeof($aPlaceIDs))
959 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
960 if (sizeof($aExcludePlaceIDs))
962 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
964 // $sSQL .= " limit $iLimit";
965 if (CONST_Debug) var_dump($sSQL);
966 $aPlaceIDs = $oDB->getCol($sSQL);
969 // Fallback to the road
970 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
972 $aPlaceIDs = $aRoadPlaceIDs;
977 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
979 $sPlaceIDs = join(',',$aPlaceIDs);
981 $aClassPlaceIDs = array();
983 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
985 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
986 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
987 $sSQL .= " and linked_place_id is null";
988 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
989 $sSQL .= " order by rank_search asc limit $iLimit";
990 if (CONST_Debug) var_dump($sSQL);
991 $aClassPlaceIDs = $oDB->getCol($sSQL);
994 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
996 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
997 $bCacheTable = $oDB->getOne($sSQL);
999 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1001 if (CONST_Debug) var_dump($sSQL);
1002 $iMaxRank = ((int)$oDB->getOne($sSQL));
1004 // For state / country level searches the normal radius search doesn't work very well
1005 $sPlaceGeom = false;
1006 if ($iMaxRank < 9 && $bCacheTable)
1008 // Try and get a polygon to search in instead
1009 $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";
1010 if (CONST_Debug) var_dump($sSQL);
1011 $sPlaceGeom = $oDB->getOne($sSQL);
1021 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1022 if (CONST_Debug) var_dump($sSQL);
1023 $aPlaceIDs = $oDB->getCol($sSQL);
1024 $sPlaceIDs = join(',',$aPlaceIDs);
1027 if ($sPlaceIDs || $sPlaceGeom)
1033 // More efficient - can make the range bigger
1037 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1038 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1039 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1041 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1042 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1045 $sSQL .= ",placex as f where ";
1046 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1051 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1053 if (sizeof($aExcludePlaceIDs))
1055 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1057 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1058 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1059 if ($iOffset) $sSQL .= " offset $iOffset";
1060 $sSQL .= " limit $iLimit";
1061 if (CONST_Debug) var_dump($sSQL);
1062 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1066 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1069 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1070 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1072 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1073 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1074 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1075 if (sizeof($aExcludePlaceIDs))
1077 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1079 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1080 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1081 if ($iOffset) $sSQL .= " offset $iOffset";
1082 $sSQL .= " limit $iLimit";
1083 if (CONST_Debug) var_dump($sSQL);
1084 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1089 $aPlaceIDs = $aClassPlaceIDs;
1095 if (PEAR::IsError($aPlaceIDs))
1097 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1100 if (CONST_Debug) var_Dump($aPlaceIDs);
1102 foreach($aPlaceIDs as $iPlaceID)
1104 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1106 if ($iQueryLoop > 20) break;
1110 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1111 if ($iGroupLoop > 4) break;
1112 if ($iQueryLoop > 30) break;
1115 // Did we find anything?
1116 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1118 //var_Dump($aResultPlaceIDs);exit;
1119 // Get the details for display (is this a redundant extra step?)
1120 $sPlaceIDs = join(',',$aResultPlaceIDs);
1121 $sOrderSQL = 'CASE ';
1122 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1124 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1126 $sOrderSQL .= ' ELSE 10000000 END';
1127 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1128 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1129 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1130 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1131 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1132 // $sSQL .= $sOrderSQL." as porder, ";
1133 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1134 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1135 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1136 $sSQL .= "and linked_place_id is null ";
1137 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1138 if (!$bDeDupe) $sSQL .= ",place_id";
1139 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1140 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1141 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1143 $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,";
1144 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1145 $sSQL .= "null as placename,";
1146 $sSQL .= "null as ref,";
1147 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1148 // $sSQL .= $sOrderSQL." as porder, ";
1149 $sSQL .= "-0.15 as importance ";
1150 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1151 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1152 $sSQL .= "group by place_id";
1153 if (!$bDeDupe) $sSQL .= ",place_id";
1155 $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,";
1156 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1157 $sSQL .= "null as placename,";
1158 $sSQL .= "null as ref,";
1159 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1160 // $sSQL .= $sOrderSQL." as porder, ";
1161 $sSQL .= "-0.10 as importance ";
1162 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1163 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1164 $sSQL .= "group by place_id";
1165 if (!$bDeDupe) $sSQL .= ",place_id";
1166 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1167 $sSQL .= "order by importance desc";
1168 // $sSQL .= "order by rank_search,rank_address,porder asc";
1169 if (CONST_Debug) var_dump('<hr>',$sSQL);
1170 $aSearchResults = $oDB->getAll($sSQL);
1171 //var_dump($sSQL,$aSearchResults);exit;
1173 if (PEAR::IsError($aSearchResults))
1175 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1178 } // end if ($sQuery)
1181 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1183 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1184 $aResultPlaceIDs = array($iPlaceID);
1186 // TODO: this needs refactoring!
1188 // Get the details for display (is this a redundant extra step?)
1189 $sPlaceIDs = join(',',$aResultPlaceIDs);
1190 $sOrderSQL = 'CASE ';
1191 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1193 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1195 $sOrderSQL .= ' ELSE 10000000 END';
1196 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1197 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1198 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1199 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1200 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1201 // $sSQL .= $sOrderSQL." as porder, ";
1202 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1203 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1204 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1205 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1206 if (!$bDeDupe) $sSQL .= ",place_id";
1207 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1208 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1209 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1211 $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,";
1212 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1213 $sSQL .= "null as placename,";
1214 $sSQL .= "null as ref,";
1215 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1216 // $sSQL .= $sOrderSQL." as porder, ";
1217 $sSQL .= "-0.15 as importance ";
1218 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1219 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1220 $sSQL .= "group by place_id";
1221 if (!$bDeDupe) $sSQL .= ",place_id";
1223 $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,";
1224 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1225 $sSQL .= "null as placename,";
1226 $sSQL .= "null as ref,";
1227 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1228 // $sSQL .= $sOrderSQL." as porder, ";
1229 $sSQL .= "-0.10 as importance ";
1230 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1231 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1232 $sSQL .= "group by place_id";
1233 if (!$bDeDupe) $sSQL .= ",place_id";
1234 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1235 $sSQL .= "order by importance desc";
1236 // $sSQL .= "order by rank_search,rank_address,porder asc";
1237 if (CONST_Debug) var_dump('<hr>',$sSQL);
1238 $aSearchResults = $oDB->getAll($sSQL);
1239 //var_dump($sSQL,$aSearchResults);exit;
1241 if (PEAR::IsError($aSearchResults))
1243 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1249 $sSearchResult = '';
1250 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1252 $sSearchResult = 'No Results Found';
1254 //var_Dump($aSearchResults);
1256 $aClassType = getClassTypesWithImportance();
1257 $aRecheckWords = preg_split('/\b/',$sQuery);
1258 foreach($aRecheckWords as $i => $sWord)
1260 if (!$sWord) unset($aRecheckWords[$i]);
1262 foreach($aSearchResults as $iResNum => $aResult)
1264 if (CONST_Search_AreaPolygons)
1266 // Get the bounding box and outline polygon
1267 $sSQL = "select place_id,numfeatures,area,outline,";
1268 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1269 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1270 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1272 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1273 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1274 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1275 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1276 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1277 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1278 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1279 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1280 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1281 $aPointPolygon = $oDB->getRow($sSQL);
1282 if (PEAR::IsError($aPointPolygon))
1284 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1286 if ($aPointPolygon['place_id'])
1288 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1289 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1290 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1291 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1293 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1294 $aResult['lat'] = $aPointPolygon['centrelat'];
1295 $aResult['lon'] = $aPointPolygon['centrelon'];
1299 // Translate geometary string to point array
1300 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1302 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1304 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1306 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1308 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1311 $iSteps = ($fRadius * 40000)^2;
1312 $fStepSize = (2*pi())/$iSteps;
1313 $aPolyPoints = array();
1314 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1316 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1318 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1319 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1320 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1321 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1325 // Output data suitable for display (points and a bounding box)
1326 if ($bShowPolygons && isset($aPolyPoints))
1328 $aResult['aPolyPoints'] = array();
1329 foreach($aPolyPoints as $aPoint)
1331 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1334 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1338 if (!isset($aResult['aBoundingBox']))
1341 $fDiameter = 0.0001;
1343 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1344 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1346 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1348 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1349 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1351 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1353 $fRadius = $fDiameter / 2;
1355 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1356 $fStepSize = (2*pi())/$iSteps;
1357 $aPolyPoints = array();
1358 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1360 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1362 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1363 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1364 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1365 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1367 // Output data suitable for display (points and a bounding box)
1370 $aResult['aPolyPoints'] = array();
1371 foreach($aPolyPoints as $aPoint)
1373 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1376 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1379 // Is there an icon set for this type of result?
1380 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1381 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1383 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1386 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1387 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1389 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1392 if ($bShowAddressDetails)
1394 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1395 //var_dump($aResult['address']);
1399 // Adjust importance for the number of exact string matches in the result
1400 $aResult['importance'] = max(0.001,$aResult['importance']);
1402 $sAddress = $aResult['langaddress'];
1403 foreach($aRecheckWords as $i => $sWord)
1405 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1407 $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
1409 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1411 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1412 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1414 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1416 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1417 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1419 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1423 $aResult['importance'] = 1000000000000000;
1426 $aResult['name'] = $aResult['langaddress'];
1427 $aResult['foundorder'] = $iResNum;
1428 $aSearchResults[$iResNum] = $aResult;
1430 uasort($aSearchResults, 'byImportance');
1432 //var_dump($aSearchResults);exit;
1434 $aOSMIDDone = array();
1435 $aClassTypeNameDone = array();
1436 $aToFilter = $aSearchResults;
1437 $aSearchResults = array();
1440 foreach($aToFilter as $iResNum => $aResult)
1442 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1443 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1446 $fLat = $aResult['lat'];
1447 $fLon = $aResult['lon'];
1448 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1451 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1452 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1454 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1455 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1456 $aSearchResults[] = $aResult;
1459 // Absolute limit on number of results
1460 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1463 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1465 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1467 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1472 logEnd($oDB, $hLog, sizeof($aToFilter));
1474 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1475 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1476 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1477 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1478 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1479 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1482 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1484 $sMoreURL .= '&q='.urlencode($sQuery);
1486 if (CONST_Debug) exit;
1488 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');