2 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
3 require_once(CONST_BasePath.'/lib/log.php');
5 ini_set('memory_limit', '200M');
9 $fLat = CONST_Default_Lat;
10 $fLon = CONST_Default_Lon;
11 $iZoom = CONST_Default_Zoom;
12 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
13 $sOutputFormat = 'html';
14 $aSearchResults = array();
15 $aExcludePlaceIDs = array();
16 $sCountryCodesSQL = false;
17 $sSuggestion = $sSuggestionURL = false;
18 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
19 $bReverseInPlan = false;
20 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
23 if ($iFinalLimit > 50) $iFinalLimit = 50;
24 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
26 $iMaxAddressRank = 30;
29 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
31 $sOutputFormat = $_GET['format'];
34 // Show / use polygons
35 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
36 if ($sOutputFormat == 'html') {
37 $bAsText = $bShowPolygons;
38 $bShowPolygons = false;
43 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
44 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
45 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
46 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
47 if ((($bShowPolygons?1:0)
52 ) > CONST_PolygonOutput_MaximumTypes) {
53 if (CONST_PolygonOutput_MaximumTypes) {
54 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
56 userError("Polygon output is disabled");
62 // Show address breakdown
63 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
66 $aLangPrefOrder = getPreferredLanguages();
67 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
68 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
69 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
71 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
73 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
75 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
77 $iExcludedPlaceID = (int)$iExcludedPlaceID;
78 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
82 // Only certain ranks of feature
83 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
85 if (isset($_GET['featuretype']))
87 switch($_GET['featuretype'])
90 $iMinAddressRank = $iMaxAddressRank = 4;
93 $iMinAddressRank = $iMaxAddressRank = 8;
96 $iMinAddressRank = 14;
97 $iMaxAddressRank = 16;
100 $iMinAddressRank = 8;
101 $iMaxAddressRank = 20;
106 if (isset($_GET['countrycodes']))
108 $aCountryCodes = array();
109 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
111 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
113 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
116 $sCountryCodesSQL = join(',', $aCountryCodes);
120 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
121 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
123 $sQuery = substr($_SERVER['PATH_INFO'], 1);
125 // reverse order of '/' separated string
126 $aPhrases = explode('/', $sQuery);
127 $aPhrases = array_reverse($aPhrases);
128 $sQuery = join(', ',$aPhrases);
131 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
133 if (!isset($_GET[$sKey])) return false;
134 $sValue = trim($_GET[$sKey]);
135 if (!$sValue) return false;
136 $aStructuredQuery[$sKey] = $sValue;
137 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
138 $iMinAddressRank = $iNewMinAddressRank;
139 $iMaxAddressRank = $iNewMaxAddressRank;
145 $aStructuredOptions = array(
146 array('amenity', 26, 30),
147 array('street', 26, 30),
148 array('city', 14, 24),
149 array('county', 9, 13),
150 array('state', 8, 8),
151 array('country', 4, 4),
152 array('postalcode', 16, 25),
154 $aStructuredQuery = array();
155 foreach($aStructuredOptions as $aStructuredOption)
157 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
159 if (sizeof($aStructuredQuery) > 0) {
160 $sQuery = join(', ', $aStructuredQuery);
165 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
167 // Hack to make it handle "new york, ny" (and variants) correctly
168 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
169 if (isset($aLangPrefOrder['name:en']))
171 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
172 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
173 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
176 // If we have a view box create the SQL
177 // Small is the actual view box, Large is double (on each axis) that
178 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
179 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
181 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
182 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
184 if (isset($_GET['viewbox']) && $_GET['viewbox'])
186 $aCoOrdinates = explode(',',$_GET['viewbox']);
187 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
188 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
189 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
190 $aCoOrdinates[0] += $fHeight;
191 $aCoOrdinates[2] -= $fHeight;
192 $aCoOrdinates[1] += $fWidth;
193 $aCoOrdinates[3] -= $fWidth;
194 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
196 $bBoundingBoxSearch = false;
198 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
200 $aPoints = explode(',',$_GET['route']);
201 if (sizeof($aPoints) % 2 != 0)
203 userError("Uneven number of points");
206 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
208 foreach($aPoints as $i => $fPoint)
212 if ($i != 1) $sViewboxCentreSQL .= ",";
213 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
217 $fPrevCoord = (float)$fPoint;
220 $sViewboxCentreSQL .= ")'::geometry,4326)";
222 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
223 $sViewboxSmallSQL = $oDB->getOne($sSQL);
224 if (PEAR::isError($sViewboxSmallSQL))
226 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
228 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
230 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
231 $sViewboxLargeSQL = $oDB->getOne($sSQL);
232 if (PEAR::isError($sViewboxLargeSQL))
234 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
236 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
237 $bBoundingBoxSearch = true;
240 // Do we have anything that looks like a lat/lon pair?
241 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
243 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
244 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
245 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
247 $_GET['nearlat'] = $fQueryLat;
248 $_GET['nearlon'] = $fQueryLon;
249 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
252 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
254 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
255 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
256 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
258 $_GET['nearlat'] = $fQueryLat;
259 $_GET['nearlon'] = $fQueryLon;
260 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
263 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
265 $fQueryLat = $aData[2];
266 $fQueryLon = $aData[3];
267 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
269 $_GET['nearlat'] = $fQueryLat;
270 $_GET['nearlon'] = $fQueryLon;
271 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
275 if ($sQuery || $aStructuredQuery)
277 // Start with a blank search
279 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
280 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
283 $sNearPointSQL = false;
284 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
286 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
287 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
288 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
289 $aSearches[0]['fRadius'] = 0.1;
292 $bSpecialTerms = false;
293 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
294 $aSpecialTerms = array();
295 foreach($aSpecialTermsRaw as $aSpecialTerm)
297 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
298 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
301 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
302 $aSpecialTerms = array();
303 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
305 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
306 unset($aStructuredQuery['amenity']);
308 foreach($aSpecialTermsRaw as $aSpecialTerm)
310 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
311 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
312 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
313 $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';
314 if (CONST_Debug) var_Dump($sSQL);
315 $aSearchWords = $oDB->getAll($sSQL);
316 $aNewSearches = array();
317 foreach($aSearches as $aSearch)
319 foreach($aSearchWords as $aSearchTerm)
321 $aNewSearch = $aSearch;
322 if ($aSearchTerm['country_code'])
324 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
325 $aNewSearches[] = $aNewSearch;
326 $bSpecialTerms = true;
328 if ($aSearchTerm['class'])
330 $aNewSearch['sClass'] = $aSearchTerm['class'];
331 $aNewSearch['sType'] = $aSearchTerm['type'];
332 $aNewSearches[] = $aNewSearch;
333 $bSpecialTerms = true;
337 $aSearches = $aNewSearches;
340 // Split query into phrases
341 // Commas are used to reduce the search space by indicating where phrases split
342 if (sizeof($aStructuredQuery) > 0)
344 $aPhrases = $aStructuredQuery;
345 $bStructuredPhrases = true;
349 $aPhrases = explode(',',$sQuery);
350 $bStructuredPhrases = false;
354 // Convert each phrase to standard form
355 // Create a list of standard words
356 // Get all 'sets' of words
357 // Generate a complete list of all
359 foreach($aPhrases as $iPhrase => $sPhrase)
361 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
362 if (PEAR::isError($aPhrase))
364 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
365 if (CONST_Debug) var_dump($aPhrase);
368 if (trim($aPhrase['string']))
370 $aPhrases[$iPhrase] = $aPhrase;
371 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
372 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
373 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
377 unset($aPhrases[$iPhrase]);
381 // reindex phrases - we make assumptions later on
382 $aPhraseTypes = array_keys($aPhrases);
383 $aPhrases = array_values($aPhrases);
385 if (sizeof($aTokens))
388 // Check which tokens we have, get the ID numbers
389 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
390 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
391 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
392 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
394 if (CONST_Debug) var_Dump($sSQL);
396 $aValidTokens = array();
397 if (sizeof($aTokens))
398 $aDatabaseWords = $oDB->getAll($sSQL);
400 $aDatabaseWords = array();
401 if (PEAR::IsError($aDatabaseWords))
403 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
405 $aPossibleMainWordIDs = array();
406 foreach($aDatabaseWords as $aToken)
408 if (isset($aValidTokens[$aToken['word_token']]))
410 $aValidTokens[$aToken['word_token']][] = $aToken;
414 $aValidTokens[$aToken['word_token']] = array($aToken);
416 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
418 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
420 $aSuggestion = array();
421 $bSuggestion = false;
422 if (CONST_Suggestions_Enabled)
424 foreach($aPhrases as $iPhrase => $aPhrase)
426 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
428 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
429 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
430 $aRow = $aSuggestionWords[0];
431 if ($aRow && $aRow['word'])
433 $aSuggestion[] = $aRow['word'];
438 $aSuggestion[] = $aPhrase['string'];
443 $aSuggestion[] = $aPhrase['string'];
447 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
449 // Try and calculate GB postcodes we might be missing
450 foreach($aTokens as $sToken)
452 // Source of gb postcodes is now definitive - always use
453 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
455 if (substr($aData[1],-2,1) != ' ')
457 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
458 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
460 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
461 if ($aGBPostcodeLocation)
463 $aValidTokens[$sToken] = $aGBPostcodeLocation;
468 foreach($aTokens as $sToken)
470 // Unknown single word token with a number - assume it is a house number
471 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
473 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
477 // Any words that have failed completely?
480 // Start the search process
481 $aResultPlaceIDs = array();
484 Calculate all searches using aValidTokens i.e.
486 'Wodsworth Road, Sheffield' =>
490 0 1 (wodsworth)(road)
493 Score how good the search is so they can be ordered
495 foreach($aPhrases as $iPhrase => $sPhrase)
497 $aNewPhraseSearches = array();
498 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
499 else $sPhraseType = '';
501 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
503 $aWordsetSearches = $aSearches;
505 // Add all words from this wordset
506 foreach($aWordset as $iToken => $sToken)
508 //echo "<br><b>$sToken</b>";
509 $aNewWordsetSearches = array();
511 foreach($aWordsetSearches as $aCurrentSearch)
514 //var_dump($aCurrentSearch);
517 // If the token is valid
518 if (isset($aValidTokens[' '.$sToken]))
520 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
522 $aSearch = $aCurrentSearch;
523 $aSearch['iSearchRank']++;
524 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
526 if ($aSearch['sCountryCode'] === false)
528 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
529 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
530 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
531 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
534 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
536 if ($aSearch['fLat'] === '')
538 $aSearch['fLat'] = $aSearchTerm['lat'];
539 $aSearch['fLon'] = $aSearchTerm['lon'];
540 $aSearch['fRadius'] = $aSearchTerm['radius'];
541 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
544 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
546 if ($aSearch['sHouseNumber'] === '')
548 $aSearch['sHouseNumber'] = $sToken;
549 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
551 // Fall back to not searching for this item (better than nothing)
552 $aSearch = $aCurrentSearch;
553 $aSearch['iSearchRank'] += 1;
554 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
558 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
560 if ($aSearch['sClass'] === '')
562 $aSearch['sOperator'] = $aSearchTerm['operator'];
563 $aSearch['sClass'] = $aSearchTerm['class'];
564 $aSearch['sType'] = $aSearchTerm['type'];
565 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
566 else $aSearch['sOperator'] = 'near'; // near = in for the moment
568 // Do we have a shortcut id?
569 if ($aSearch['sOperator'] == 'name')
571 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
572 if ($iAmenityID = $oDB->getOne($sSQL))
574 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
575 $aSearch['aName'][$iAmenityID] = $iAmenityID;
576 $aSearch['sClass'] = '';
577 $aSearch['sType'] = '';
580 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
583 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
585 if (sizeof($aSearch['aName']))
587 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
589 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
593 $aSearch['iSearchRank'] += 1000; // skip;
598 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
599 // $aSearch['iNamePhrase'] = $iPhrase;
601 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
605 if (isset($aValidTokens[$sToken]))
607 // Allow searching for a word - but at extra cost
608 foreach($aValidTokens[$sToken] as $aSearchTerm)
610 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
612 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
614 $aSearch = $aCurrentSearch;
615 $aSearch['iSearchRank'] += 1;
616 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
617 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
620 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
622 $aSearch = $aCurrentSearch;
623 $aSearch['iSearchRank'] += 2;
624 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
625 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
626 $aSearch['iNamePhrase'] = $iPhrase;
627 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
634 // Allow skipping a word - but at EXTREAM cost
635 //$aSearch = $aCurrentSearch;
636 //$aSearch['iSearchRank']+=100;
637 //$aNewWordsetSearches[] = $aSearch;
641 usort($aNewWordsetSearches, 'bySearchRank');
642 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
644 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
646 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
647 usort($aNewPhraseSearches, 'bySearchRank');
649 $aSearchHash = array();
650 foreach($aNewPhraseSearches as $iSearch => $aSearch)
652 $sHash = serialize($aSearch);
653 if (isset($aSearchHash[$sHash]))
655 unset($aNewPhraseSearches[$iSearch]);
659 $aSearchHash[$sHash] = 1;
663 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
666 // Re-group the searches by their score, junk anything over 20 as just not worth trying
667 $aGroupedSearches = array();
668 foreach($aNewPhraseSearches as $aSearch)
670 if ($aSearch['iSearchRank'] < $iMaxRank)
672 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
673 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
676 ksort($aGroupedSearches);
679 $aSearches = array();
680 foreach($aGroupedSearches as $iScore => $aNewSearches)
682 $iSearchCount += sizeof($aNewSearches);
683 $aSearches = array_merge($aSearches, $aNewSearches);
684 if ($iSearchCount > 50) break;
687 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
693 // Re-group the searches by their score, junk anything over 20 as just not worth trying
694 $aGroupedSearches = array();
695 foreach($aSearches as $aSearch)
697 if ($aSearch['iSearchRank'] < $iMaxRank)
699 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
700 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
703 ksort($aGroupedSearches);
706 if (CONST_Debug) var_Dump($aGroupedSearches);
710 $aCopyGroupedSearches = $aGroupedSearches;
711 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
713 foreach($aSearches as $iSearch => $aSearch)
715 if (sizeof($aSearch['aAddress']))
717 $iReverseItem = array_pop($aSearch['aAddress']);
718 if (isset($aPossibleMainWordIDs[$iReverseItem]))
720 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
721 $aSearch['aName'] = array($iReverseItem);
722 $aGroupedSearches[$iGroup][] = $aSearch;
724 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
725 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
731 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
733 $aCopyGroupedSearches = $aGroupedSearches;
734 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
736 foreach($aSearches as $iSearch => $aSearch)
738 $aReductionsList = array($aSearch['aAddress']);
739 $iSearchRank = $aSearch['iSearchRank'];
740 while(sizeof($aReductionsList) > 0)
743 if ($iSearchRank > iMaxRank) break 3;
744 $aNewReductionsList = array();
745 foreach($aReductionsList as $aReductionsWordList)
747 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
749 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
750 $aReverseSearch = $aSearch;
751 $aSearch['aAddress'] = $aReductionsWordListResult;
752 $aSearch['iSearchRank'] = $iSearchRank;
753 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
754 if (sizeof($aReductionsWordListResult) > 0)
756 $aNewReductionsList[] = $aReductionsWordListResult;
760 $aReductionsList = $aNewReductionsList;
764 ksort($aGroupedSearches);
767 // Filter out duplicate searches
768 $aSearchHash = array();
769 foreach($aGroupedSearches as $iGroup => $aSearches)
771 foreach($aSearches as $iSearch => $aSearch)
773 $sHash = serialize($aSearch);
774 if (isset($aSearchHash[$sHash]))
776 unset($aGroupedSearches[$iGroup][$iSearch]);
777 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
781 $aSearchHash[$sHash] = 1;
786 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
790 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
793 foreach($aSearches as $aSearch)
797 // Must have a location term
798 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
800 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
802 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
804 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
805 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
806 $sSQL .= " order by st_area(geometry) desc limit 1";
807 $aPlaceIDs = $oDB->getCol($sSQL);
812 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
813 if (!$aSearch['sClass']) continue;
814 if (CONST_Debug) var_dump('<hr>',$aSearch);
815 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
816 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
817 if ($oDB->getOne($sSQL))
819 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
820 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
821 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
822 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
823 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
824 $sSQL .= " limit $iLimit";
825 if (CONST_Debug) var_dump($sSQL);
826 $aPlaceIDs = $oDB->getCol($sSQL);
828 if (!sizeof($aPlaceIDs))
830 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
831 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
832 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
833 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
834 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
835 $sSQL .= " limit $iLimit";
836 if (CONST_Debug) var_dump($sSQL);
837 $aPlaceIDs = $oDB->getCol($sSQL);
842 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
843 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
844 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
845 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
846 $sSQL .= " limit $iLimit";
847 if (CONST_Debug) var_dump($sSQL);
848 $aPlaceIDs = $oDB->getCol($sSQL);
854 if (CONST_Debug) var_dump('<hr>',$aSearch);
855 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
856 $aPlaceIDs = array();
858 // First we need a position, either aName or fLat or both
862 // TODO: filter out the pointless search terms (2 letter name tokens and less)
863 // they might be right - but they are just too darned expensive to run
864 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
865 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
866 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
867 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
868 if ($aSearch['fLon'] && $aSearch['fLat'])
870 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
871 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
873 if (sizeof($aExcludePlaceIDs))
875 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
877 if ($sCountryCodesSQL)
879 $aTerms[] = "country_code in ($sCountryCodesSQL)";
882 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
883 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
885 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
887 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
888 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
889 $aOrder[] = "$sImportanceSQL DESC";
893 $sSQL = "select place_id";
894 $sSQL .= " from search_name";
895 $sSQL .= " where ".join(' and ',$aTerms);
896 $sSQL .= " order by ".join(', ',$aOrder);
897 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
898 $sSQL .= " limit 50";
899 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
902 $sSQL .= " limit ".$iLimit;
904 if (CONST_Debug) { var_dump($sSQL); }
905 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
906 if (PEAR::IsError($aViewBoxPlaceIDs))
908 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
910 //var_dump($aViewBoxPlaceIDs);
911 // Did we have an viewbox matches?
912 $aPlaceIDs = array();
913 $bViewBoxMatch = false;
914 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
916 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
917 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
918 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
919 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
920 $aPlaceIDs[] = $aViewBoxRow['place_id'];
923 //var_Dump($aPlaceIDs);
926 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
928 $aRoadPlaceIDs = $aPlaceIDs;
929 $sPlaceIDs = join(',',$aPlaceIDs);
931 // Now they are indexed look for a house attached to a street we found
932 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
933 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
934 if (sizeof($aExcludePlaceIDs))
936 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
938 $sSQL .= " limit $iLimit";
939 if (CONST_Debug) var_dump($sSQL);
940 $aPlaceIDs = $oDB->getCol($sSQL);
942 // If not try the aux fallback table
943 if (!sizeof($aPlaceIDs))
945 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
946 if (sizeof($aExcludePlaceIDs))
948 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
950 // $sSQL .= " limit $iLimit";
951 if (CONST_Debug) var_dump($sSQL);
952 $aPlaceIDs = $oDB->getCol($sSQL);
955 if (!sizeof($aPlaceIDs))
957 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
958 if (sizeof($aExcludePlaceIDs))
960 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
962 // $sSQL .= " limit $iLimit";
963 if (CONST_Debug) var_dump($sSQL);
964 $aPlaceIDs = $oDB->getCol($sSQL);
967 // Fallback to the road
968 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
970 $aPlaceIDs = $aRoadPlaceIDs;
975 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
977 $sPlaceIDs = join(',',$aPlaceIDs);
979 $aClassPlaceIDs = array();
981 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
983 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
984 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
985 $sSQL .= " and linked_place_id is null";
986 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
987 $sSQL .= " order by rank_search asc limit $iLimit";
988 if (CONST_Debug) var_dump($sSQL);
989 $aClassPlaceIDs = $oDB->getCol($sSQL);
992 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
994 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
995 $bCacheTable = $oDB->getOne($sSQL);
997 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
999 if (CONST_Debug) var_dump($sSQL);
1000 $iMaxRank = ((int)$oDB->getOne($sSQL));
1002 // For state / country level searches the normal radius search doesn't work very well
1003 $sPlaceGeom = false;
1004 if ($iMaxRank < 9 && $bCacheTable)
1006 // Try and get a polygon to search in instead
1007 $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";
1008 if (CONST_Debug) var_dump($sSQL);
1009 $sPlaceGeom = $oDB->getOne($sSQL);
1019 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1020 if (CONST_Debug) var_dump($sSQL);
1021 $aPlaceIDs = $oDB->getCol($sSQL);
1022 $sPlaceIDs = join(',',$aPlaceIDs);
1025 if ($sPlaceIDs || $sPlaceGeom)
1031 // More efficient - can make the range bigger
1035 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1036 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1037 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1039 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1040 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1043 $sSQL .= ",placex as f where ";
1044 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1049 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1051 if (sizeof($aExcludePlaceIDs))
1053 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1055 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1056 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1057 if ($iOffset) $sSQL .= " offset $iOffset";
1058 $sSQL .= " limit $iLimit";
1059 if (CONST_Debug) var_dump($sSQL);
1060 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1064 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1067 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1068 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1070 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1071 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1072 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1073 if (sizeof($aExcludePlaceIDs))
1075 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1077 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1078 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1079 if ($iOffset) $sSQL .= " offset $iOffset";
1080 $sSQL .= " limit $iLimit";
1081 if (CONST_Debug) var_dump($sSQL);
1082 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1087 $aPlaceIDs = $aClassPlaceIDs;
1093 if (PEAR::IsError($aPlaceIDs))
1095 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1098 if (CONST_Debug) var_Dump($aPlaceIDs);
1100 foreach($aPlaceIDs as $iPlaceID)
1102 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1104 if ($iQueryLoop > 20) break;
1108 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1109 if ($iGroupLoop > 4) break;
1110 if ($iQueryLoop > 30) break;
1113 // Did we find anything?
1114 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1116 //var_Dump($aResultPlaceIDs);exit;
1117 // Get the details for display (is this a redundant extra step?)
1118 $sPlaceIDs = join(',',$aResultPlaceIDs);
1119 $sOrderSQL = 'CASE ';
1120 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1122 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1124 $sOrderSQL .= ' ELSE 10000000 END';
1125 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1126 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1127 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1128 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1129 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1130 // $sSQL .= $sOrderSQL." as porder, ";
1131 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1132 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1133 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1134 $sSQL .= "and linked_place_id is null ";
1135 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1136 if (!$bDeDupe) $sSQL .= ",place_id";
1137 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1138 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1139 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1141 $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,";
1142 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1143 $sSQL .= "null as placename,";
1144 $sSQL .= "null as ref,";
1145 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1146 // $sSQL .= $sOrderSQL." as porder, ";
1147 $sSQL .= "-0.15 as importance ";
1148 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1149 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1150 $sSQL .= "group by place_id";
1151 if (!$bDeDupe) $sSQL .= ",place_id";
1153 $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,";
1154 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1155 $sSQL .= "null as placename,";
1156 $sSQL .= "null as ref,";
1157 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1158 // $sSQL .= $sOrderSQL." as porder, ";
1159 $sSQL .= "-0.10 as importance ";
1160 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1161 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1162 $sSQL .= "group by place_id";
1163 if (!$bDeDupe) $sSQL .= ",place_id";
1164 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1165 $sSQL .= "order by importance desc";
1166 // $sSQL .= "order by rank_search,rank_address,porder asc";
1167 if (CONST_Debug) var_dump('<hr>',$sSQL);
1168 $aSearchResults = $oDB->getAll($sSQL);
1169 //var_dump($sSQL,$aSearchResults);exit;
1171 if (PEAR::IsError($aSearchResults))
1173 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1176 } // end if ($sQuery)
1179 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1181 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1182 $aResultPlaceIDs = array($iPlaceID);
1184 // TODO: this needs refactoring!
1186 // Get the details for display (is this a redundant extra step?)
1187 $sPlaceIDs = join(',',$aResultPlaceIDs);
1188 $sOrderSQL = 'CASE ';
1189 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1191 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1193 $sOrderSQL .= ' ELSE 10000000 END';
1194 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1195 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1196 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1197 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1198 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1199 // $sSQL .= $sOrderSQL." as porder, ";
1200 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1201 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1202 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1203 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1204 if (!$bDeDupe) $sSQL .= ",place_id";
1205 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1206 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1207 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1209 $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,";
1210 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1211 $sSQL .= "null as placename,";
1212 $sSQL .= "null as ref,";
1213 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1214 // $sSQL .= $sOrderSQL." as porder, ";
1215 $sSQL .= "-0.15 as importance ";
1216 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1217 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1218 $sSQL .= "group by place_id";
1219 if (!$bDeDupe) $sSQL .= ",place_id";
1221 $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,";
1222 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1223 $sSQL .= "null as placename,";
1224 $sSQL .= "null as ref,";
1225 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1226 // $sSQL .= $sOrderSQL." as porder, ";
1227 $sSQL .= "-0.10 as importance ";
1228 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1229 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1230 $sSQL .= "group by place_id";
1231 if (!$bDeDupe) $sSQL .= ",place_id";
1232 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1233 $sSQL .= "order by importance desc";
1234 // $sSQL .= "order by rank_search,rank_address,porder asc";
1235 if (CONST_Debug) var_dump('<hr>',$sSQL);
1236 $aSearchResults = $oDB->getAll($sSQL);
1237 //var_dump($sSQL,$aSearchResults);exit;
1239 if (PEAR::IsError($aSearchResults))
1241 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1247 $sSearchResult = '';
1248 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1250 $sSearchResult = 'No Results Found';
1252 //var_Dump($aSearchResults);
1254 $aClassType = getClassTypesWithImportance();
1255 $aRecheckWords = preg_split('/\b/',$sQuery);
1256 foreach($aRecheckWords as $i => $sWord)
1258 if (!$sWord) unset($aRecheckWords[$i]);
1260 foreach($aSearchResults as $iResNum => $aResult)
1262 if (CONST_Search_AreaPolygons)
1264 // Get the bounding box and outline polygon
1265 $sSQL = "select place_id,numfeatures,area,outline,";
1266 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1267 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1268 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1270 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1271 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1272 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1273 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1274 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1275 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1276 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1277 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1278 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1279 $aPointPolygon = $oDB->getRow($sSQL);
1280 if (PEAR::IsError($aPointPolygon))
1282 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1284 if ($aPointPolygon['place_id'])
1286 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1287 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1288 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1289 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1291 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1292 $aResult['lat'] = $aPointPolygon['centrelat'];
1293 $aResult['lon'] = $aPointPolygon['centrelon'];
1297 // Translate geometary string to point array
1298 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1300 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1302 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1304 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1306 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1309 $iSteps = ($fRadius * 40000)^2;
1310 $fStepSize = (2*pi())/$iSteps;
1311 $aPolyPoints = array();
1312 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1314 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1316 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1317 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1318 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1319 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1323 // Output data suitable for display (points and a bounding box)
1324 if ($bShowPolygons && isset($aPolyPoints))
1326 $aResult['aPolyPoints'] = array();
1327 foreach($aPolyPoints as $aPoint)
1329 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1332 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1336 if (!isset($aResult['aBoundingBox']))
1339 $fDiameter = 0.0001;
1341 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1342 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1344 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1346 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1347 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1349 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1351 $fRadius = $fDiameter / 2;
1353 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1354 $fStepSize = (2*pi())/$iSteps;
1355 $aPolyPoints = array();
1356 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1358 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1360 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1361 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1362 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1363 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1365 // Output data suitable for display (points and a bounding box)
1368 $aResult['aPolyPoints'] = array();
1369 foreach($aPolyPoints as $aPoint)
1371 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1374 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1377 // Is there an icon set for this type of result?
1378 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1379 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1381 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1384 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1385 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1387 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1390 if ($bShowAddressDetails)
1392 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1393 //var_dump($aResult['address']);
1397 // Adjust importance for the number of exact string matches in the result
1398 $aResult['importance'] = max(0.001,$aResult['importance']);
1400 $sAddress = $aResult['langaddress'];
1401 foreach($aRecheckWords as $i => $sWord)
1403 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1405 $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
1407 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1409 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1410 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1412 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1414 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1415 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1417 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1421 $aResult['importance'] = 1000000000000000;
1424 $aResult['name'] = $aResult['langaddress'];
1425 $aResult['foundorder'] = $iResNum;
1426 $aSearchResults[$iResNum] = $aResult;
1428 uasort($aSearchResults, 'byImportance');
1430 //var_dump($aSearchResults);exit;
1432 $aOSMIDDone = array();
1433 $aClassTypeNameDone = array();
1434 $aToFilter = $aSearchResults;
1435 $aSearchResults = array();
1438 foreach($aToFilter as $iResNum => $aResult)
1440 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1441 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1444 $fLat = $aResult['lat'];
1445 $fLon = $aResult['lon'];
1446 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1449 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1450 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1452 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1453 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1454 $aSearchResults[] = $aResult;
1457 // Absolute limit on number of results
1458 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1461 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1463 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1465 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1470 logEnd($oDB, $hLog, sizeof($aToFilter));
1472 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1473 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1474 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1475 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1476 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1477 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1480 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1482 $sMoreURL .= '&q='.urlencode($sQuery);
1484 if (CONST_Debug) exit;
1486 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');