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;
29 $sAllowedTypesSQLList = false;
32 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
34 $sOutputFormat = $_GET['format'];
37 // Show / use polygons
38 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
39 if ($sOutputFormat == 'html') {
40 $bAsText = $bShowPolygons;
41 $bShowPolygons = false;
46 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
47 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
48 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
49 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
50 if ((($bShowPolygons?1:0)
55 ) > CONST_PolygonOutput_MaximumTypes) {
56 if (CONST_PolygonOutput_MaximumTypes) {
57 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
59 userError("Polygon output is disabled");
65 // Show address breakdown
66 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
69 $aLangPrefOrder = getPreferredLanguages();
70 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
71 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
72 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
74 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
76 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
78 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
80 $iExcludedPlaceID = (int)$iExcludedPlaceID;
81 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
85 // Only certain ranks of feature
86 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
88 if (isset($_GET['featuretype']))
90 switch($_GET['featuretype'])
93 $iMinAddressRank = $iMaxAddressRank = 4;
96 $iMinAddressRank = $iMaxAddressRank = 8;
99 $iMinAddressRank = 14;
100 $iMaxAddressRank = 16;
103 $iMinAddressRank = 8;
104 $iMaxAddressRank = 20;
109 if (isset($_GET['countrycodes']))
111 $aCountryCodes = array();
112 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
114 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
116 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
119 $sCountryCodesSQL = join(',', $aCountryCodes);
123 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
124 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
126 $sQuery = substr($_SERVER['PATH_INFO'], 1);
128 // reverse order of '/' separated string
129 $aPhrases = explode('/', $sQuery);
130 $aPhrases = array_reverse($aPhrases);
131 $sQuery = join(', ',$aPhrases);
134 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
136 if (!isset($_GET[$sKey])) return false;
137 $sValue = trim($_GET[$sKey]);
138 if (!$sValue) return false;
139 $aStructuredQuery[$sKey] = $sValue;
140 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
141 $iMinAddressRank = $iNewMinAddressRank;
142 $iMaxAddressRank = $iNewMaxAddressRank;
148 $aStructuredOptions = array(
149 array('amenity', 26, 30),
150 array('street', 26, 30),
151 array('city', 14, 24),
152 array('county', 9, 13),
153 array('state', 8, 8),
154 array('country', 4, 4),
155 array('postalcode', 16, 25),
157 $aStructuredQuery = array();
158 $sAllowedTypesSQLList = '';
159 foreach($aStructuredOptions as $aStructuredOption)
161 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
163 if (sizeof($aStructuredQuery) > 0) {
164 $sQuery = join(', ', $aStructuredQuery);
165 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
170 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
172 // Hack to make it handle "new york, ny" (and variants) correctly
173 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
174 if (isset($aLangPrefOrder['name:en']))
176 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
177 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
178 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
181 // If we have a view box create the SQL
182 // Small is the actual view box, Large is double (on each axis) that
183 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
184 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
186 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
187 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
189 if (isset($_GET['viewbox']) && $_GET['viewbox'])
191 $aCoOrdinates = explode(',',$_GET['viewbox']);
192 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
193 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
194 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
195 $aCoOrdinates[0] += $fHeight;
196 $aCoOrdinates[2] -= $fHeight;
197 $aCoOrdinates[1] += $fWidth;
198 $aCoOrdinates[3] -= $fWidth;
199 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
201 $bBoundingBoxSearch = false;
203 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
205 $aPoints = explode(',',$_GET['route']);
206 if (sizeof($aPoints) % 2 != 0)
208 userError("Uneven number of points");
211 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
213 foreach($aPoints as $i => $fPoint)
217 if ($i != 1) $sViewboxCentreSQL .= ",";
218 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
222 $fPrevCoord = (float)$fPoint;
225 $sViewboxCentreSQL .= ")'::geometry,4326)";
227 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
228 $sViewboxSmallSQL = $oDB->getOne($sSQL);
229 if (PEAR::isError($sViewboxSmallSQL))
231 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
233 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
235 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
236 $sViewboxLargeSQL = $oDB->getOne($sSQL);
237 if (PEAR::isError($sViewboxLargeSQL))
239 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
241 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
242 $bBoundingBoxSearch = true;
245 // Do we have anything that looks like a lat/lon pair?
246 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
248 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
249 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
250 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
252 $_GET['nearlat'] = $fQueryLat;
253 $_GET['nearlon'] = $fQueryLon;
254 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
257 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
259 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
260 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
261 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
263 $_GET['nearlat'] = $fQueryLat;
264 $_GET['nearlon'] = $fQueryLon;
265 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
268 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
270 $fQueryLat = $aData[2];
271 $fQueryLon = $aData[3];
272 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
274 $_GET['nearlat'] = $fQueryLat;
275 $_GET['nearlon'] = $fQueryLon;
276 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
280 if ($sQuery || $aStructuredQuery)
282 // Start with a blank search
284 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
285 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
288 $sNearPointSQL = false;
289 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
291 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
292 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
293 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
294 $aSearches[0]['fRadius'] = 0.1;
297 $bSpecialTerms = false;
298 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
299 $aSpecialTerms = array();
300 foreach($aSpecialTermsRaw as $aSpecialTerm)
302 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
303 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
306 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
307 $aSpecialTerms = array();
308 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
310 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
311 unset($aStructuredQuery['amenity']);
313 foreach($aSpecialTermsRaw as $aSpecialTerm)
315 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
316 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
317 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
318 $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';
319 if (CONST_Debug) var_Dump($sSQL);
320 $aSearchWords = $oDB->getAll($sSQL);
321 $aNewSearches = array();
322 foreach($aSearches as $aSearch)
324 foreach($aSearchWords as $aSearchTerm)
326 $aNewSearch = $aSearch;
327 if ($aSearchTerm['country_code'])
329 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
330 $aNewSearches[] = $aNewSearch;
331 $bSpecialTerms = true;
333 if ($aSearchTerm['class'])
335 $aNewSearch['sClass'] = $aSearchTerm['class'];
336 $aNewSearch['sType'] = $aSearchTerm['type'];
337 $aNewSearches[] = $aNewSearch;
338 $bSpecialTerms = true;
342 $aSearches = $aNewSearches;
345 // Split query into phrases
346 // Commas are used to reduce the search space by indicating where phrases split
347 if (sizeof($aStructuredQuery) > 0)
349 $aPhrases = $aStructuredQuery;
350 $bStructuredPhrases = true;
354 $aPhrases = explode(',',$sQuery);
355 $bStructuredPhrases = false;
359 // Convert each phrase to standard form
360 // Create a list of standard words
361 // Get all 'sets' of words
362 // Generate a complete list of all
364 foreach($aPhrases as $iPhrase => $sPhrase)
366 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
367 if (PEAR::isError($aPhrase))
369 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
370 if (CONST_Debug) var_dump($aPhrase);
373 if (trim($aPhrase['string']))
375 $aPhrases[$iPhrase] = $aPhrase;
376 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
377 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
378 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
382 unset($aPhrases[$iPhrase]);
386 // reindex phrases - we make assumptions later on
387 $aPhraseTypes = array_keys($aPhrases);
388 $aPhrases = array_values($aPhrases);
390 if (sizeof($aTokens))
393 // Check which tokens we have, get the ID numbers
394 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
395 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
396 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
397 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
399 if (CONST_Debug) var_Dump($sSQL);
401 $aValidTokens = array();
402 if (sizeof($aTokens))
403 $aDatabaseWords = $oDB->getAll($sSQL);
405 $aDatabaseWords = array();
406 if (PEAR::IsError($aDatabaseWords))
408 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
410 $aPossibleMainWordIDs = array();
411 foreach($aDatabaseWords as $aToken)
413 if (isset($aValidTokens[$aToken['word_token']]))
415 $aValidTokens[$aToken['word_token']][] = $aToken;
419 $aValidTokens[$aToken['word_token']] = array($aToken);
421 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
423 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
425 $aSuggestion = array();
426 $bSuggestion = false;
427 if (CONST_Suggestions_Enabled)
429 foreach($aPhrases as $iPhrase => $aPhrase)
431 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
433 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
434 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
435 $aRow = $aSuggestionWords[0];
436 if ($aRow && $aRow['word'])
438 $aSuggestion[] = $aRow['word'];
443 $aSuggestion[] = $aPhrase['string'];
448 $aSuggestion[] = $aPhrase['string'];
452 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
454 // Try and calculate GB postcodes we might be missing
455 foreach($aTokens as $sToken)
457 // Source of gb postcodes is now definitive - always use
458 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
460 if (substr($aData[1],-2,1) != ' ')
462 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
463 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
465 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
466 if ($aGBPostcodeLocation)
468 $aValidTokens[$sToken] = $aGBPostcodeLocation;
473 foreach($aTokens as $sToken)
475 // Unknown single word token with a number - assume it is a house number
476 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
478 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
482 // Any words that have failed completely?
485 // Start the search process
486 $aResultPlaceIDs = array();
489 Calculate all searches using aValidTokens i.e.
491 'Wodsworth Road, Sheffield' =>
495 0 1 (wodsworth)(road)
498 Score how good the search is so they can be ordered
500 foreach($aPhrases as $iPhrase => $sPhrase)
502 $aNewPhraseSearches = array();
503 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
504 else $sPhraseType = '';
506 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
508 $aWordsetSearches = $aSearches;
510 // Add all words from this wordset
511 foreach($aWordset as $iToken => $sToken)
513 //echo "<br><b>$sToken</b>";
514 $aNewWordsetSearches = array();
516 foreach($aWordsetSearches as $aCurrentSearch)
519 //var_dump($aCurrentSearch);
522 // If the token is valid
523 if (isset($aValidTokens[' '.$sToken]))
525 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
527 $aSearch = $aCurrentSearch;
528 $aSearch['iSearchRank']++;
529 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
531 if ($aSearch['sCountryCode'] === false)
533 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
534 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
535 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
536 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
539 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
541 if ($aSearch['fLat'] === '')
543 $aSearch['fLat'] = $aSearchTerm['lat'];
544 $aSearch['fLon'] = $aSearchTerm['lon'];
545 $aSearch['fRadius'] = $aSearchTerm['radius'];
546 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
549 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
551 if ($aSearch['sHouseNumber'] === '')
553 $aSearch['sHouseNumber'] = $sToken;
554 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
556 // Fall back to not searching for this item (better than nothing)
557 $aSearch = $aCurrentSearch;
558 $aSearch['iSearchRank'] += 1;
559 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
563 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
565 if ($aSearch['sClass'] === '')
567 $aSearch['sOperator'] = $aSearchTerm['operator'];
568 $aSearch['sClass'] = $aSearchTerm['class'];
569 $aSearch['sType'] = $aSearchTerm['type'];
570 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
571 else $aSearch['sOperator'] = 'near'; // near = in for the moment
573 // Do we have a shortcut id?
574 if ($aSearch['sOperator'] == 'name')
576 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
577 if ($iAmenityID = $oDB->getOne($sSQL))
579 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
580 $aSearch['aName'][$iAmenityID] = $iAmenityID;
581 $aSearch['sClass'] = '';
582 $aSearch['sType'] = '';
585 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
588 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
590 if (sizeof($aSearch['aName']))
592 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
594 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
598 $aSearch['iSearchRank'] += 1000; // skip;
603 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
604 // $aSearch['iNamePhrase'] = $iPhrase;
606 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
610 if (isset($aValidTokens[$sToken]))
612 // Allow searching for a word - but at extra cost
613 foreach($aValidTokens[$sToken] as $aSearchTerm)
615 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
617 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
619 $aSearch = $aCurrentSearch;
620 $aSearch['iSearchRank'] += 1;
621 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
622 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
625 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
627 $aSearch = $aCurrentSearch;
628 $aSearch['iSearchRank'] += 2;
629 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
630 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
631 $aSearch['iNamePhrase'] = $iPhrase;
632 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
639 // Allow skipping a word - but at EXTREAM cost
640 //$aSearch = $aCurrentSearch;
641 //$aSearch['iSearchRank']+=100;
642 //$aNewWordsetSearches[] = $aSearch;
646 usort($aNewWordsetSearches, 'bySearchRank');
647 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
649 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
651 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
652 usort($aNewPhraseSearches, 'bySearchRank');
654 $aSearchHash = array();
655 foreach($aNewPhraseSearches as $iSearch => $aSearch)
657 $sHash = serialize($aSearch);
658 if (isset($aSearchHash[$sHash]))
660 unset($aNewPhraseSearches[$iSearch]);
664 $aSearchHash[$sHash] = 1;
668 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
671 // Re-group the searches by their score, junk anything over 20 as just not worth trying
672 $aGroupedSearches = array();
673 foreach($aNewPhraseSearches as $aSearch)
675 if ($aSearch['iSearchRank'] < $iMaxRank)
677 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
678 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
681 ksort($aGroupedSearches);
684 $aSearches = array();
685 foreach($aGroupedSearches as $iScore => $aNewSearches)
687 $iSearchCount += sizeof($aNewSearches);
688 $aSearches = array_merge($aSearches, $aNewSearches);
689 if ($iSearchCount > 50) break;
692 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
698 // Re-group the searches by their score, junk anything over 20 as just not worth trying
699 $aGroupedSearches = array();
700 foreach($aSearches as $aSearch)
702 if ($aSearch['iSearchRank'] < $iMaxRank)
704 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
705 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
708 ksort($aGroupedSearches);
711 if (CONST_Debug) var_Dump($aGroupedSearches);
715 $aCopyGroupedSearches = $aGroupedSearches;
716 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
718 foreach($aSearches as $iSearch => $aSearch)
720 if (sizeof($aSearch['aAddress']))
722 $iReverseItem = array_pop($aSearch['aAddress']);
723 if (isset($aPossibleMainWordIDs[$iReverseItem]))
725 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
726 $aSearch['aName'] = array($iReverseItem);
727 $aGroupedSearches[$iGroup][] = $aSearch;
729 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
730 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
736 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
738 $aCopyGroupedSearches = $aGroupedSearches;
739 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
741 foreach($aSearches as $iSearch => $aSearch)
743 $aReductionsList = array($aSearch['aAddress']);
744 $iSearchRank = $aSearch['iSearchRank'];
745 while(sizeof($aReductionsList) > 0)
748 if ($iSearchRank > iMaxRank) break 3;
749 $aNewReductionsList = array();
750 foreach($aReductionsList as $aReductionsWordList)
752 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
754 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
755 $aReverseSearch = $aSearch;
756 $aSearch['aAddress'] = $aReductionsWordListResult;
757 $aSearch['iSearchRank'] = $iSearchRank;
758 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
759 if (sizeof($aReductionsWordListResult) > 0)
761 $aNewReductionsList[] = $aReductionsWordListResult;
765 $aReductionsList = $aNewReductionsList;
769 ksort($aGroupedSearches);
772 // Filter out duplicate searches
773 $aSearchHash = array();
774 foreach($aGroupedSearches as $iGroup => $aSearches)
776 foreach($aSearches as $iSearch => $aSearch)
778 $sHash = serialize($aSearch);
779 if (isset($aSearchHash[$sHash]))
781 unset($aGroupedSearches[$iGroup][$iSearch]);
782 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
786 $aSearchHash[$sHash] = 1;
791 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
795 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
798 foreach($aSearches as $aSearch)
802 // Must have a location term
803 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
805 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
807 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
809 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
810 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
811 $sSQL .= " order by st_area(geometry) desc limit 1";
812 $aPlaceIDs = $oDB->getCol($sSQL);
817 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
818 if (!$aSearch['sClass']) continue;
819 if (CONST_Debug) var_dump('<hr>',$aSearch);
820 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
821 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
822 if ($oDB->getOne($sSQL))
824 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
825 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
826 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
827 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
828 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
829 $sSQL .= " limit $iLimit";
830 if (CONST_Debug) var_dump($sSQL);
831 $aPlaceIDs = $oDB->getCol($sSQL);
833 if (!sizeof($aPlaceIDs))
835 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
836 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
837 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
838 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
839 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
840 $sSQL .= " limit $iLimit";
841 if (CONST_Debug) var_dump($sSQL);
842 $aPlaceIDs = $oDB->getCol($sSQL);
847 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
848 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
849 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
850 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
851 $sSQL .= " limit $iLimit";
852 if (CONST_Debug) var_dump($sSQL);
853 $aPlaceIDs = $oDB->getCol($sSQL);
859 if (CONST_Debug) var_dump('<hr>',$aSearch);
860 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
861 $aPlaceIDs = array();
863 // First we need a position, either aName or fLat or both
867 // TODO: filter out the pointless search terms (2 letter name tokens and less)
868 // they might be right - but they are just too darned expensive to run
869 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
870 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
871 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
872 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
873 if ($aSearch['fLon'] && $aSearch['fLat'])
875 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
876 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
878 if (sizeof($aExcludePlaceIDs))
880 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
882 if ($sCountryCodesSQL)
884 $aTerms[] = "country_code in ($sCountryCodesSQL)";
887 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
888 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
890 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
892 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
893 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
894 $aOrder[] = "$sImportanceSQL DESC";
898 $sSQL = "select place_id";
899 $sSQL .= " from search_name";
900 $sSQL .= " where ".join(' and ',$aTerms);
901 $sSQL .= " order by ".join(', ',$aOrder);
902 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
903 $sSQL .= " limit 50";
904 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
907 $sSQL .= " limit ".$iLimit;
909 if (CONST_Debug) { var_dump($sSQL); }
910 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
911 if (PEAR::IsError($aViewBoxPlaceIDs))
913 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
915 //var_dump($aViewBoxPlaceIDs);
916 // Did we have an viewbox matches?
917 $aPlaceIDs = array();
918 $bViewBoxMatch = false;
919 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
921 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
922 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
923 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
924 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
925 $aPlaceIDs[] = $aViewBoxRow['place_id'];
928 //var_Dump($aPlaceIDs);
931 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
933 $aRoadPlaceIDs = $aPlaceIDs;
934 $sPlaceIDs = join(',',$aPlaceIDs);
936 // Now they are indexed look for a house attached to a street we found
937 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
938 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
939 if (sizeof($aExcludePlaceIDs))
941 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
943 $sSQL .= " limit $iLimit";
944 if (CONST_Debug) var_dump($sSQL);
945 $aPlaceIDs = $oDB->getCol($sSQL);
947 // If not try the aux fallback table
948 if (!sizeof($aPlaceIDs))
950 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
951 if (sizeof($aExcludePlaceIDs))
953 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
955 // $sSQL .= " limit $iLimit";
956 if (CONST_Debug) var_dump($sSQL);
957 $aPlaceIDs = $oDB->getCol($sSQL);
960 if (!sizeof($aPlaceIDs))
962 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
963 if (sizeof($aExcludePlaceIDs))
965 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
967 // $sSQL .= " limit $iLimit";
968 if (CONST_Debug) var_dump($sSQL);
969 $aPlaceIDs = $oDB->getCol($sSQL);
972 // Fallback to the road
973 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
975 $aPlaceIDs = $aRoadPlaceIDs;
980 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
982 $sPlaceIDs = join(',',$aPlaceIDs);
984 $aClassPlaceIDs = array();
986 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
988 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
989 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
990 $sSQL .= " and linked_place_id is null";
991 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
992 $sSQL .= " order by rank_search asc limit $iLimit";
993 if (CONST_Debug) var_dump($sSQL);
994 $aClassPlaceIDs = $oDB->getCol($sSQL);
997 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
999 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1000 $bCacheTable = $oDB->getOne($sSQL);
1002 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1004 if (CONST_Debug) var_dump($sSQL);
1005 $iMaxRank = ((int)$oDB->getOne($sSQL));
1007 // For state / country level searches the normal radius search doesn't work very well
1008 $sPlaceGeom = false;
1009 if ($iMaxRank < 9 && $bCacheTable)
1011 // Try and get a polygon to search in instead
1012 $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";
1013 if (CONST_Debug) var_dump($sSQL);
1014 $sPlaceGeom = $oDB->getOne($sSQL);
1024 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1025 if (CONST_Debug) var_dump($sSQL);
1026 $aPlaceIDs = $oDB->getCol($sSQL);
1027 $sPlaceIDs = join(',',$aPlaceIDs);
1030 if ($sPlaceIDs || $sPlaceGeom)
1036 // More efficient - can make the range bigger
1040 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1041 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1042 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1044 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1045 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1048 $sSQL .= ",placex as f where ";
1049 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1054 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1056 if (sizeof($aExcludePlaceIDs))
1058 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1060 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1061 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1062 if ($iOffset) $sSQL .= " offset $iOffset";
1063 $sSQL .= " limit $iLimit";
1064 if (CONST_Debug) var_dump($sSQL);
1065 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1069 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1072 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1073 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1075 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1076 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1077 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1078 if (sizeof($aExcludePlaceIDs))
1080 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1082 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1083 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1084 if ($iOffset) $sSQL .= " offset $iOffset";
1085 $sSQL .= " limit $iLimit";
1086 if (CONST_Debug) var_dump($sSQL);
1087 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1092 $aPlaceIDs = $aClassPlaceIDs;
1098 if (PEAR::IsError($aPlaceIDs))
1100 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1103 if (CONST_Debug) var_Dump($aPlaceIDs);
1105 foreach($aPlaceIDs as $iPlaceID)
1107 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1109 if ($iQueryLoop > 20) break;
1113 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1114 if ($iGroupLoop > 4) break;
1115 if ($iQueryLoop > 30) break;
1118 // Did we find anything?
1119 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1121 //var_Dump($aResultPlaceIDs);exit;
1122 // Get the details for display (is this a redundant extra step?)
1123 $sPlaceIDs = join(',',$aResultPlaceIDs);
1124 $sOrderSQL = 'CASE ';
1125 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1127 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1129 $sOrderSQL .= ' ELSE 10000000 END';
1130 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1131 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1132 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1133 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1134 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1135 // $sSQL .= $sOrderSQL." as porder, ";
1136 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1137 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1138 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1139 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1140 $sSQL .= "and linked_place_id is null ";
1141 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1142 if (!$bDeDupe) $sSQL .= ",place_id";
1143 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1144 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1145 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1147 $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,";
1148 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1149 $sSQL .= "null as placename,";
1150 $sSQL .= "null as ref,";
1151 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1152 // $sSQL .= $sOrderSQL." as porder, ";
1153 $sSQL .= "-0.15 as importance ";
1154 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1155 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1156 $sSQL .= "group by place_id";
1157 if (!$bDeDupe) $sSQL .= ",place_id";
1159 $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,";
1160 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1161 $sSQL .= "null as placename,";
1162 $sSQL .= "null as ref,";
1163 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1164 // $sSQL .= $sOrderSQL." as porder, ";
1165 $sSQL .= "-0.10 as importance ";
1166 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1167 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1168 $sSQL .= "group by place_id";
1169 if (!$bDeDupe) $sSQL .= ",place_id";
1170 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1171 $sSQL .= "order by importance desc";
1172 // $sSQL .= "order by rank_search,rank_address,porder asc";
1173 if (CONST_Debug) var_dump('<hr>',$sSQL);
1174 $aSearchResults = $oDB->getAll($sSQL);
1175 //var_dump($sSQL,$aSearchResults);exit;
1177 if (PEAR::IsError($aSearchResults))
1179 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1182 } // end if ($sQuery)
1185 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1187 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1188 $aResultPlaceIDs = array($iPlaceID);
1190 // TODO: this needs refactoring!
1192 // Get the details for display (is this a redundant extra step?)
1193 $sPlaceIDs = join(',',$aResultPlaceIDs);
1194 $sOrderSQL = 'CASE ';
1195 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1197 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1199 $sOrderSQL .= ' ELSE 10000000 END';
1200 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1201 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1202 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1203 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1204 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1205 // $sSQL .= $sOrderSQL." as porder, ";
1206 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1207 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1208 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1209 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1210 if (!$bDeDupe) $sSQL .= ",place_id";
1211 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1212 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1213 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1215 $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,";
1216 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1217 $sSQL .= "null as placename,";
1218 $sSQL .= "null as ref,";
1219 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1220 // $sSQL .= $sOrderSQL." as porder, ";
1221 $sSQL .= "-0.15 as importance ";
1222 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1223 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1224 $sSQL .= "group by place_id";
1225 if (!$bDeDupe) $sSQL .= ",place_id";
1227 $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,";
1228 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1229 $sSQL .= "null as placename,";
1230 $sSQL .= "null as ref,";
1231 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1232 // $sSQL .= $sOrderSQL." as porder, ";
1233 $sSQL .= "-0.10 as importance ";
1234 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1235 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1236 $sSQL .= "group by place_id";
1237 if (!$bDeDupe) $sSQL .= ",place_id";
1238 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1239 $sSQL .= "order by importance desc";
1240 // $sSQL .= "order by rank_search,rank_address,porder asc";
1241 if (CONST_Debug) var_dump('<hr>',$sSQL);
1242 $aSearchResults = $oDB->getAll($sSQL);
1243 //var_dump($sSQL,$aSearchResults);exit;
1245 if (PEAR::IsError($aSearchResults))
1247 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1253 $sSearchResult = '';
1254 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1256 $sSearchResult = 'No Results Found';
1258 //var_Dump($aSearchResults);
1260 $aClassType = getClassTypesWithImportance();
1261 $aRecheckWords = preg_split('/\b/',$sQuery);
1262 foreach($aRecheckWords as $i => $sWord)
1264 if (!$sWord) unset($aRecheckWords[$i]);
1266 foreach($aSearchResults as $iResNum => $aResult)
1268 if (CONST_Search_AreaPolygons)
1270 // Get the bounding box and outline polygon
1271 $sSQL = "select place_id,numfeatures,area,outline,";
1272 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1273 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1274 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1276 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1277 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1278 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1279 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1280 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1281 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1282 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1283 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1284 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1285 $aPointPolygon = $oDB->getRow($sSQL);
1286 if (PEAR::IsError($aPointPolygon))
1288 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1290 if ($aPointPolygon['place_id'])
1292 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1293 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1294 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1295 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1297 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1298 $aResult['lat'] = $aPointPolygon['centrelat'];
1299 $aResult['lon'] = $aPointPolygon['centrelon'];
1303 // Translate geometary string to point array
1304 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1306 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1308 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1310 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1312 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1315 $iSteps = ($fRadius * 40000)^2;
1316 $fStepSize = (2*pi())/$iSteps;
1317 $aPolyPoints = array();
1318 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1320 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1322 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1323 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1324 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1325 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1329 // Output data suitable for display (points and a bounding box)
1330 if ($bShowPolygons && isset($aPolyPoints))
1332 $aResult['aPolyPoints'] = array();
1333 foreach($aPolyPoints as $aPoint)
1335 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1338 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1342 if (!isset($aResult['aBoundingBox']))
1345 $fDiameter = 0.0001;
1347 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1348 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1350 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1352 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1353 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1355 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1357 $fRadius = $fDiameter / 2;
1359 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1360 $fStepSize = (2*pi())/$iSteps;
1361 $aPolyPoints = array();
1362 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1364 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1366 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1367 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1368 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1369 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1371 // Output data suitable for display (points and a bounding box)
1374 $aResult['aPolyPoints'] = array();
1375 foreach($aPolyPoints as $aPoint)
1377 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1380 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1383 // Is there an icon set for this type of result?
1384 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1385 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1387 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1390 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1391 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1393 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1396 if ($bShowAddressDetails)
1398 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1399 //var_dump($aResult['address']);
1403 // Adjust importance for the number of exact string matches in the result
1404 $aResult['importance'] = max(0.001,$aResult['importance']);
1406 $sAddress = $aResult['langaddress'];
1407 foreach($aRecheckWords as $i => $sWord)
1409 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1411 $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
1413 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1415 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1416 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1418 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1420 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1421 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1423 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1427 $aResult['importance'] = 1000000000000000;
1430 $aResult['name'] = $aResult['langaddress'];
1431 $aResult['foundorder'] = $iResNum;
1432 $aSearchResults[$iResNum] = $aResult;
1434 uasort($aSearchResults, 'byImportance');
1436 //var_dump($aSearchResults);exit;
1438 $aOSMIDDone = array();
1439 $aClassTypeNameDone = array();
1440 $aToFilter = $aSearchResults;
1441 $aSearchResults = array();
1444 foreach($aToFilter as $iResNum => $aResult)
1446 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1447 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1450 $fLat = $aResult['lat'];
1451 $fLon = $aResult['lon'];
1452 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1455 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1456 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1458 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1459 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1460 $aSearchResults[] = $aResult;
1463 // Absolute limit on number of results
1464 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1467 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1469 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1471 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1476 logEnd($oDB, $hLog, sizeof($aToFilter));
1478 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1479 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1480 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1481 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1482 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1483 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1486 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1488 $sMoreURL .= '&q='.urlencode($sQuery);
1490 if (CONST_Debug) exit;
1492 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');