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 $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
23 if ($iLimit > 100) $iLimit = 100;
25 $iMaxAddressRank = 30;
28 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
30 $sOutputFormat = $_GET['format'];
33 // Show / use polygons
34 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
35 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
36 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
37 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
38 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
39 if ((($bShowPolygons?1:0)
44 ) > CONST_PolygonOutput_MaximumTypes) {
45 if (CONST_PolygonOutput_MaximumTypes) {
46 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
48 userError("Polygon output is disabled");
53 // Show address breakdown
54 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
57 $aLangPrefOrder = getPreferredLanguages();
58 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
59 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
60 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
62 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
64 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
66 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
68 $iExcludedPlaceID = (int)$iExcludedPlaceID;
69 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
73 // Only certain ranks of feature
74 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
76 if (isset($_GET['featuretype']))
78 switch($_GET['featuretype'])
81 $iMinAddressRank = $iMaxAddressRank = 4;
84 $iMinAddressRank = $iMaxAddressRank = 8;
87 $iMinAddressRank = 14;
88 $iMaxAddressRank = 16;
92 $iMaxAddressRank = 20;
97 if (isset($_GET['countrycodes']))
99 $aCountryCodes = array();
100 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
102 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
104 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
107 $sCountryCodesSQL = join(',', $aCountryCodes);
111 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
112 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
114 $sQuery = substr($_SERVER['PATH_INFO'], 1);
116 // reverse order of '/' separated string
117 $aPhrases = explode('/', $sQuery);
118 $aPhrases = array_reverse($aPhrases);
119 $sQuery = join(', ',$aPhrases);
122 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
124 if (!isset($_GET[$sKey])) return false;
125 $sValue = trim($_GET[$sKey]);
126 if (!$sValue) return false;
127 $aStructuredQuery[$sKey] = $sValue;
128 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
129 $iMinAddressRank = $iNewMinAddressRank;
130 $iMaxAddressRank = $iNewMaxAddressRank;
136 $aStructuredOptions = array(
137 array('amenity', 26, 30),
138 array('street', 26, 30),
139 array('city', 14, 24),
140 array('county', 9, 13),
141 array('state', 8, 8),
142 array('country', 4, 4),
143 array('postalcode', 16, 25),
145 $aStructuredQuery = array();
146 foreach($aStructuredOptions as $aStructuredOption)
148 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
150 if (sizeof($aStructuredQuery) > 0) {
151 $sQuery = join(', ', $aStructuredQuery);
156 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
158 // Hack to make it handle "new york, ny" (and variants) correctly
159 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
160 if (isset($aLangPrefOrder['name:en']))
162 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
163 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
164 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
167 // If we have a view box create the SQL
168 // Small is the actual view box, Large is double (on each axis) that
169 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
170 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
172 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
173 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
175 if (isset($_GET['viewbox']) && $_GET['viewbox'])
177 $aCoOrdinates = explode(',',$_GET['viewbox']);
178 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
179 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
180 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
181 $aCoOrdinates[0] += $fHeight;
182 $aCoOrdinates[2] -= $fHeight;
183 $aCoOrdinates[1] += $fWidth;
184 $aCoOrdinates[3] -= $fWidth;
185 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
187 $bBoundingBoxSearch = false;
189 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
191 $aPoints = explode(',',$_GET['route']);
192 if (sizeof($aPoints) % 2 != 0)
194 userError("Uneven number of points");
197 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
199 foreach($aPoints as $i => $fPoint)
203 if ($i != 1) $sViewboxCentreSQL .= ",";
204 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
208 $fPrevCoord = (float)$fPoint;
211 $sViewboxCentreSQL .= ")'::geometry,4326)";
213 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
214 $sViewboxSmallSQL = $oDB->getOne($sSQL);
215 if (PEAR::isError($sViewboxSmallSQL))
217 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
219 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
221 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
222 $sViewboxLargeSQL = $oDB->getOne($sSQL);
223 if (PEAR::isError($sViewboxLargeSQL))
225 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
227 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
230 // Do we have anything that looks like a lat/lon pair?
231 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
233 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
234 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
235 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
237 $_GET['nearlat'] = $fQueryLat;
238 $_GET['nearlon'] = $fQueryLon;
239 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
242 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
244 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
245 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
246 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
248 $_GET['nearlat'] = $fQueryLat;
249 $_GET['nearlon'] = $fQueryLon;
250 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
253 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
255 $fQueryLat = $aData[2];
256 $fQueryLon = $aData[3];
257 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
259 $_GET['nearlat'] = $fQueryLat;
260 $_GET['nearlon'] = $fQueryLon;
261 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
265 if ($sQuery || $aStructuredQuery)
267 // Start with a blank search
269 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
270 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
273 $sNearPointSQL = false;
274 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
276 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
277 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
278 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
279 $aSearches[0]['fRadius'] = 0.1;
282 $bSpecialTerms = false;
283 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
284 $aSpecialTerms = array();
285 foreach($aSpecialTermsRaw as $aSpecialTerm)
287 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
288 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
291 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
292 $aSpecialTerms = array();
293 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
295 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
296 unset($aStructuredQuery['amenity']);
298 foreach($aSpecialTermsRaw as $aSpecialTerm)
300 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
301 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
302 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
303 $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';
304 if (CONST_Debug) var_Dump($sSQL);
305 $aSearchWords = $oDB->getAll($sSQL);
306 $aNewSearches = array();
307 foreach($aSearches as $aSearch)
309 foreach($aSearchWords as $aSearchTerm)
311 $aNewSearch = $aSearch;
312 if ($aSearchTerm['country_code'])
314 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
315 $aNewSearches[] = $aNewSearch;
316 $bSpecialTerms = true;
318 if ($aSearchTerm['class'])
320 $aNewSearch['sClass'] = $aSearchTerm['class'];
321 $aNewSearch['sType'] = $aSearchTerm['type'];
322 $aNewSearches[] = $aNewSearch;
323 $bSpecialTerms = true;
327 $aSearches = $aNewSearches;
330 // Split query into phrases
331 // Commas are used to reduce the search space by indicating where phrases split
332 if (sizeof($aStructuredQuery) > 0)
334 $aPhrases = $aStructuredQuery;
335 $bStructuredPhrases = true;
339 $aPhrases = explode(',',$sQuery);
340 $bStructuredPhrases = false;
344 // Convert each phrase to standard form
345 // Create a list of standard words
346 // Get all 'sets' of words
347 // Generate a complete list of all
349 foreach($aPhrases as $iPhrase => $sPhrase)
351 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
352 if (PEAR::isError($aPhrase))
354 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
355 if (CONST_Debug) var_dump($aPhrase);
358 if (trim($aPhrase['string']))
360 $aPhrases[$iPhrase] = $aPhrase;
361 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
362 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
363 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
367 unset($aPhrases[$iPhrase]);
371 // reindex phrases - we make assumptions later on
372 $aPhraseTypes = array_keys($aPhrases);
373 $aPhrases = array_values($aPhrases);
375 if (sizeof($aTokens))
378 // Check which tokens we have, get the ID numbers
379 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
380 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
381 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
382 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
384 if (CONST_Debug) var_Dump($sSQL);
386 $aValidTokens = array();
387 if (sizeof($aTokens))
388 $aDatabaseWords = $oDB->getAll($sSQL);
390 $aDatabaseWords = array();
391 if (PEAR::IsError($aDatabaseWords))
393 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
395 $aPossibleMainWordIDs = array();
396 foreach($aDatabaseWords as $aToken)
398 if (isset($aValidTokens[$aToken['word_token']]))
400 $aValidTokens[$aToken['word_token']][] = $aToken;
404 $aValidTokens[$aToken['word_token']] = array($aToken);
406 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
408 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
410 $aSuggestion = array();
411 $bSuggestion = false;
412 if (CONST_Suggestions_Enabled)
414 foreach($aPhrases as $iPhrase => $aPhrase)
416 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
418 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
419 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
420 $aRow = $aSuggestionWords[0];
421 if ($aRow && $aRow['word'])
423 $aSuggestion[] = $aRow['word'];
428 $aSuggestion[] = $aPhrase['string'];
433 $aSuggestion[] = $aPhrase['string'];
437 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
439 // Try and calculate GB postcodes we might be missing
440 foreach($aTokens as $sToken)
442 // Source of gb postcodes is now definitive - always use
443 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
445 if (substr($aData[1],-2,1) != ' ')
447 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
448 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
450 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
451 if ($aGBPostcodeLocation)
453 $aValidTokens[$sToken] = $aGBPostcodeLocation;
458 foreach($aTokens as $sToken)
460 // Unknown single word token with a number - assume it is a house number
461 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
463 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
467 // Any words that have failed completely?
470 // Start the search process
471 $aResultPlaceIDs = array();
474 Calculate all searches using aValidTokens i.e.
476 'Wodsworth Road, Sheffield' =>
480 0 1 (wodsworth)(road)
483 Score how good the search is so they can be ordered
485 foreach($aPhrases as $iPhrase => $sPhrase)
487 $aNewPhraseSearches = array();
488 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
489 else $sPhraseType = '';
491 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
493 $aWordsetSearches = $aSearches;
495 // Add all words from this wordset
496 foreach($aWordset as $iToken => $sToken)
498 //echo "<br><b>$sToken</b>";
499 $aNewWordsetSearches = array();
501 foreach($aWordsetSearches as $aCurrentSearch)
504 //var_dump($aCurrentSearch);
507 // If the token is valid
508 if (isset($aValidTokens[' '.$sToken]))
510 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
512 $aSearch = $aCurrentSearch;
513 $aSearch['iSearchRank']++;
514 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
516 if ($aSearch['sCountryCode'] === false)
518 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
519 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
520 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
521 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
524 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
526 if ($aSearch['fLat'] === '')
528 $aSearch['fLat'] = $aSearchTerm['lat'];
529 $aSearch['fLon'] = $aSearchTerm['lon'];
530 $aSearch['fRadius'] = $aSearchTerm['radius'];
531 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
534 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
536 if ($aSearch['sHouseNumber'] === '')
538 $aSearch['sHouseNumber'] = $sToken;
539 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
541 // Fall back to not searching for this item (better than nothing)
542 $aSearch = $aCurrentSearch;
543 $aSearch['iSearchRank'] += 1;
544 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
548 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
550 if ($aSearch['sClass'] === '')
552 $aSearch['sOperator'] = $aSearchTerm['operator'];
553 $aSearch['sClass'] = $aSearchTerm['class'];
554 $aSearch['sType'] = $aSearchTerm['type'];
555 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
556 else $aSearch['sOperator'] = 'near'; // near = in for the moment
558 // Do we have a shortcut id?
559 if ($aSearch['sOperator'] == 'name')
561 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
562 if ($iAmenityID = $oDB->getOne($sSQL))
564 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
565 $aSearch['aName'][$iAmenityID] = $iAmenityID;
566 $aSearch['sClass'] = '';
567 $aSearch['sType'] = '';
570 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
573 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
575 if (sizeof($aSearch['aName']))
577 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
579 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
583 $aSearch['iSearchRank'] += 1000; // skip;
588 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
589 // $aSearch['iNamePhrase'] = $iPhrase;
591 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
595 if (isset($aValidTokens[$sToken]))
597 // Allow searching for a word - but at extra cost
598 foreach($aValidTokens[$sToken] as $aSearchTerm)
600 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
602 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
604 $aSearch = $aCurrentSearch;
605 $aSearch['iSearchRank'] += 1;
606 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
607 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
610 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
612 $aSearch = $aCurrentSearch;
613 $aSearch['iSearchRank'] += 2;
614 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
615 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
616 $aSearch['iNamePhrase'] = $iPhrase;
617 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
624 // Allow skipping a word - but at EXTREAM cost
625 //$aSearch = $aCurrentSearch;
626 //$aSearch['iSearchRank']+=100;
627 //$aNewWordsetSearches[] = $aSearch;
631 usort($aNewWordsetSearches, 'bySearchRank');
632 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
634 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
636 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
637 usort($aNewPhraseSearches, 'bySearchRank');
639 $aSearchHash = array();
640 foreach($aNewPhraseSearches as $iSearch => $aSearch)
642 $sHash = serialize($aSearch);
643 if (isset($aSearchHash[$sHash]))
645 unset($aNewPhraseSearches[$iSearch]);
649 $aSearchHash[$sHash] = 1;
653 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
656 // Re-group the searches by their score, junk anything over 20 as just not worth trying
657 $aGroupedSearches = array();
658 foreach($aNewPhraseSearches as $aSearch)
660 if ($aSearch['iSearchRank'] < $iMaxRank)
662 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
663 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
666 ksort($aGroupedSearches);
669 $aSearches = array();
670 foreach($aGroupedSearches as $iScore => $aNewSearches)
672 $iSearchCount += sizeof($aNewSearches);
673 $aSearches = array_merge($aSearches, $aNewSearches);
674 if ($iSearchCount > 50) break;
677 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
683 // Re-group the searches by their score, junk anything over 20 as just not worth trying
684 $aGroupedSearches = array();
685 foreach($aSearches as $aSearch)
687 if ($aSearch['iSearchRank'] < $iMaxRank)
689 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
690 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
693 ksort($aGroupedSearches);
696 if (CONST_Debug) var_Dump($aGroupedSearches);
700 $aCopyGroupedSearches = $aGroupedSearches;
701 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
703 foreach($aSearches as $iSearch => $aSearch)
705 if (sizeof($aSearch['aAddress']))
707 $iReverseItem = array_pop($aSearch['aAddress']);
708 if (isset($aPossibleMainWordIDs[$iReverseItem]))
710 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
711 $aSearch['aName'] = array($iReverseItem);
712 $aGroupedSearches[$iGroup][] = $aSearch;
714 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
715 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
721 // Filter out duplicate searches
722 $aSearchHash = array();
723 foreach($aGroupedSearches as $iGroup => $aSearches)
725 foreach($aSearches as $iSearch => $aSearch)
727 $sHash = serialize($aSearch);
728 if (isset($aSearchHash[$sHash]))
730 unset($aGroupedSearches[$iGroup][$iSearch]);
731 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
735 $aSearchHash[$sHash] = 1;
740 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
744 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
747 foreach($aSearches as $aSearch)
751 // Must have a location term
752 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
754 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
756 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
758 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
759 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
760 $sSQL .= " order by st_area(geometry) desc limit 1";
761 $aPlaceIDs = $oDB->getCol($sSQL);
766 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
767 if (!$aSearch['sClass']) continue;
768 if (CONST_Debug) var_dump('<hr>',$aSearch);
769 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
771 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
772 if ($oDB->getOne($sSQL))
774 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
775 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
776 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid) and linked_place_id is null";
777 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
778 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
779 $sSQL .= " limit $iLimit";
780 if (CONST_Debug) var_dump($sSQL);
781 $aPlaceIDs = $oDB->getCol($sSQL);
783 if (!sizeof($aPlaceIDs))
785 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
786 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
787 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid) and linked_place_id is null";
788 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
789 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
790 $sSQL .= " limit $iLimit";
791 if (CONST_Debug) var_dump($sSQL);
792 $aPlaceIDs = $oDB->getCol($sSQL);
797 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
798 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
799 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
800 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
801 $sSQL .= " limit $iLimit";
802 if (CONST_Debug) var_dump($sSQL);
803 $aPlaceIDs = $oDB->getCol($sSQL);
809 if (CONST_Debug) var_dump('<hr>',$aSearch);
810 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
811 $aPlaceIDs = array();
813 // First we need a position, either aName or fLat or both
817 // TODO: filter out the pointless search terms (2 letter name tokens and less)
818 // they might be right - but they are just too darned expensive to run
819 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
820 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
821 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
822 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
823 if ($aSearch['fLon'] && $aSearch['fLat'])
825 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
826 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
828 if (sizeof($aExcludePlaceIDs))
830 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
832 if ($sCountryCodesSQL)
834 $aTerms[] = "country_code in ($sCountryCodesSQL)";
837 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
838 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
840 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
842 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
843 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
844 $aOrder[] = "$sImportanceSQL DESC";
848 $sSQL = "select place_id";
849 $sSQL .= " from search_name";
850 $sSQL .= " where ".join(' and ',$aTerms);
851 $sSQL .= " order by ".join(', ',$aOrder);
852 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
853 $sSQL .= " limit 50";
854 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
857 $sSQL .= " limit ".$iLimit;
859 if (CONST_Debug) var_dump($sSQL);
860 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
861 if (PEAR::IsError($aViewBoxPlaceIDs))
863 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
865 //var_dump($aViewBoxPlaceIDs);
866 // Did we have an viewbox matches?
867 $aPlaceIDs = array();
868 $bViewBoxMatch = false;
869 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
871 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
872 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
873 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
874 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
875 $aPlaceIDs[] = $aViewBoxRow['place_id'];
878 //var_Dump($aPlaceIDs);
881 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
883 $aRoadPlaceIDs = $aPlaceIDs;
884 $sPlaceIDs = join(',',$aPlaceIDs);
886 // Now they are indexed look for a house attached to a street we found
887 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
888 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
889 if (sizeof($aExcludePlaceIDs))
891 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
893 $sSQL .= " limit $iLimit";
894 if (CONST_Debug) var_dump($sSQL);
895 $aPlaceIDs = $oDB->getCol($sSQL);
897 // If not try the aux fallback table
898 if (!sizeof($aPlaceIDs))
900 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
901 if (sizeof($aExcludePlaceIDs))
903 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
905 // $sSQL .= " limit $iLimit";
906 if (CONST_Debug) var_dump($sSQL);
907 $aPlaceIDs = $oDB->getCol($sSQL);
910 if (!sizeof($aPlaceIDs))
912 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
913 if (sizeof($aExcludePlaceIDs))
915 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
917 // $sSQL .= " limit $iLimit";
918 if (CONST_Debug) var_dump($sSQL);
919 $aPlaceIDs = $oDB->getCol($sSQL);
922 // Fallback to the road
923 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
925 $aPlaceIDs = $aRoadPlaceIDs;
930 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
932 $sPlaceIDs = join(',',$aPlaceIDs);
934 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
936 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
937 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
938 $sSQL .= " and linked_place_id is null";
939 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
940 $sSQL .= " order by rank_search asc limit $iLimit";
941 if (CONST_Debug) var_dump($sSQL);
942 $aPlaceIDs = $oDB->getCol($sSQL);
945 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
947 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
948 $bCacheTable = $oDB->getOne($sSQL);
950 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
952 if (CONST_Debug) var_dump($sSQL);
953 $iMaxRank = ((int)$oDB->getOne($sSQL));
955 // For state / country level searches the normal radius search doesn't work very well
957 if ($iMaxRank < 9 && $bCacheTable)
959 // Try and get a polygon to search in instead
960 $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";
961 if (CONST_Debug) var_dump($sSQL);
962 $sPlaceGeom = $oDB->getOne($sSQL);
972 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
973 if (CONST_Debug) var_dump($sSQL);
974 $aPlaceIDs = $oDB->getCol($sSQL);
975 $sPlaceIDs = join(',',$aPlaceIDs);
978 if ($sPlaceIDs || $sPlaceGeom)
984 // More efficient - can make the range bigger
988 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
989 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
990 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
992 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
993 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
996 $sSQL .= ",placex as f where ";
997 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1002 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1004 if (sizeof($aExcludePlaceIDs))
1006 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1008 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1009 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1010 if ($iOffset) $sSQL .= " offset $iOffset";
1011 $sSQL .= " limit $iLimit";
1012 if (CONST_Debug) var_dump($sSQL);
1013 $aPlaceIDs = $oDB->getCol($sSQL);
1017 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1020 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1021 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1023 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1024 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1025 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1026 if (sizeof($aExcludePlaceIDs))
1028 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1030 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1031 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1032 if ($iOffset) $sSQL .= " offset $iOffset";
1033 $sSQL .= " limit $iLimit";
1034 if (CONST_Debug) var_dump($sSQL);
1035 $aPlaceIDs = $oDB->getCol($sSQL);
1043 if (PEAR::IsError($aPlaceIDs))
1045 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1048 if (CONST_Debug) var_Dump($aPlaceIDs);
1050 foreach($aPlaceIDs as $iPlaceID)
1052 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1054 if ($iQueryLoop > 20) break;
1057 if (sizeof($aResultPlaceIDs)) break;
1058 if ($iGroupLoop > 4) break;
1059 if ($iQueryLoop > 30) break;
1062 // Did we find anything?
1063 if (sizeof($aResultPlaceIDs))
1065 //var_Dump($aResultPlaceIDs);exit;
1066 // Get the details for display (is this a redundant extra step?)
1067 $sPlaceIDs = join(',',$aResultPlaceIDs);
1068 $sOrderSQL = 'CASE ';
1069 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1071 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1073 $sOrderSQL .= ' ELSE 10000000 END';
1074 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1075 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1076 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1077 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1078 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1079 // $sSQL .= $sOrderSQL." as porder, ";
1080 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1081 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1082 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1083 $sSQL .= "and linked_place_id is null ";
1084 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1085 if (!$bDeDupe) $sSQL .= ",place_id";
1086 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1087 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1088 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1090 $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,";
1091 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1092 $sSQL .= "null as placename,";
1093 $sSQL .= "null as ref,";
1094 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1095 // $sSQL .= $sOrderSQL." as porder, ";
1096 $sSQL .= "-0.15 as importance ";
1097 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1098 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1099 $sSQL .= "group by place_id";
1100 if (!$bDeDupe) $sSQL .= ",place_id";
1102 $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,";
1103 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1104 $sSQL .= "null as placename,";
1105 $sSQL .= "null as ref,";
1106 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1107 // $sSQL .= $sOrderSQL." as porder, ";
1108 $sSQL .= "-0.10 as importance ";
1109 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1110 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1111 $sSQL .= "group by place_id";
1112 if (!$bDeDupe) $sSQL .= ",place_id";
1113 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1114 $sSQL .= "order by importance desc";
1115 // $sSQL .= "order by rank_search,rank_address,porder asc";
1116 if (CONST_Debug) var_dump('<hr>',$sSQL);
1117 $aSearchResults = $oDB->getAll($sSQL);
1118 //var_dump($sSQL,$aSearchResults);exit;
1120 if (PEAR::IsError($aSearchResults))
1122 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1125 } // end if ($sQuery)
1128 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1130 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1131 $aResultPlaceIDs = array($iPlaceID);
1133 // TODO: this needs refactoring!
1135 // Get the details for display (is this a redundant extra step?)
1136 $sPlaceIDs = join(',',$aResultPlaceIDs);
1137 $sOrderSQL = 'CASE ';
1138 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1140 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1142 $sOrderSQL .= ' ELSE 10000000 END';
1143 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1144 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1145 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1146 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1147 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1148 // $sSQL .= $sOrderSQL." as porder, ";
1149 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1150 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1151 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1152 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1153 if (!$bDeDupe) $sSQL .= ",place_id";
1154 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1155 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1156 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1158 $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,";
1159 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1160 $sSQL .= "null as placename,";
1161 $sSQL .= "null as ref,";
1162 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1163 // $sSQL .= $sOrderSQL." as porder, ";
1164 $sSQL .= "-0.15 as importance ";
1165 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1166 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1167 $sSQL .= "group by place_id";
1168 if (!$bDeDupe) $sSQL .= ",place_id";
1170 $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,";
1171 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1172 $sSQL .= "null as placename,";
1173 $sSQL .= "null as ref,";
1174 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1175 // $sSQL .= $sOrderSQL." as porder, ";
1176 $sSQL .= "-0.10 as importance ";
1177 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1178 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1179 $sSQL .= "group by place_id";
1180 if (!$bDeDupe) $sSQL .= ",place_id";
1181 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1182 $sSQL .= "order by importance desc";
1183 // $sSQL .= "order by rank_search,rank_address,porder asc";
1184 if (CONST_Debug) var_dump('<hr>',$sSQL);
1185 $aSearchResults = $oDB->getAll($sSQL);
1186 //var_dump($sSQL,$aSearchResults);exit;
1188 if (PEAR::IsError($aSearchResults))
1190 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1196 $sSearchResult = '';
1197 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1199 $sSearchResult = 'No Results Found';
1201 //var_Dump($aSearchResults);
1203 $aClassType = getClassTypesWithImportance();
1204 $aRecheckWords = preg_split('/\b/',$sQuery);
1205 foreach($aRecheckWords as $i => $sWord)
1207 if (!$sWord) unset($aRecheckWords[$i]);
1209 foreach($aSearchResults as $iResNum => $aResult)
1211 if (CONST_Search_AreaPolygons)
1213 // Get the bounding box and outline polygon
1214 $sSQL = "select place_id,numfeatures,area,outline,";
1215 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1216 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1217 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1219 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1220 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1221 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1222 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1223 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1224 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1225 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1226 if ($bAsText) $sSQL .= ",ST_AsText(geometry) as astext";
1227 if ($bShowPolygons) $sSQL .= ",ST_AsText(geometry) as outlinestring";
1228 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1229 $aPointPolygon = $oDB->getRow($sSQL);
1230 if (PEAR::IsError($aPointPolygon))
1232 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1234 if ($aPointPolygon['place_id'])
1236 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1237 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1238 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1239 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1241 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1242 $aResult['lat'] = $aPointPolygon['centrelat'];
1243 $aResult['lon'] = $aPointPolygon['centrelon'];
1247 // Translate geometary string to point array
1248 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1250 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1252 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1254 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1256 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1259 $iSteps = ($fRadius * 40000)^2;
1260 $fStepSize = (2*pi())/$iSteps;
1261 $aPolyPoints = array();
1262 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1264 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1266 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1267 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1268 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1269 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1273 // Output data suitable for display (points and a bounding box)
1274 if ($bShowPolygons && isset($aPolyPoints))
1276 $aResult['aPolyPoints'] = array();
1277 foreach($aPolyPoints as $aPoint)
1279 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1282 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1286 if (!isset($aResult['aBoundingBox']))
1289 $fDiameter = 0.0001;
1291 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1292 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1294 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1296 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1297 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1299 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1301 $fRadius = $fDiameter / 2;
1303 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1304 $fStepSize = (2*pi())/$iSteps;
1305 $aPolyPoints = array();
1306 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1308 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1310 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1311 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1312 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1313 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1315 // Output data suitable for display (points and a bounding box)
1318 $aResult['aPolyPoints'] = array();
1319 foreach($aPolyPoints as $aPoint)
1321 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1324 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1327 // Is there an icon set for this type of result?
1328 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1329 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1331 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1334 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1335 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1337 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1340 if ($bShowAddressDetails)
1342 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1343 //var_dump($aResult['address']);
1347 // Adjust importance for the number of exact string matches in the result
1348 $aResult['importance'] = max(0.001,$aResult['importance']);
1350 $sAddress = $aResult['langaddress'];
1351 foreach($aRecheckWords as $i => $sWord)
1353 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1355 $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
1357 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1359 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1360 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1362 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1364 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1365 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1367 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1371 $aResult['importance'] = 1000000000000000;
1374 $aResult['name'] = $aResult['langaddress'];
1375 $aResult['foundorder'] = $iResNum;
1376 $aSearchResults[$iResNum] = $aResult;
1378 uasort($aSearchResults, 'byImportance');
1380 //var_dump($aSearchResults);exit;
1382 $aOSMIDDone = array();
1383 $aClassTypeNameDone = array();
1384 $aToFilter = $aSearchResults;
1385 $aSearchResults = array();
1388 foreach($aToFilter as $iResNum => $aResult)
1390 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1391 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1394 $fLat = $aResult['lat'];
1395 $fLon = $aResult['lon'];
1396 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1399 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1400 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1402 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1403 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1404 $aSearchResults[] = $aResult;
1407 // Absolute limit on number of results
1408 if (sizeof($aSearchResults) >= $iLimit) break;
1411 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1413 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1415 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1420 logEnd($oDB, $hLog, sizeof($aToFilter));
1422 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1423 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1424 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1425 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1426 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1427 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1430 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1432 $sMoreURL .= '&q='.urlencode($sQuery);
1434 if (CONST_Debug) exit;
1436 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');