'National Map',
'PAC' => 'Pacific',
'WUJ' => 'Aldergrove (near Vancouver)',
'XPG' => 'Prince George',
'XSS' => 'Silver Star Mountain (near Vernon)',
'XSI' => 'Victoria',
'WRN' => 'Prairies',
'CASBE' => 'Bethune (near Regina)',
'WHK' => 'Carvel (near Edmonton)',
'CASFW' => 'Foxwarren (near Brandon)',
'WHN' => 'Jimmy Lake (near Cold Lake)',
'CASRA' => 'Radisson (near Saskatoon)',
'CASSU' => 'Schuler (near Medicine Hat)',
'CASSR' => 'Spirit River (near Grande Prairie)',
'CASSM' => 'Strathmore (near Calgary)',
'CASWL' => 'Woodlands (near Winnipeg)',
'ONT' => 'Ontario',
'WBI' => 'Britt (near Sudbury)',
'CASDR' => 'Dryden',
'CASET' => 'Exeter (near London)',
'XFT' => 'Franktown (near Ottawa)',
'WKR' => 'King City (near Toronto)',
'CASMR' => 'Montreal River (near Sault Ste Marie)',
'CASRF' => 'Smooth Rock Falls (near Timmins)',
'XNI' => 'Superior West (near Thunder Bay)',
'QUE' => 'Quebec',
'WMB' => 'Lac Castor (near Saguenay)',
'CASLA' => 'Landrienne (near Rouyn-Noranda)',
'CASBV' => 'Blainville (near Montréal)',
'CASVD' => 'Val d\'Irène (near Mont Joli)',
'CASSF' => 'Villeroy (near Trois-Rivières)',
'ERN' => 'Atlantic',
'CASCM' => 'Chipman (near Fredericton)',
'XGO' => 'Halifax',
'CASHR' => 'Holyrood (near St. John\'s)',
'XME' => 'Marble Mountain',
'CASMB' => 'Marion Bridge (near Sydney)',
); // end of list of allowed sites
// error_reporting(E_ALL & ~E_NOTICE); // uncomment to turn on full error reporting
print "
This script is deprecated \n";
print "Since 30-Mar-2021, Environment Canada no longer produces the radar images used";
print " by this script, so this script no longer works.
\n";
return;
$hasUrlFopenSet = ini_get('allow_url_fopen');
if(!$hasUrlFopenSet) {
print "Warning: PHP does not have 'allow_url_fopen = on;' -- image fetch by ec-radar.php is not possible. \n";
print "To fix, add the statement:
allow_url_fopen = on;\n\n to your php.ini file to enable ec-radar.php operation.\n";
return;
}
$t = pathinfo(__FILE__); // get our program name for the HTML comments
$Program = $t['basename'];
$Status = "\n";
$BasePath = $t['dirname'];
//$Status .= "\n";
$printIt = true;
if(isset($_REQUEST['inc']) && strtolower($_REQUEST['inc']) == 'y' or
(isset($doInclude) and $doInclude)) {$doInclude = true;}
if(isset($doPrint)) { $printIt = $doPrint; }
if(! isset($doInclude)) {$doInclude = false; }
if(isset($_REQUEST['site'])) { $siteID = strtoupper($_REQUEST['site']); }
$siteID = preg_replace('|[^A-Z]+|s','',$siteID); // Make sure only alpha in siteID
if(!isset($allowedSites[$siteID])) {
print "Sorry... site id '$siteID' is not a valid EC radar site name.
\n";
return;
}
if (isset($_REQUEST['cache']) && (strtolower($_REQUEST['cache']) == 'no') ) {
$forceRefresh = true;
} else {
$forceRefresh = false;
}
if (isset($doAutoPlay)) {
$autoPlay = $doAutoPlay;
} elseif (isset($_REQUEST['play']) && (strtolower($_REQUEST['play']) == 'no') ) {
$autoPlay = false;
} else {
$autoPlay = true;
}
if (isset($_REQUEST['imgonly']) && (strtolower($_REQUEST['imgonly']) == 'y')) {
$imageOnly = true; // just return the latest thumbnail image after processing
$printIt = false; // and don't spoil the image with any other stuff
} else {
$imageOnly = false;
}
if (isset($_REQUEST['lang'])) {
$Lang = strtolower($_REQUEST['lang']);
}
if (isset($doLang)) {$Lang = $doLang;};
if (! isset($Lang)) {$Lang = $defaultLang;};
if ($Lang == 'fr') {
$LMode = 'f';
$ECNAME = "Environnement Canada";
$ECHEAD = 'Radar météo';
$ECNO = 'N/O - Non opérationnel';
$LNoJS = 'Pour voir l\'animation, il faut que JavaScript soit en fonction.';
$LPlay = 'Animer - Pause';
$LPrev = 'Image précédente';
$LNext = 'Prochaine image';
} else {
$Lang = 'en';
$LMode = 'e';
$ECNAME = "Environment Canada";
$ECHEAD = 'Weather Radar';
$ECNO = 'N/O - Non-operational';
$LNoJS = 'Please enable JavaScript to view the animation.';
$LPlay = 'Play - Stop';
$LPrev = 'Previous';
$LNext = 'Next';
}
$cacheName = preg_replace('|.txt$|',"-$Lang.txt",$cacheName);
//
if (isset($_SERVER['DOCUMENT_ROOT'])) {
$ROOTDIR = $_SERVER['DOCUMENT_ROOT'];
} else {
$ROOTDIR = '.';
}
$TradarDir = $radarDir;
if (substr($TradarDir,0,1) == '.') {$TradarDir = substr($TradarDir,1); } //prune off '.' from './' if need be
if (substr($TradarDir,0,1) <> '/') {$TradarDir = '/' . $TradarDir; } // put on leading slash if missing
$cacheDir = $BasePath . $TradarDir;
$imageDir = $radarDir;
$Status .= "\n\n";
date_default_timezone_set( @date_default_timezone_get());
$Status .= "\n";
// Default radar image sizes from EC
$new_width = 580;
$new_height = 480;
$thumb_width = 290;
$thumb_height = 240;
if (! preg_match('|^[WXC]|',$siteID) || ($siteID == 'WRN') ) {
// the regional summary sizes
$new_width = 573;
$new_height = 300;
$thumb_width = 290;
$thumb_height = 150;
}
if ($siteID == 'NAT') {
// the national summary size
$new_width = 600;
$new_height = 522;
$thumb_width = 300;
$thumb_height = 261;
}
if (!$linkToPage) {
$linkToPage = $_SERVER['PHP_SELF'];
}
if (isset($_REQUEST['linkto'])) {
$linkToPage = $_REQUEST['linkto'];
}
// all settings and overrides now loaded ... begin processing
$Status .= "\n";
$cacheName = preg_replace('|.txt$|',"-$siteID.txt",$cacheName);
$RawImgURL = "https://weather.gc.ca/data/radar/detailed/temp_image/$siteID/%s";
$RawOvlURL = "https://weather.gc.ca";
$compositeSites = array(
'NAT' => 'nat',
'PAC' => 'pyr',
'WRN' => 'pnr',
'ONT' => 'ont',
'QUE' => 'que',
'ERN' => 'ern',
);
if(isset($compositeSites[$siteID])) {
$RawImgURL = "https://weather.gc.ca/data/radar/temp_image/COMPOSITE_$siteID/%s";
}
$ECURL = 'https://weather.gc.ca/radar/index_' . $LMode . '.html?id=' . $siteID;
if($Lang == 'fr') {
$RawImgURL = preg_replace('|weather|i','meteo',$RawImgURL);
$ECURL = preg_replace('|weather|i','meteo',$ECURL);
$Status .= "\n";
}
$RealCacheName = $cacheDir . $cacheName;
$tpath = realpath($RealCacheName);
if ($tpath) {
$Status .= "\n";
$RealCacheName = $tpath;
}
$reloadImages = false; // assume we don't have to reload unless a newer image set is around
if(file_exists($RealCacheName)) {
$lastCacheTime = filemtime($RealCacheName);
} else {
$lastCacheTime = time();
$forceRefresh = true;
}
$lastCacheTimeHM = gmdate("Y-m-d H:i:s",$lastCacheTime) . " UTC";
$NOWgmtHM = gmdate("Y-m-d H:i:s",time()) . " UTC";
$diffSecs = time() - $lastCacheTime;
$Status .= "\n";
if(isset($_GET['force']) | isset($_GET['cache'])) {$refetchSeconds = 0;}
if($diffSecs > $refetchSeconds) {$forceRefresh = true;}
$Status .= "\n";
// refresh cached copy of page if needed
// fetch/cache code by Tom at carterlake.org
if (! $forceRefresh) {
$Status .= "\n";
$site = implode('', file($RealCacheName));
$forceRefresh = true;
} else {
$Status .= "\n";
$site = ECR_fetchUrlWithoutHanging($ECURL,false);
$fp = fopen($RealCacheName, "w");
if (strlen($site) and $fp) {
$write = fputs($fp, $site);
fclose($fp);
$Status .= "\n";
$reloadImages = true;
} else {
$Status .= "\n";
$Status .= "\n";
$Status .= "\n";
}
}
if(strlen($site) < 100) {
print "Sorry. Incomplete file received from Environment Canada website.
\n";
print $Status;
return;
}
preg_match('|charset="{0,1}([^"\n]+)"{0,1}\n|i',$site,$matches);
if (isset($matches[1])) {
$charsetInput = strtoupper($matches[1]);
} else {
$charsetInput = 'UTF-8';
}
$doIconv = ($charsetInput == $charsetOutput)?false:true; // only do iconv() if sets are different
$Status .= "\n";
// find the site name
//
preg_match_all('|(.*) |',$site,$matches);
// $Status .= "\n";
$siteTitle = $matches[1][0];
if($doIconv and $siteTitle) {
$siteTitle = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$siteTitle);
}
preg_match_all('|(.*) |',$site,$matches);
$siteHeading = $matches[1][0];
if($doIconv and $siteHeading) {
$siteHeading = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$siteHeading);
}
if(preg_match_all('|\s+]+>(.*)
\s+ >|',$site,$matches) ) {
$siteDescr = $matches[1][0];
} else {
$siteDescr = '';
}
if($doIconv and $siteDescr) {
$siteDescr = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$siteDescr);
}
// used to be "timezone":{"id":"CDT","title":"Central Daylight Time","offset":"-5"}
// now is "timezone":{"id":"Canada\/Eastern","title":"","offset":""}
preg_match_all('|"timezone"\:\{"id":"([^"]+)","title":"([^"]*)","offset":"([^"]*)"\}|Uis',$site,$matches);
// $Status .= "\n";
if (!$matches[3][0]) { // oops.. no offset. use text to calculate proper values.
// look for latest image text description
// PRECIPET - Rain 2015-11-29, 07:40 PM EST
preg_match('|([^<]+)
|is',$site,$matches);
// $Status .= "\n";
$tStr = substr($matches[1],strpos($matches[1],'2'));
$Status .= "\n";
// tStr = '2015-11-30, 18:50 UTC' (national)
// tStr = '2015-11-30, 02:00 PM EST' (English)
// tStr = '2015-11-30, 14:00 HNE' (French)
$tStr = str_replace(',','',$tStr);
$TZ = substr($tStr,strlen($tStr)-3); // peel off the text TZ abbreviation
$TZName = $TZ;
$tStr = substr($tStr,0,strlen($tStr)-4);
//$Status .= "\n";
//find UTC time from latest image url
preg_match('! \n";
$tStrUTC = $matches[1];
// 2015_11_30_21_30
//$Status .= "\n";
$t = explode('_',$tStrUTC);
$tStrUTC = $t[0].'-'.$t[1].'-'.$t[2].' '.$t[3].':'.$t[4];
$Status .= "\n";
$TZOffsetSecs = strtotime($tStr.' GMT')-strtotime($tStrUTC.' GMT');
$TZHrs = $TZOffsetSecs / 3600;
} else {
$TZ = $matches[1][0];
$TZName = $matches[2][0];
$TZHrs = $matches[3][0];
$TZOffsetSecs = $TZHrs * 3600;
}
$Status .= "\n";
//this is for NAT/regional maps only
if(preg_match_all('||Uis',$site,$matches)) {
// $Status .= "\n";
$MapDef = implode('',$matches[0]); // extract image map text from page
$MapDef = preg_replace('|/radar/index_[ef]\.html\?id=|is',"$linkToPage?lang=$Lang&site=",$MapDef);
// $MapDef = preg_replace('| ]+)>|is'," ",$MapDef);
$MapDef = preg_replace('| xmlns:html="http://www.w3.org/Profiles/XHTML-transitional"|','',$MapDef);
$MapDef = preg_replace('|]+)>|','',$MapDef);
// $MapDef = preg_replace('|name="([^"]+)"|i','name="$1" id="$1"',$MapDef);
preg_match_all('|\s+name="(.*)"\s*|Ui',$MapDef,$matches2);
// $Status .= "\n";
$MapName = $matches2[1][0];
if($doIconv) {
$MapName = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$MapName);
$MapDef = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$MapDef);
}
// $Status .= "\n";
// $Status .= "\n";
} else {
$MapDef = '';
$MapName = '';
}
// V1.12 -- special find of current image as background in animation
$mostRecentImg = '';
if(preg_match('|src="/data/radar/temp_image//\S+/(\S+).GIF"|is',$site,$tmatch)) {
$mostRecentImg = $tmatch[1];
$Status .= "\n";
}
// find all the radar images available
// in two passes.. get the base and the short image list.
$start = strpos($site, '');
$finish = strpos($site, '',$start);
$length = $finish-$start;
$shortList = substr($site, $start, $length);
// $Status .= "\n";
// $Status .= "\n";
// now pick up the short list
// $start = strpos($site, 'image-list-title">');
// $finish = strpos($site, '
',$start);
// $length = $finish-$start;
// $shortList .= substr($site, $start, $length);
// $Status .= "\n";
$number_found = preg_match_all("!(display|base)\=\'(.*?)\'!", $shortList, $matches);
// $Status .= "\n";
//
// New EC Radar HTML has logic to handle if JavaSript is disabled
// which causes the above regular expression to generate two `base'
// .GIF's.
//
// The work-around is to determine whether cell 1 is a `base', if so, we
// delete cell 0. To plan for possible future logic, we keep
// deleting `base' entries until there's only one remaining.
//
if ($number_found > 2 && $matches[1][1] == "base") {
for ($i = 1; $i <= $number_found; $i++) {
// Remove the first set of `base' values.
unset($matches[0][0]);
unset($matches[1][0]);
unset($matches[2][0]);
// Do we end our for-loop?
if ($i < $number_found && $matches[1][1] != "base") {
break;
}
}
// Reset index numbers so data sorts properly by time.
$matches[0] = array_values($matches[0]);
$matches[1] = array_values($matches[1]);
$matches[2] = array_values($matches[2]);
}
// $Status .= "\n";
// V1.12 -- add in most recent image to array if available
if($mostRecentImg <> '') {
$imglist[] = $mostRecentImg; // add to first entry
foreach ($matches[2] as $i => $ourImg) {
$imglist[] = $ourImg;
}
} else {
$imglist = $matches[2];
}
$Status .= "\n";
// $imglistText = array();
$total_time = 0;
$newestRadarCacheFile = '';
$lastRadarGMTText ='';
$newestRadarImgHTML = '';
$numImages = 0;
$NOWgmt = time();
$NOWdate = gmdate("D, d M Y H:i:s", $NOWgmt);
$imglistText[0] = '';
$lastRadarGMT = 0;
if($reloadImages) {
$default_opts = array(
'http'=>array(
'method'=>"GET",
'protocol_version' => 1.1,
'header'=>"Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (ec-radar.php - saratoga-weather.org)\r\n" .
"Accept: text/html,text/plain\r\n"
),
'ssl'=>array(
'method'=>"GET",
'protocol_version' => 1.1,
'verify_peer' => false,
'header'=>"Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (ec-radar.php - saratoga-weather.org)\r\n" .
"Accept: text/html,text/plain\r\n"
)
);
$default = stream_context_set_default($default_opts);
// Now generate overlays in the same order as used by EC
/*
/cacheable/images/radar/layers/rivers/wkr_rivers.gif
/cacheable/images/radar/layers/roads/WKR_roads.gif
/cacheable/images/radar/layers/road_labels/wkr_labs.gif
/cacheable/images/radar/layers/radar_circle/radar_circle.gif
/cacheable/images/radar/layers/additional_cities/wkr_towns.gif
/cacheable/images/radar/layers/default_cities/wkr_towns.gif
towns overlay for summary files.
nat: /cacheable/images/radar/layers/composite_cities/nat_composite.gif
pac: /cacheable/images/radar/layers/composite_cities/pyr_composite.gif
wrn: /cacheable/images/radar/layers/composite_cities/pnr_composite.gif
ont: /cacheable/images/radar/layers/composite_cities/ont_composite.gif
que: /cacheable/images/radar/layers/composite_cities/que_composite.gif
atl: /cacheable/images/radar/layers/composite_cities/atl_composite.gif
*/
$townOverlays = array(
'NAT' => 'nat',
'PAC' => 'pyr',
'WRN' => 'pnr',
'ONT' => 'ont',
'QUE' => 'que',
'ERN' => 'ern',
);
$imgType = $show14Color ? '14-Color':'8-Color';
$u8c = $show14Color ? '':'_detailed';
// V2.00 -- generate the overlay directly using GD functions
$Status .= "\n";
$Status .= "\n";
$Status .= "\n";
$overlayIMG = imagecreatetruecolor($new_width,$new_height);
$overlayBGColor = imagecolorallocatealpha($overlayIMG,255,255,255,127); // transparency=full
imagecolortransparent($overlayIMG,$overlayBGColor); // what the EC uses...
imagefill($overlayIMG,0,0,$overlayBGColor); // make image background transparent
// Enable blend mode and save full alpha channel
imagealphablending($overlayIMG, true);
imagesavealpha($overlayIMG, true);
$didOverlay = '';
if(isset($townOverlays[$siteID]) and $showRegionalTowns) { // summary site.. use only one overlay
$tIMGraw = file_get_contents($RawOvlURL.
'/cacheable/images/radar/layers'.$u8c.'/composite_cities/' .
$townOverlays[$siteID] . '_composite.gif');
$tIMG = imagecreatefromstring($tIMGraw);
if($tIMG) {
displayTrans($tIMG,'rivers');
imagecopy($overlayIMG,$tIMG,0,0,0,0,$new_width,$new_height);
imagedestroy($tIMG);
$didOverlay .= 'Composite cities, ';
} else {
print "\n";
}
}
if(!isset($townOverlays[$siteID])) { // not a summary site
if ($showRivers) {
$tIMGraw = file_get_contents($RawOvlURL.
'/cacheable/images/radar/layers'.$u8c.'/rivers/' . strtolower($siteID) . '_rivers.gif');
$tIMG = imagecreatefromstring($tIMGraw);
if($tIMG) {
displayTrans($tIMG,'rivers');
imagecopy($overlayIMG,$tIMG,0,0,0,0,$new_width,$new_height);
imagedestroy($tIMG);
$didOverlay .= 'Rivers, ';
} else {
print "\n";
}
}
if ($showRoads) {
$tIMGraw = file_get_contents($RawOvlURL.
'/cacheable/images/radar/layers'.$u8c.'/roads/'. $siteID . '_roads.gif');
$tIMG = imagecreatefromstring($tIMGraw);
if($tIMG) {
displayTrans($tIMG,'roads');
imagecopy($overlayIMG,$tIMG,0,0,0,0,$new_width,$new_height);
imagedestroy($tIMG);
$didOverlay .= 'Roads, ';
} else {
print "\n";
}
}
if ($showRoadLabels) {
$tIMGraw = file_get_contents($RawOvlURL.
'/cacheable/images/radar/layers'.$u8c.'/road_labels/' . strtolower($siteID) . '_labs.gif');
$tIMG = imagecreatefromstring($tIMGraw);
if($tIMG) {
displayTrans($tIMG,'road labels');
imagecopy($overlayIMG,$tIMG,0,0,0,0,$new_width,$new_height);
imagedestroy($tIMG);
$didOverlay .= 'Road Labels, ';
} else {
print "\n";
}
}
if ($showRadarRings) {
$tIMGraw = file_get_contents($RawOvlURL.
'/cacheable/images/radar/layers'.$u8c.'/radar_circle/radar_circle.gif');
$tIMG = imagecreatefromstring($tIMGraw);
if($tIMG) {
displayTrans($tIMG,'radar circles');
imagecopy($overlayIMG,$tIMG,0,0,0,0,$new_width,$new_height);
imagedestroy($tIMG);
$didOverlay .= 'Radar Circles, ';
} else {
print "\n";
}
}
if ($showAdditTowns) {
$tIMGraw = file_get_contents($RawOvlURL.
'/cacheable/images/radar/layers'.$u8c.'/additional_cities/' . strtolower($siteID) .'_towns.gif');
$tIMG = imagecreatefromstring($tIMGraw);
if($tIMG) {
displayTrans($tIMG,'addit. cities');
imagecopy($overlayIMG,$tIMG,0,0,0,0,$new_width,$new_height);
imagedestroy($tIMG);
$didOverlay .= 'Additional Cities, ';
} else {
print "\n";
}
}
if ($showTowns) {
$tIMGraw = file_get_contents($RawOvlURL.
'/cacheable/images/radar/layers'.$u8c.'/default_cities/' . strtolower($siteID) .'_towns.gif');
$tIMG = imagecreatefromstring($tIMGraw);
if($tIMG) {
displayTrans($tIMG,'cities');
imagecopy($overlayIMG,$tIMG,0,0,0,0,$new_width,$new_height);
imagedestroy($tIMG);
$didOverlay .= 'Default Cities, ';
} else {
print "\n";
}
}
} // end of overlay creation for regular radar sites
if(strlen($didOverlay) > 1) {
$didOverlay = substr($didOverlay,0,strlen($didOverlay)-2);
$Status .= "\n";
}
imagepng($overlayIMG,$cacheDir.'overlay-'.$siteID.'.png'); // save it
}
//print "now process \n";
//print "\n" . print_r($imglist,true) . " \n";
// process image file list from EC radar page
foreach ($imglist as $i => $ourImg ) {
$ourImg .= '.GIF'; // have to add back the .GIF since the preg_match_all removes it.
$radarCacheFile = "radar-$siteID-$i.png";
$RealRadarCacheFile = $cacheDir . $radarCacheFile;
$tpath = realpath($RealRadarCacheFile);
if ($tpath <> '') {
$RealRadarCacheFile = $tpath;
}
$imgURL = sprintf($RawImgURL,$ourImg);
// $Status .= "\n";
// $Status .= "\n";
preg_match('|_(\d+)_(\d+)_(\d+)_(\d+)_(\d+).GIF|',$ourImg,$matches);
// $Status .= "\n";
$RadarGMT = gmmktime($matches[4],$matches[5],0,$matches[2],$matches[3],$matches[1]);
$RadarGMTText = gmdate("D, d M Y H:i:s", $RadarGMT);
// $Status .= "\n";
$imglistText[$i] = gmdate("Y-m-d H:i ",$RadarGMT+$TZOffsetSecs) . $TZ;
if ($i == 0) { // newest image processing
$lastRadarGMT = $RadarGMT;
$lastRadarGMTText = $RadarGMTText;
$diff = $NOWgmt - $lastRadarGMT;
$Status .= "\n";
} // end img=0 processing
if ($reloadImages) { // do the reload
$didIt = false;
$time_start = ECR_fetch_microtime();
if($show14Color) {
$imgURL = preg_replace('|/detailed/|','/',$imgURL); // get old detailed images only
} else {
$imgURL = preg_replace('|/radar/temp_image/|i','/radar/detailed/temp_image/',$imgURL);
}
$Status .= "\n";
$didIt = download_file($imgURL,$cacheDir,$radarCacheFile,$overlayIMG,$new_width,$new_height);
$time_stop = ECR_fetch_microtime();
$total_time += ($time_stop - $time_start);
$time_fetch = sprintf("%01.3f",round($time_stop - $time_start,3));
if ($didIt) {
$Status .= "\n";
} else {
$Status .= "\n";
}
} // end if reloadImages
$numImages++;
} // end foreach imglist
if ($reloadImages) { // make thumbnail too for latest image
$imgname = "radar-$siteID-0.png"; // get latest image name
$thumbname = preg_replace('|\.png|','-sm.png',$imgname);
$time_start = ECR_fetch_microtime();
$image = imagecreatefrompng ($cacheDir . $imgname);; // fetch our radar
if (! $image ) { // oops... no existing image, create a dummy one
$image = imagecreate ($new_width, $new_height); /* Create a blank image */
$bgc = imagecolorallocate ($image, 128, 128, 128);
imagefilledrectangle ($image, 0, 0, $new_width, $new_height, $bgc);
}
$MaxX = imagesx($image);
$MaxY = imagesy($image);
$image_p = imagecreatetruecolor($thumb_width, $thumb_height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $MaxX, $MaxY);
if (time() > ($lastRadarGMT + $noRadarMinutes*60 + $refetchSeconds + 15)) {
// stale radar if > 25 minutes + refetchTime + 15 seconds old
$text_color = imagecolorallocate ($image_p, 192,51,51);
$bgcolor = imagecolorallocate ($image, 128, 128, 128);
imagefilledrectangle($image_p, 5, 95, 230, 140,$bgcolor);
imagestring ($image_p, 5, 15, 100, "$ECNO", $text_color);
imagestring ($image_p, 5, 15, 120, $imglistText[0], $text_color);
}
imagepng($image_p, $cacheDir . $thumbname);
imagedestroy($image);
imagedestroy($image_p);
$time_stop = ECR_fetch_microtime();
$total_time += ($time_stop - $time_start);
$time_fetch = sprintf("%01.3f",round($time_stop - $time_start,3));
$Status .= "\n";
$Status .= "\n";
}
if(isset($overlayIMG)) {imagedestroy($overlayIMG);}
if ($imageOnly) {
$ourImg = $cacheDir . "radar-$siteID-0-sm.png";
if (file_exists($ourImg)) {
$ourImgSize = filesize($ourImg);
$ourImgGMT = filectime($ourImg);
header("Content-type: image/png"); // now send to browser
header("Content-length: " . $ourImgSize);
header("Last-modified: " . gmdate("D, d M Y H:i:s", $ourImgGMT) . ' GMT');
header("Expires: " . gmdate("D, d M Y H:i:s", $ourImgGMT+$refetchSeconds) . ' GMT');
readfile($ourImg);
}
exit;
}
// print it out:
if ($printIt && ! $doInclude) {
//------------------------------------------------
header("Cache-Control: no-cache,no-store, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$NOWdate = gmdate("D, d M Y H:i:s", time());
header("Expires: $NOWdate GMT");
header("Last-Modified: $NOWdate GMT");
?>
\n";
if ($printIt) {
$ECURL = preg_replace('|&|Ui','&',$ECURL); // make link XHTML compatible
// print "\n";
// print $newestRadarImgHTML;
print "\n";
gen_animation($numImages, $siteID, $radarDir,$aniSec);
// print $imgHTML;
print "
$siteHeading - $ECNAME
\n
\n";
}
if ($printIt && ! $doInclude) {?>
\n";
$ch = curl_init(); // initialize a cURL session
curl_setopt($ch, CURLOPT_URL, $theURL); // connect to provided URL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // don't verify peer certificate
curl_setopt($ch, CURLOPT_USERAGENT,
'Mozilla/5.0 (ec-radar.php - saratoga-weather.org)');
curl_setopt($ch,CURLOPT_HTTPHEADER, // request LD-JSON format
array (
"Accept: text/html,text/plain"
));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $numberOfSeconds); // connection timeout
curl_setopt($ch, CURLOPT_TIMEOUT, $numberOfSeconds); // data timeout
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the data transfer
curl_setopt($ch, CURLOPT_NOBODY, false); // set nobody
curl_setopt($ch, CURLOPT_HEADER, true); // include header information
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow Location: redirect
// curl_setopt($ch, CURLOPT_MAXREDIRS, 1); // but only one time
if (isset($needCookie[$domain])) {
curl_setopt($ch, $needCookie[$domain]); // set the cookie for this request
curl_setopt($ch, CURLOPT_COOKIESESSION, true); // and ignore prior cookies
$Status .= "\n";
}
$data = curl_exec($ch); // execute session
if(curl_error($ch) <> '') { // IF there is an error
$Status .= "\n"; // display error notice
}
$cinfo = curl_getinfo($ch); // get info on curl exec.
/*
curl info sample
Array
(
[url] => http://saratoga-weather.net/clientraw.txt
[content_type] => text/plain
[http_code] => 200
[header_size] => 266
[request_size] => 141
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.125
[namelookup_time] => 0.016
[connect_time] => 0.063
[pretransfer_time] => 0.063
[size_upload] => 0
[size_download] => 758
[speed_download] => 6064
[speed_upload] => 0
[download_content_length] => 758
[upload_content_length] => -1
[starttransfer_time] => 0.125
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => 74.208.149.102
[certinfo] => Array
(
)
[primary_port] => 80
[local_ip] => 192.168.1.104
[local_port] => 54156
)
*/
$Status .= "\n";
//$Status .= "\n";
curl_close($ch); // close the cURL session
//$Status .= "\n";
$i = strpos($data,"\r\n\r\n");
$headers = substr($data,0,$i);
$content = substr($data,$i+4);
if($cinfo['http_code'] <> '200') {
$Status .= "\n";
}
return $data; // return headers+contents
} else {
// print "\n";
$STRopts = array(
'http'=>array(
'method'=>"GET",
'protocol_version' => 1.1,
'header'=>"Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (ec-radar.php - saratoga-weather.org)\r\n" .
"Accept: text/html,text/plain\r\n"
),
'ssl'=>array(
'method'=>"GET",
'protocol_version' => 1.1,
'verify_peer' => false,
'header'=>"Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (ec-radar.php - saratoga-weather.org)\r\n" .
"Accept: text/html,text/plain\r\n"
)
);
$STRcontext = stream_context_create($STRopts);
$T_start = ECR_fetch_microtime();
$xml = file_get_contents($url,false,$STRcontext);
$T_close = ECR_fetch_microtime();
$headerarray = get_headers($url,0);
$theaders = join("\r\n",$headerarray);
$xml = $theaders . "\r\n\r\n" . $xml;
$ms_total = sprintf("%01.3f",round($T_close - $T_start,3));
$Status .= "\n";
$Status .= "<-- get_headers returns\n".$theaders."\n -->\n";
// print " file() stats: total=$ms_total secs.\n";
$overall_end = time();
$overall_elapsed = $overall_end - $overall_start;
$Status .= "\n";
// print "fetch function elapsed= $overall_elapsed secs.\n";
return($xml);
}
} // end ECR_fetchUrlWithoutHanging
// ------------------------------------------------------------------
function ECR_fetch_microtime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
// ---------------------------------------------------------------------------
function setTransparency($new_image,$image_source)
{
$transparencyIndex = imagecolortransparent($image_source);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
if ($transparencyIndex >= 0) {
$transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
imagefill($new_image, 0, 0, $transparencyIndex);
imagecolortransparent($new_image, $transparencyIndex);
}
// ---------------------------------------------------------------------------
function displayTrans($image_source,$for) {
global $Status;
$tI = imagecolortransparent($image_source);
$cI = imagecolorsforindex($image_source,$tI);
if ($tI >= 0) {
$Status .= "\n";
}
}
// ---------------------------------------------------------------------------
function download_file($file_source,$file_dir, $file_target,$overlay,$width,$height) {
global $Status;
// load the source gif and do the overlay, then save the resulting file V2.00
$tIMG = imagecreatetruecolor($width,$height);
// Enable blend mode and save full alpha channel
imagealphablending($tIMG, true);
imagesavealpha($tIMG, true);
$STRopts = array(
'http'=>array(
'method'=>"GET",
'protocol_version' => 1.1,
'header'=>"Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (ec-radar.php - saratoga-weather.org)\r\n" .
"Accept: text/html,text/plain\r\n"
),
'ssl'=>array(
'method'=>"GET",
'protocol_version' => 1.1,
'verify_peer' => false,
'header'=>"Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (ec-radar.php - saratoga-weather.org)\r\n" .
"Accept: text/html,text/plain\r\n"
)
);
$STRcontext = stream_context_create($STRopts);
$T_start = ECR_fetch_microtime();
$rawIMGstring = file_get_contents($file_source,false,$STRcontext);
$T_close = ECR_fetch_microtime();
$headerarray = get_headers($file_source,0);
$ms_total = sprintf("%01.3f",round($T_close - $T_start,3));
$Status .= "\n";
$sceIMG = imagecreatefromstring($rawIMGstring);
if(!$sceIMG) {
$Status .= "\n";
$Status .= "\n";
imagedestroy($tIMG);
return false;
}
imagecopy($tIMG,$sceIMG,0,0,0,0,$width,$height);
imagecopy($tIMG,$overlay,0,0,0,0,$width,$height);
if(!imagepng($tIMG,$file_dir . $file_target)) {
$Status .= "\n";
imagedestroy($tIMG);
return false;
}
imagedestroy($tIMG);
return true;
}
// ------------------------------------------------------------------
function gen_animation ( $numImages, $siteID, $radarDir,$aniSec) {
// generate JavaScript and control buttons for rotating the images
global $new_width, $new_height, $siteTitle, $imglistText, $LPlay, $LPrev, $LNext, $LNoJS,
$siteHeading, $siteDescr, $ECNO, $MapDef,$MapName, $TZ, $TZOffsecSecs, $autoPlay;
if ($numImages < 1) {
print "Sorry, no current radar images for site $siteID are available.
\n";
return;
}
if ($numImages > 1) {
// generate the animation for 2 or more images
?>
" alt="" width="" height="" id="_Ath_Slide" title="" '') {echo " usemap=\"#" . $MapName . "\" "; }?>/>
'') { print " $ECNO"; }?>
'') { print "$siteDescr
\n"; }?>
" alt="" width=" " height="" title="" />