<?php
//------------------------------------------------
// NOAA-reports.php
// Original Author:  Ken True  webmaster@saratoga-weather.org
// 
// Heavily modified, primarily for CUmulus, but will also work for WeatherLink and VWS
// bodged by beteljuice - V3.2 Apr. 2012
//                                   bugfix for malformed html showing in Chrome browsers
//  V3.3 Aug 2013 - bug fix for nav menu with VWS
//
// May be used as a 'stand-alone' page, OR as an 'include' in another (php) page. 
//
// If using SaratogaWX AJAX / multilingual / php templates
// your first point of call should ALWAYS be http://saratoga-weather.org/wxtemplates/updates.php
//
// Permission is given to freely use and/or modify this script for
// private, non-commercial usage.
// No warranty is expressed or implied .. use at your own risk.
//

$Naming = 'WL';              // set to 'WL' or 'VWS' or 'CU' maybe overidden by posting ?type=
                             // or if an include call, $wxtype='CU'; before the include call

// $ourTZ = 'PST8PDT';			// set your timezone, 'old' style - see 'others' on link below
$ourTZ = 'Europe/Madrid';		// set your timezone - see: http://php.net/manual/en/timezones.php

// Note: Check line(s) 70 onward if your reports (web) directory is different to expected.
// Note:  WeatherLink conventions:
//    NOAAMO.TXT, NOAAYR.TXT  for current month and current year
//    NOAAPRMO.TXT, NOAAPRYR.TXT for last month, last year
//    NOAAyyyy.TXT for year 'yyyy' summary
//    NOAAyyyy-mm.TXT for month 'mm' in year 'yyyy' summary
//    NOAA-reports - directory containing the reports
//
// VWS naming format
//    noaamo.txt,noaayr.txt  for current month and current year
//    yyyy.txt  for year 'yyyy' summary
//    yyyy_mm.txt for month 'mm', year 'yyyy' summary.
//    noaa - directory containing the reports
//
// Note:  Cumulus (CU) conventions:
//
//    NOAAYRyyyy.txt for year 'yyyy' summary
//    NOAAMOmmyy.txt for month 'mm' in year (20)'yy' summary
//    NO (current) Year or Month summaries
//    NOAA-reports - directory containing the reports



$IncludeMode = true; // default behaviour, false means html headers / footers are produced
                      // maybe overridden by $doInclude=true; before eg. include 'NOAA-reports-test.php';
                      // or even posting .php?inc=y 

$use_css = true; // when $IncludeMode = false , will add a stylesheet call to the html generated
                 // if you are using as an 'include' then you will have to load noaarep.css in your <head>

$use_nav = true; // true = build a 'menu' based on contents of 'reports' directory
                 // false = NO 'menu', DIY with post .php?yr=yyyy&mo=mm (no input = current or latest month report.

$classic_nav = false; // false = show ALL available nav options at once
                      // false = show selected year together with a 'drop-down' style nav.
                      // if Javascript DISabled, classic style will be displayed ;-)


$months = array( "01"=>"Jan", "02"=>"Feb", "03"=>"Mar",
		 "04"=>"Apr", "05"=>"May", "06"=>"Jun",
		 "07"=>"Jul", "08"=>"Aug", "09"=>"Sep",
		 "10"=>"Oct", "11"=>"Nov", "12"=>"Dec"
	   );

// *** Change below if your reports directory is different to the 'type' default ******************

if ($Naming == 'WL') {
  $NOAAdir = './'; // point to your NOAA file sub-directry
  $ThisYearFile = "./NOAAYR.TXT"; // point to your current NOAA yearly file
  $ThisMonthFile= "./NOAAMO.TXT"; // point to your current NOAA monthly file
  $LastYearFile = "./NOAAPRYR.TXT"; // point to your prior NOAA yearly file
  $LastMonthFile= "./NOAAPRMO.TXT"; // point to your prior NOAA monthly file
}
if ($Naming == 'VWS') {
  $NOAAdir = './noaa';      // point to your NOAA file sub-directry
  $ThisYearFile = "$NOAAdir/noaayr.txt"; // point to your current NOAA yearly file
  $ThisMonthFile= "$NOAAdir/noaamo.txt"; // point to your current NOAA monthly file
}
if ($Naming == 'CU') {
  $NOAAdir = '../CumulusMX/NOAA';      // point to your NOAA file sub-directry
//  NO current NOAA month or yearly files
}



// END user variables, you only need to look below if you wish to change wording / language 

// safely display NOAA style text report files
// Original Author:  Ken True - webmaster@saratoga-weather.org


// look for 'posted' or 'include' variables 
$yr = 	isset($_REQUEST['yr']) ? $_REQUEST['yr'] : '';
$mo =   isset($_REQUEST['mo']) ? $_REQUEST['mo'] : ''; 
if (isset($_REQUEST['type'])) { $Naming = $_REQUEST['type']; } 
if (isset($wxtype)) { $Naming = $wxtype; } // new - beteljuice

// facility to show the code in a browser
if ( isset($_REQUEST['sce']) and strtolower($_REQUEST['sce']) == 'view' ) {
   //--self downloader --
   $filenameReal = __FILE__;
   $download_size = filesize($filenameReal);
   header('Pragma: public');
   header('Cache-Control: private');
   header('Cache-Control: no-cache, must-revalidate');
   header("Content-type: text/plain");
   header("Accept-Ranges: bytes");
   header("Content-Length: $download_size");
   header('Connection: close');
   
   readfile($filenameReal);
   exit;
}
// END show code

if (isset($_REQUEST['inc']) and strtolower($_REQUEST['inc']) == 'n') {
  $IncludeMode = true;
}
if (isset($doInclude)) {
  $IncludeMode = $doInclude;
}

if (! $IncludeMode ) { // 'stand-alone' - create html headers
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Refresh" content="300" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>NOAA style reports</title>
<link href="noaarep.css" rel="stylesheet" type="text/css" >

</head>
<body>
  <center><h1 id="pageName"></h1></center>
<?php 
}


// check to see if default ccs file exists - if not, create it before building the page 
//if (!file_exists('noaarep.css')) { createcss();}


$PHP_SELF = $_SERVER['PHP_SELF'];
putenv("TZ=$ourTZ");
$now = getdate();
// print "<!-- now \n" . print_r($now,true) . " -->\n";
$now_month = sprintf("%02d",$now['mon']);
$now_year = $now['year'];
$prior_month = $now['mon'] - 1;
$prior_year = $now['year'];
$last_year = $prior_year -1;
if ($prior_month < 1) {$prior_month = 12; $prior_year--;}
$prior_month = sprintf("%02d",$prior_month);
print "<!-- parms: yr='$yr' mo='$mo' -->\n";
print "<!-- now='$now_year'-'$now_month' prior='$prior_year'-'$prior_month' -->\n";

if ($Naming == 'WL') { // check for month/year rollover and update

	if(! file_exists("$NOAAdir/NOAA$prior_year-$prior_month.TXT") and file_exists($LastMonthFile) ) {
	   print "<!-- copying $LastMonthFile to $NOAAdir/NOAA$prior_year-$prior_month.TXT -->\n";
		if (copy($LastMonthFile,"$NOAAdir/NOAA$prior_year-$prior_month.TXT")) {
			print "<!-- copy successful -->\n";
		} else {
			print "<!-- unable to copy -->\n";
		}
	}

	if(! file_exists("$NOAAdir/NOAA$last_year.TXT") and file_exists($LastYearFile) ) {
		print "<!-- copying $LastYearFile to $NOAAdir/NOAA$last_year.TXT -->\n";
		if (copy($LastYearFile,"$NOAAdir/NOAA$last_year.TXT")) {
			print "<!-- copy successful -->\n";
		} else {
			print "<!-- unable to copy -->\n";
		}
	}
} // END WL rollover check


if ($handle = opendir("$NOAAdir")) { 
	while (false !== ($file = readdir($handle))) { 
		if ($file != "." && $file != "..") { 
            $files[] = $file; 
        } 
	} 
	closedir($handle); 

	sort($files); // ascending order
	$lastyear = '2017';

// set up the files and find the first and last year for reports
	$first_year = "2012";
 
	foreach ($files as $key => $file) {
		if ($Naming == 'WL') {
			$year = substr($file,4,4);
		} elseif ($Naming == 'VWS') {
			$year = substr($file,0,4);
		} elseif ($Naming == 'CU') {
			$year = substr($file,6,4);
			$year2 = substr($file, 8, 2);
		}

		if ((! preg_match("/^\d{4}$/",$year) ) && (!preg_match("/^\d(4)$/", $year2) && substr($file, 4, 2) == "MO" && $Naming == "CU") ) { continue;} //make sure year is numeric

		$filesfound["$file"] = 1;
		if (!$first_year && $Naming != "CU") { // everything EXCEPT Cumulus
			$first_year = $year; 
			$last_year = $year; // not used
		}
		
		if ($Naming == "CU") { // find the year value of ANY 'orphan' Cumulus year OR month reports
			if (substr($file, 4, 2) == "MO") { // found a month report
				$CU_year[] = "20" .$year2;
			} else { // found a year report
				$CU_year[] = $year;
			}
		} // END Cumulus 'orphan' check
	}  // END foreach

	if ($Naming == "CU") { // find first and last valid years
		$first_year = min($CU_year);
		$last_year = max($CU_year); // not used !
	}
 
	if (! $first_year) {
		echo "<h2>Sorry... no NOAA-style reports found.</h2>";
		echo "</body></html>";
		return;
	}

// Even if $use_nav = false, we use the (same) routine to check that the requested report exists.
// We simply don't output the 'menu'

// start building page 
	echo "<div class=\"noaa_rep_container\">
	<div class=\"noaarep.css\">\n";

//	if($use_nav) { echo "Select a Year or Month report<br />\n"; }

	If($now_year - $first_year == 0 || !$use_nav) {$classic_nav = true;} // Don't create drop-down and js
  
// now create the index links based on which files we have

//  for ($y = $first_year; $y <= $now_year; $y++) {
// above will do ascending sort by year in index 
// but we like the Index links sorted in descending year so
//   newest reports are at the top of the list
//

	$testfile = ""; // initialise to prevent twitch level error reporting   
	$cu_year = ""; // initialise 
	$cu_month = ""; // initialise
	$cu_month_year = ""; // initialise
 
 
 // initialise selected single line and full entry <div>s 
 // single line entry is effectively only used to control 'drop-box' 
	$single_line = "
 <div id=\"selected_nav\" style=\"display: none;\">
	<span class=\"noaa_rep_nav noaa_expand\" onClick=\"switch_nav();\">V/&#923;</span>";
 
	$full_nav = "<div id=\"all_nav\" style=\"display: inline;\">\n";
 
	$nav_build = array(); // initialise, will become eg. $nav_build[2011][found_year, months[] ]
 
	for ($y = $now_year; $y >= $first_year; $y--) { // populate $nav_build array()
		$yy = sprintf("%04d",$y);
		if ($Naming == 'WL')  {$t = "NOAA$yy.TXT"; }
		if ($Naming == 'VWS') {$t = "$yy.txt"; }
		if ($Naming == 'CU') {$t = "NOAAYR$yy.txt"; }

		if ($filesfound[$t] || ($yy == $now_year && $Naming != "CU")) { 
			$nav_build[$y]['active'] = true;
			if (!$cu_year) { $cu_year = $yy;}
		} else {
			$nav_build[$y]['active'] = false;
		}
	
// create month select for each year
		for ($m = 1; $m <= 12; $m++) {
			$mm = sprintf("%02d",$m);
			if ($Naming == 'WL')  {$testfile = "NOAA$yy-$mm.TXT";}
			if ($Naming == 'VWS') {$testfile = "$yy" . "_" . "$mm.txt"; }
			if ($Naming == 'CU') {$testfile = "NOAAMO$mm" .substr($yy, 2,2). ".txt"; }
	 
			if (array_key_exists($testfile, $filesfound)) {
				$nav_build[$y]['months'][$m] = "<a href=\"$PHP_SELF?yr=$yy&amp;mo=$mm\" class=\"noaa_rep_nav HIGHLIGHT\">" .$months[$mm]. "</a>"; // trailing space removed - beteljuice
				if (!$cu_month) { // first valid month in latest valid year
					$cu_month = $mm; 
					$cu_month_year = $yy; 
				} else { // update last valid month in latest valid year
					if ($cu_month_year == $yy) { $cu_month = $mm; }
				}
	  
			} else {
				if ($yy == $now_year && $mm == $now_month && $Naming != "CU") {
					$nav_build[$y]['months'][$m] = "<a href=\"$PHP_SELF\" class=\"noaa_rep_nav HIGHLIGHT\">" . $months[$mm] ."</a> ";
				} else {
					$nav_build[$y]['months'][$m] = "<span class=\"noaa_rep_nav HIGHLIGHT\">" . $months[$mm] ."</span>";
				}
			}
			if ($m < 12) {
				$nav_build[$y]['months'][$m] .= " ";
			} else {
				$nav_build[$y]['months'][$m] .= "\n";
			}

		} // END month step through

	} // END year step through
 
 
 
// Now PREPARE the reports

	if ($Naming == "CU" && !$yr && !$mo) { // show default latest Cumulus report
		if ($cu_month_year >= $cu_year) { // month report newer than year report
			$yr = $cu_month_year;
			$mo = $cu_month;
		}else { // year report is newer than month report
			$yr = $cu_yr;
			$mo = "";
		}
	}

	if (! $yr && ! $mo && $Naming != "CU") {  // special for 'current month', except Cumulus
		$advisory = "<br /><b>Report for $now_year $now_month</b>\n";
		$rpt = implode("",file("$ThisMonthFile"));
	}

	if ($yr == $now_year && !$mo && $Naming != "CU") { // special for current year, except Cumulus
		$advisory = "<br /><b>Report for $now_year</b>\n";
		$rpt = implode("",file("$ThisYearFile"));
	} else { // otherwise, process the requested year or year/month

		if ($yr) {
			$noaa_picked_yr = $yr;
			$noaa_picked_mon = $mo;
			if ($mo) { // month given
				if ($Naming == 'WL')  {$testfile = "NOAA$yr-$mo.TXT";}
				if ($Naming == 'VWS') {$testfile = "$yr" . "_" . "$mo.txt";}
				if ($Naming == 'CU') {$testfile = "NOAAMO$mo" .substr($yr, 2,2). ".txt";}
			} else { // no month given
				if ($Naming == 'WL')  {$testfile = "NOAA$yr.TXT";}
				if ($Naming == 'VWS') {$testfile = "$yr.txt";}
				if ($Naming == 'CU') {$testfile = "NOAAYR$yr.txt";}
			} // END no month given

			if (array_key_exists($testfile, $filesfound)) {
				$advisory = "<br /><b>Report for $yr " .($mo ? $months[$mo] : ''). "</b>\n";
				$rpt = implode("",file("$NOAAdir/$testfile"));

			} else {
// Nowt found need classic (full availability) menu
				$classic_nav = true;
				$advisory = "<br /><b>Sorry, no report for " .$yr. " " .($mo ? ($mo >= 1 && $mo <= 12 ? $months[$mo] : "month " .$mo) : ""). "</b><br /><br />\n"; // can only happen if 'posted'
			}
		}
	}
 
 
// o/p nav
	if($use_nav) {
// **** bug fix 17th Aug 2013 **********
		if(! $yr && ! $mo && $Naming != "CU"){ // special for 'current month', except Cumulus
			$yr = $now_year ; // special for 'current month', except Cumulus
			$noaa_picked_yr = $now_year ;
			$noaa_picked_mon = $now_month;
		}

		for ($y = $now_year; $y >= $first_year; $y--) { // BUILD menu from $nav_build array()
 
			$yy = sprintf("%04d",$y);
   
// create year select
// set up 'classic' nav
			$updown = "";
			$yr_id = "";
			if(!$classic_nav) { // needs updown and year id on latest year, reserved space and no id thereafter 
				if($y == $now_year) {
					$updown = "<span id=\"nav_updown\" class=\"noaa_rep_nav noaa_expand_alt\" onClick=\"switch_nav();\">V/&#923;</span>";
					$yr_id = "id=\"nav_year_one\" ";
				} else {
					$updown = "<span class=\"noaa_rep_nav noaa_expand_alt\" onClick=\"switch_nav();\">V/&#923;</span>";
					$yr_id = "";
				}
			} // end if $classic_nav

			if($nav_build[$y]['active']) { // create 'link' for year

				if($yr == $y) { // create single-line 'drop-down' and highlight for classic
					$single_line .= "<a href=\"$PHP_SELF?yr=$yy\" class=\"noaa_rep_nav_alt " .(!$noaa_picked_mon ? "noaa_selected" : ""). "\">$yy</a> &gt; " .DoMonths($yy). "</div>\n";
					$full_nav2 .= $updown."<span class=\"noaa_selected_line\"><a ".$yr_id."href=\"$PHP_SELF?yr=$yy\" class=\"noaa_rep_nav " .(!$noaa_picked_mon ? "noaa_selected" : ""). "\">$yy</a> &gt; " .DoMonths($yy). "</span>";
				} else {
					$full_nav2 .= $updown."<a ".$yr_id."href=\"$PHP_SELF?yr=$yy\" class=\"noaa_rep_nav\">$yy</a> &gt; " .DoMonths($yy);
				}
			} else { // year is not an active link
				if($yr == $y) { // create single-line 'drop-down' and highlight for classic
					$single_line .= "<span class=\"noaa_rep_nav_alt\">$yy</span> &gt; " .DoMonths($yy). "</div>\n";
					$full_nav2 .= $updown."<span class=\"noaa_selected_line\"><span class=\"noaa_rep_nav " .(!$noaa_picked_mon ? "noaa_selected" : ""). "\">$yy</span> &gt; " .DoMonths($yy). "</span>";
					} else {
					$full_nav2 .= $updown."<span class=\"noaa_rep_nav\">$yy</span> &gt; " .DoMonths($yy);
				}
			}

		if($yr != $first_year) { $full_nav2 .= "<br />\n";} 

		} // END year step through

	} // end if $use_nav
 	$full_nav2 .= "</div> <!-- END all_nav -->\n";
 } // END if directory 
 
 echo $full_nav. $full_nav2;
 if(!$classic_nav ) {echo $single_line. "<!-- END selected_nav -->\n";}
 echo "</div> <!-- END noaa_rep_nav -->\n";
 
 echo $advisory;
 
 if($rpt){
	echo "<pre>\n";
	echo utf8_encode(preg_replace('|<|Uis','&lt;',$rpt));
	echo "</pre>\n";
}
echo "</div> <!-- END noaa_rep_container -->\n";


//  JavaScript construct for 'drop-down' style nav - beteljuice



if(!$classic_nav && $use_nav) { // classic nav is ALWAYS in the page (if $use_nav = true), JavaScript is to turn it OFF and work drop-down
?>
<script type="text/javascript">
/* use php to write this bit if classic menu NOT chosen */
// Reverse logic - fiddle to show menu correctly if JavaScript IS enabled !
// default is full / classic nav - so switch to single line
switch_nav();
document.getElementById("nav_updown").style.visibility = "visible"; // show 'full' menu collapse button
// END fiddle 

function switch_nav() {
	nav_el = document.getElementById('selected_nav');
	nav_el2 = document.getElementById('all_nav');

	if(nav_el.style.display == "none") {
		nav_el2.style.display = "none";
		nav_el.style.display = "inline";
	} else {
		nav_el.style.display = "none";
		nav_el2.style.display = "inline";
	}
} // END function switch_nav()

</script>
<?php
}


// echo "------- debugging -----\n";
// print_r($filesfound);
if (! $IncludeMode ) { // closing html
?>
</body>
</html>
<?php
}
// END main routine


function DoMonths($year) {
	global $full_nav2, $nav_build, $noaa_picked_yr, $noaa_picked_mon ;

	$noaa_patch = "";
	for ( $m = 1; $m <= 12; $m++){
		$mm = sprintf("%02d",$m);
		$noaa_replace = ($year == $noaa_picked_yr && $mm == $noaa_picked_mon ? "noaa_selected" : "");
		$noaa_patch .= str_replace("HIGHLIGHT", $noaa_replace, $nav_build[$year]['months'][$m]);
	}
	return $noaa_patch;
} // END DoMonths()


// Make a css file (no error checks !)
function createcss() {
	$op = "
/* default stylesheet for NOAA Style Reports ala beteljuice */
/* overall container */
.noaa_rep_container {
    font-family: courier new, courier, monospace;
    width: 635px;
    margin: 0 auto;
}

.noaa_rep_container a, .noaa_rep_container a:link, .noaa_rep_container a:visited, .noaa_rep_container a:hover, .noaa_rep_container a:active {
    color: #000000; 
    text-decoration: none;
    background-color: white;
}


/* container for nav buttons */
.noaa_rep_nav_container {
    font-family: lucida console, courier new, courier, monospace;
    font-size: 8pt;
    font-weight: bold;
    text-align: left;
    line-height: 2.2;
    text-align: center;
}


/* the nav buttons themselves */
.noaa_rep_nav {
    text-align: left;
    border: 1px solid #000000;
    border-radius: 10px 10px 10px 10px; /* NOT IE8 and below */
    padding: 2px 5px 2px 5px;
    color: #808080;	
    background-color: #DDDDDD;
    font-weight: bold;
}

/* modified year button when used with expand - collapse (same as above but 'flattened' left-hand side) */
.noaa_rep_nav_alt {
    text-align: left;
    border: 1px solid #000000;
    border-radius: 0px 10px 10px 0px; /* NOT IE8 and below */
    padding: 2px 5px 2px 5px;
    color: #808080;
    background-color: #DDDDDD;
    font-weight: bold;
}

/* expand - collapse button (single line) */
.noaa_expand {
    color: #000000;
    border-radius: 10px 0px 0px 10px; /* NOT IE8 and below */
    background-color: #DDC81D; /* dirty yellow */
    cursor: pointer;
}

/* expand - collapse button (full menu) */
.noaa_expand_alt {
    color: #808080;
    border-radius: 10px 10px 10px 10px; /* NOT IE8 and below */
    background-color: #DDC81D; /* dirty yellow */
    cursor: pointer;
    visibility: hidden; 
}

/* nav button hover color - NOT IE8 and below */
a.noaa_rep_nav:hover {
    box-shadow: 0 0 7px #007EBF;
}

/* nav button hover color - NOT IE8 and below */
a.noaa_rep_nav_alt:hover {
    box-shadow: 0 0 7px #007EBF;
}

/* highlight selected year or month button - NOT IE8 and below */
.noaa_selected {
    box-shadow: 0 0 7px #FF0000; /* red */
}

/* highlight selected year line */
.noaa_selected_line {
    background-color: #FFFF00; /* yellow */
}


/* container for the actual report file */
.noaa_rep_container pre {
    color: #000000;
    font-family: monospace;
    font-size: 9pt;
    font-weight: normal;
    text-align: left;
    border: 1px solid #000000;
    border-radius: 10px 10px 10px 10px; /* NOT IE8 and below */
    padding: 20px 0px 25px 20px;
    background-color: #f9f8EB;
}

";
    $handle = fopen('noaarep.css', 'w');
    fwrite($handle, $op);
    fclose($handle);
} // END function createcss()


?>
