<div class="ajaxDashboard">
<?php
# Used with get-metar-conditions-inc.php to format and display multiple METAR reports
# Author: Ken True webmaster@saratoga-weather.org
#
# NOTE: it is recommended that you NOT change this file .. it is subject to updates to fix display issues
#       do your customizations in the wxmetar.php page to specify settings.
#
# Version 1.00 - 17-Nov-2011 - initial release
# Version 1.01 - 18-Nov-2011 - chg $Lang to $mtrLang to address language selection stickyness
# Version 1.02 - 19-Nov-2011 - fixed a malformed PHP code marker, remove 'at' in Wind string
# Version 1.03 - 22-Nov-2011 - added 2-up/3-up display format based on narrow/wide aspect for screen
# Version 1.04 - 24-Nov-2011 - added translation capability for VISIBILITY 'greater than' phrase
# Version 1.05 - 27-Nov-2011 - added 'Distance to station' for metar lists generated by find-metar.php
# Version 1.06 - 29-Nov-2011 - added cloud-detail display and improved conditions translations
# Version 1.07 - 27-Dec-2022 - fixes for PHP 8.2
# Version 1.08 - 08-Mar-2024 - fix for 'space comma' display issue
#
$IMDversion = 'include-metar-display.php - Version 1.08 - 08-Mar-2024';

if (isset($_REQUEST['sce']) && ( strtolower($_REQUEST['sce']) == 'view' or
    strtolower($_REQUEST['sce']) == 'show') ) {
   //--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;
}
// overrides from Settings.php if available
global $Debug, $SITE;
if (isset($SITE['lang'])) 	{$mtrLang = $SITE['lang'];}
if (isset($SITE['uomTemp'])) 	{$uomTemp = $SITE['uomTemp'];}
if (isset($SITE['uomBaro'])) 	{$uomBaro = $SITE['uomBaro'];}
if (isset($SITE['uomWind'])) 	{$uomWind = $SITE['uomWind'];}
if (isset($SITE['uomRain'])) 	{$uomRain = $SITE['uomRain'];}
if (isset($SITE['fcsticonstype'])) 	{$condIconType = $SITE['fcsticonstype'];}
print "<!-- $IMDversion -->\n";

if(file_exists("get-metar-conditions-inc.php")) {
  include_once("get-metar-conditions-inc.php");
  print "<!-- $GMCVersion -->\n";
} else {
  print "<p>Unable to find/load get-metar-conditions-inc.php.</p>\n";
  return;
}



$UOM = "$uomTemp,$uomWind,$uomBaro,$uomRain";
//$UOM = "&deg;C,km/h,hPa,mm";
//
$toDisplay = array(  // keys in $mtr array to display (if they exist) and in this order
'TEMP' => 'Temperature',
'WIND CHILL' => 'Wind Chill',
'HEAT INDEX' => 'Heat Index',
'WIND' => 'Wind',
'DEWPT' => 'Dew Point',
'HUMIDITY' => 'Humidity',
'BAROMETER' => 'Barometer',
'CONDITIONS' => 'Summary',
'CLOUDS' => 'Clouds',
'VISIBILITY' => 'Visibility',
'CLOUD-DETAILS' => 'Cloud details',
);

// Get translation values if available
foreach ($toDisplay as $key => $val) {
	$toDisplay[$key] = langtransstr($val);
}

if ($mtrLang <> 'en') { // try changing windrose graphics test for the Calm graphic
  $tfile = preg_replace('|^'.$wrName.'|',$wrName.$mtrLang.'-',$wrCalm);
  print "<!-- checking for '" . $condIconDir.$tfile . "' -->\n";
  if (file_exists($condIconDir.$tfile)) {
	$wrCalm = $tfile;  // change the PHP dashboard settings too
	$wrName = $wrName . $mtrLang . '-';
	print "<!-- new wrName='$wrName', wrCalm='$wrCalm' -->\n";
  } 
}
$maxCols = 2;
if(isset($SITE['CSSscreen']) and preg_match('|wide|',$SITE['CSSscreen'])) {
	$maxCols = 3;
}
$thisCol = 0;
 
echo "<table width=\"99%\">\n";
echo "<tr>\n";
 
foreach ($MetarList as $idx => $Mrec) {
  
  list($mtrICAO,$mtrName,$mtrDistanceM,$mtrDistanceK,$direction) = explode('|',$Mrec.'|||||');
  if($mtrICAO == '') { continue;}
  $Debug = '';
  list($condwords,$iconnum,$condicon,$condicondesc,$mtr,$metarGMT) =
        mtr_conditions($mtrICAO, $time, $sunrise, $sunset, true,$UOM);

  $metarUpdated = date($SITE['timeFormat'],$metarGMT);
  if(isset($_REQUEST['debug']) and strtolower($_REQUEST['debug']) == 'y') {
	  print $Debug;
	  print "<!-- mtr_conditions returns\n";
	  print "condwords='$condwords', iconnum=$iconnum, condicon='$condicon',\n";
	  print "condicondesc='$condicondesc'\n";
	  print "metarUpdated = $metarGMT ". gmdate("Y-m-d h:i",$metarGMT) . " GMT ($metarUpdated)\n"; 
	  // print "mtr = ".print_r($mtr,true)."\n";
	  print " -->\n";
  }
   
// now $mtr array contains the decoded values
foreach ($toDisplay as $key => $legend) {
   	
   if (!isset($mtr[$key]) or strlen($mtr[$key]) < 1) { continue; }
   if($key == 'CONDITIONS' or $key == 'CLOUDS') {
	   $mtr[$key] = fixupCondition($mtr[$key]);  // handle translations if needed
   }
   if($key == 'CLOUD-DETAILS') {
	   $cd = explode("\t",$mtr[$key]);
	   foreach ($cd as $k => $cdrec) {
		  if(preg_match('/^(.*) (\d+.*)$/',$cdrec,$matches)) {
		   
		   $cd[$k] = fixupCondition($matches[1]) . " ".$matches[2];
		   print "<!-- cloud detail fixupCondition in='$cdrec' out='".$cd[$k]."' -->\n";
		  }
	   }
	   
	   $mtr[$key] = join("<br/>\n",$cd);
   }
   if($key == 'WIND') {
	   $t = explode(" ",$mtr[$key]);
	   $dirlabel = $t[0];
	   if(isset($t[0])) $t[0] = langtransstr($t[0]); // translate wind direction
	   if(isset($t[1])) $t[1] = ''; // remove 'at'
	   $mtr[$key] = join(' ',$t);
   }
}
// time to format the output for display
if($thisCol >= $maxCols) {
	print "</tr>\n";
	print "<tr><td colspan=\"$maxCols\">&nbsp;</td></tr>\n";
	print "<tr>\n";
	$thisCol = 0;
}

?><td valign="top" align="center">
<table width="320" cellpadding="2" cellspacing="1" style="border:solid; border-color: #CCCCCC;">
  <tr>
    <td colspan="2" class="datahead" style="text-align: center;border: none">
    <?php echo "$mtrICAO - $mtrName"; 
	 if($mtrDistanceM <> '' and $mtrDistanceK <> '') {
		 echo "<br/>".langtransstr('Distance from station').": ";
		 if($direction <> '') {
			 echo " ".langtransstr($direction). " ";
		 }
		 if(isset($SITE['uomDistance']) and preg_match('|mi|i',$SITE['uomDistance'])) {
			 echo "{$mtrDistanceM}mi, ";
		 }
		 echo "{$mtrDistanceK}km";
		  
	 } ?>
    </td>
  </tr>
  <tr>
    <td colspan="2" class="data1" style="text-align: center;border: none">
    <?php echo langtransstr('Updated') . ": $metarUpdated"; ?>
    <?php
	 if(time() - $metarGMT > $maxAge) {
		print "<br/><span style=\"color: red\"><b>".langtransstr('NOT Current')."</b></span>\n";
	 }
	?>	 
    </td>
  </tr>
  <tr>
    <td align="center" valign="top" class="data1" style="text-align: center;border: none">
          <img src="<?php echo $condIconDir . newIcon($iconnum) ?>"  
            alt="<?php $t1 = fixupCondition($condwords);
                  echo $t1; ?>" 
            title="<?php echo $t1; ?>" height="58" width="55" /><br/>
            <b><?php echo $t1; ?></b>
    </td>
    <td align="center" valign="top" class="data1" style="text-align: center;border: none">
      <?php if(isset($mtr['WIND'])) { ?>
				  <img src="<?php echo $condIconDir; ?>spacer.gif" width="1" 
				    height="<?php echo $wrHeight; ?>" alt=" " align="left"/>
				  <?php $wr = $condIconDir . $wrName . $dirlabel . $wrType; // normal wind rose
				        $wr = preg_replace('|varies|','calm',$wr);
				        $wrtext = langtransstr('Wind from') ." " . langtransstr($dirlabel);
						if (preg_match('!(calm|varies)!i',$mtr['WIND']) and
						     ($wrCalm <> '') ) { // use calm instead
						  $wr = $condIconDir . $wrCalm;
						}
						$t = preg_match('|calm|i',$mtr['WIND'])?langtransstr('Calm'):$mtr['WIND'];
						$t = preg_replace('|varies|i',langtransstr('varies'),$t);
						$t = preg_replace('|gusting to|',langtransstr('Gust').":",$t);
            $t = preg_replace('|\((.*)\)|U'," <span class=\"bidi\">, $1</span>",$t); 
						if(isset($_REQUEST['debug']) ) {
						 print "<!-- t='$t' -->\n";
						}
						if(isset($_SESSION['lang']) and $_SESSION['lang'] == 'he') { 
						 // do nothing 
						} else {
							$t = preg_replace('|\s+<|U','<',$t);
						}
						if(isset($_REQUEST['debug']) ) {
						 print "<!-- t='$t' -->\n";
						}

						// fix parenthesis issue in RTL language
						
				  ?>
				    <img src="<?php echo $wr; ?>" 
					height="<?php echo $wrHeight; ?>" width="<?php echo $wrWidth; ?>" 
					title="<?php echo $wrtext; ?>" 
					alt="<?php echo $wrtext; ?>"  style="text-align:center" /><br/>
                    <span class="bidi"><?php echo $toDisplay['WIND']; ?>:</span>
                    <span class="bidi"><?php echo $t; ?></span>
       <?php } else { // isset($mtr['WIND']
	      echo "&nbsp;\n";
	   } // end isset($mtr['WIND')
	   ?>
     </td>
  </tr>
 <?php
/*
STATION : LEIB
WIND : NNW at 7 mph (11 km/h)
VISIBILITY : 16 miles
CONDITIONS :
CLOUDS : Few Clouds
TEMP : 63F (17C)
DEWPT : 57F (14C)
HUMIDITY : 83%
BAROMETER : 1019 hPa (30.09 inHg)
*/
foreach ($toDisplay as $key => $legend) {
   	
   if (!isset($mtr[$key]) or strlen($mtr[$key]) < 1) { continue; }
   if ($key == 'WIND') {continue;}
   $t = $mtr[$key];
   if ($key == 'VISIBILITY') {
     $t = preg_replace('|greater than|i',langtransstr('greater than'),$t);
   }
	 if(isset($_REQUEST['debug']) ) {
		 print "<!-- t='$t' -->\n";
	 }
   $t = preg_replace('|\((.*)\)|U',"<span class=\"bidi\">, $1</span>",$t); // fix parenthesis issue in RTL language
	 if(isset($_SESSION['lang']) and $_SESSION['lang'] !== 'he') {$t = preg_replace('|\s+<|U','<',$t); }
	 if(isset($_REQUEST['debug']) ) {
		 print "<!-- t='$t' -->\n";
	 }
   print "  <tr>\n";
   print "    <td class=\"data1\" align=\"right\">{$legend}:</td>\n";
   print "    <td class=\"data1\" align=\"left\"><b><span class=\"bidi\">".$t."</span></b></td>\n";
   print "  </tr>\n";
}

   print "  <tr>\n";
   print "     <td class=\"data1\" colspan=\"2\"><small>".$mtr['RAW-METAR']."</small></td>\n"; 
   print "  </tr>\n";
   if(isset($_REQUEST['debug']) and strtolower($_REQUEST['debug']) == 'y') {
     print "  <tr>\n";
     print "     <td class=\"data1\" colspan=\"2\"><small>".$mtr['METAR']."</small></td>\n"; 
     print "  </tr>\n";
   }
?>

</table>
</td>
<?php
  $thisCol++;
} // end of metar loop
?></tr>
</table>

</div> <!-- end ajaxDashboard class format -->

<?php
// supporting functions
//=========================================================================
// pick the NOAA style condition icon based on iconnumber 
function newIcon($numb) {
  global $condIconDir,$condIconType;
  
  $iconList = array(
	"skc.jpg",          //  0 imagesunny.visible
	"nskc.jpg",         //  1 imageclearnight.visible
	"bkn.jpg",          //  2 imagecloudy.visible
	"sct.jpg",          //  3 imagecloudy2.visible
	"nbkn.jpg",         //  4 imagecloudynight.visible
	"sct.jpg",          //  5 imagedry.visible
	"fg.jpg",           //  6 imagefog.visible
	"hazy.jpg",         //  7 imagehaze.visible
	"ra.jpg",           //  8 imageheavyrain.visible
	"few.jpg",          //  9 imagemainlyfine.visible
	"mist.jpg",         // 10 imagemist.visible
	"nfg.jpg",          // 11 imagenightfog.visible
	"nra.jpg",          // 12 imagenightheavyrain.visible
	"novc.jpg",         // 13 imagenightovercast.visible
	"nra.jpg",          // 14 imagenightrain.visible
	"nshra.jpg",        // 15 imagenightshowers.visible
	"nsn.jpg",          // 16 imagenightsnow.visible
	"ntsra.jpg",        // 17 imagenightthunder.visible
	"ovc.jpg",          // 18 imageovercast.visible
	"sct.jpg",          // 19 imagepartlycloudy.visible
	"ra.jpg",           // 20 imagerain.visible
	"ra.jpg",           // 21 imagerain2.visible
	"shra.jpg",         // 22 imageshowers2.visible
	"ip.jpg",           // 23 imagesleet.visible
	"ip.jpg",           // 24 imagesleetshowers.visible
	"sn.jpg",           // 25 imagesnow.visible
	"sn.jpg",           // 26 imagesnowmelt.visible
	"sn.jpg",           // 27 imagesnowshowers2.visible
	"skc.jpg",          // 28 imagesunny.visible
	"scttsra.jpg",      // 29 imagethundershowers.visible
	"hi_tsra.jpg",      // 30 imagethundershowers2.visible
	"tsra.jpg",         // 31 imagethunderstorms.visible
	"nsvrtsra.jpg",     // 32 imagetornado.visible
	"wind.jpg",         // 33 imagewindy.visible
	"ra1.jpg",          // 34 stopped rainning
	"windyrain.jpg"     // 35 windy/rain 
	);	
	$tempicon = $iconList[$numb];
	if($condIconType <> '.jpg') {
	  $tempicon = preg_replace('|\.jpg|',$condIconType,$tempicon);
	}
	return($tempicon);
  }
	
// Function to process %Currentsolarcondition% string and 
// remove duplicate stuff, then fix capitalization, and translate from English if needed
//  
  function fixupCondition( $inCond ) {
    global $DebugMode;
	
    $Cond = str_replace('_',' ',trim($inCond));
	$Cond = strtolower($Cond);
	$dt = '';
	
	$vals = array();
	if(strpos($Cond,'/') !==false) {
		$dt .= "<!-- vals split on slash -->\n";
		$vals = explode("/",$Cond);
	}
	if(strpos($Cond,',') !==false) {
		$dt .= "<!-- vals split on comma -->\n";
		$vals = explode(",",$Cond);
	}
	$ocnt = count($vals);
	if($ocnt < 1) { return(langtransstr(trim($inCond))); }
	foreach ($vals as $k => $v) { 
	  if($DebugMode) { $dt .= "<!-- v='$v' -->\n"; }
	  $v = ucfirst(strtolower(trim($v)));
	  $vals[$k] = langtransstr($v); 
	  if($DebugMode) { $dt .= "<!-- vals[$k]='".$vals[$k]."' -->\n"; }
	}
	
	if($vals[0] == '') {$junk = array_shift($vals);}
	if(isset($vals[2]) and $vals[0] == $vals[2]) {$junk = array_pop($vals);}
	reset($vals);
	$t = join(', ',$vals);
	
//	return($Cond . "' orig=$ocnt n=" . count($vals) ." t='$t'");
    if($DebugMode) {
      $t = "<!-- fixupCondition in='$inCond' out='$t' ocnt='$ocnt' -->" . $dt . $t;
	}
    return($t);
  
  }
?>