<?php

	// svn version and software version Sync
	/* 	svn 			software
			65				9.32
			73				9.40
			78				9.42
			79				9.43
			80        9.44
	*/

	// Connection information
	$Version = "9.44"; // update svn commit <-> version # table above
	$website = "localhost:3306";
	$website = "127.0.0.1:3306";

	$userid  = "root";
	$pw      = "mysql";
	$project = "NO PROJECT OPEN";
  $DBName  = "NO DATABASE OPEN";
	$proDesc = "No description provided";
	$PathPHP = "C:\\\"Program Files (x86)\"\\Ampps\\php\\php.exe";

	// display switches
	$debug   = true;
	$debug   = false; // default false

	$DemoMode = true;
	$DemoMode = false; // default false

	$GeekMode = false;
	$GeekMode = true; // default true

	// Other switches
	$sub_o_desc = false;

	// output to other locations
	// Web folders will only work if user has made these on their local computer supplying correct user name and passwords
	$URLOutput   = true;  $OutputWebFolder = "\\\\mae-web.mecheng.strath.ac.uk/esru/Downloads/E-services/";
	$URLOutput2  = false; $OutputWebFolder2 = "\\\\webdrive.strath.ac.uk@SSL/DavWWWRoot/home/10/las05110/MyWebSpace/";
	$CloudOutput = false; $CloudLocation = "../../Outputs/_Cloud/My Files & Folders/EnTrak_Outputs/";

	$OutputsFolder = "../../Outputs";

	$oper_sys = "windows"; //init
	$user_agent     =   $_SERVER['HTTP_USER_AGENT'];
	$user_os        =   getOS();
	$user_browser   =   getBrowser();
	$uname = php_uname();
	if (stripos($user_os, "wind") === FALSE && stripos($uname, "wind") === FALSE) {
		$oper_sys = "linux";
  }else{
		$oper_sys = "windows";
	}
	//echo ("<h3>OS is $oper_sys</h3>");exit;
	// Manually override automatic OS detection
	//$oper_sys = "windows";
	//$oper_sys = "linux";

	$NonPrintingTitleRendering   = " style='text-align: left;  display: block; width: 100%; background-color: transparent;         border-color: transparent; cursor: default; font:default; height:2px' ";
	$SelectedRendering           = " style='text-align: left;  display: block; width: 100%; background-color:#338fff; color:white; border-color: transparent;                  font:default;' ";
	$NotSelectedRendering        = " style='text-align: left;  display: block; width: 100%; background-color: transparent;         border-color: transparent; cursor: default; font:default;' ";
	$SelectedRenderingRight      = " style='text-align: right; display: block; width: 100%; background-color:#338fff; color:white; border-color: transparent;                  font:default;' ";
	$NotSelectedRenderingRight   = " style='text-align: right; display: block; width: 100%; background-color: transparent;         border-color: transparent; cursor: default; font:default;' ";
	$StandardRendering           = " style='text-align: left;  display: block; width: 100%; background-color: transparent;         border-color: transparent; cursor: default; font:default; font:bold;' ";
	$StandardRenderingButton     = " style='text-align: left;  display: block; width: 100%;  cursor: default; font:default;' ";
	$StandardRenderingRight      = " style='text-align: right; display: block; width: 100%; background-color: transparent;         border-color: transparent; cursor: default; font:default; font:bold;' ";
	$StandardRenderingWhite      = " style='
								width: 100%;
								color:white;
								text-shadow:none;
								border:white;
								box-shadow:none;
								background-color: white;
								outline:none;
								border-color:white;
								' ";

	$con = mysql_connect($website,$userid,$pw,false,128);
	if (!$con) {
		die('Could not connect: ' . mysql_error());
	}
	mysql_query("SET foreign_key_checks = 0",$con);
		// Check if connection has been made to MySQL
		//echo "From OpenDB <br/>";
		//$result = mysql_query("SHOW DATABASES",$con);
		//while($row = mysql_fetch_array($result)){
		//	echo $row[0] . "<br/>";
		//}

	function WarnUser($Warning,$RedirectPage){
		echo "<html>";
		echo $Warning;
		echo "<a href='$RedirectPage'>";
		echo "<input type='submit' value='OK' />";
		echo "</a>";
		echo "</html>";
	}

	function startsWith($haystack, $needle) {
		// search backwards starting from haystack length characters from the end
		return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
	}

	function endsWith($haystack, $needle) {
		// search forward starting from end minus needle length characters
		return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
	}

	function strafter($string, $substring) {
		$pos = strpos($string, $substring);
		if ($pos === false)
		return $string;
		else
		return(substr($string, $pos+strlen($substring)));
	}

	function strbefore($string, $substring) {
		$pos = strpos($string, $substring);
		if ($pos === false)
		return $string;
		else
		return(substr($string, 0, $pos));
	}

// return time period in seconds associated with this frequency if period is month then number of seconds is ambiguous return number of seconds in previous month
// because when called from:
// 1) FetchDataCron the value returned from this function will be subtracted from $current_time to give $timestamp_to_read_data_from
// 2) ServiceCron the value returned from this function will be subtracted from $current_time to give $timestamp_to_start_service_from
	function GetTimePeriodFromFrequency($period,$time,$mnth,$year){
		$days = get_days_in_prev_mnth($mnth,$year);
		if($period == "MINUTE" ){
			return 60 * $time;
		}elseif($period == "HOURLY" ){
			return 60 * 60 * $time;
		}elseif($period == "DAILY"  ){
			return 60 * 60 * 24 * $time;
		}elseif($period == "WEEKLY" ){
			return 60 * 60 * 24 * 7 * $time;
		}elseif($period == "MONTHLY"){
			return 60 * 60 * 24 * $days * $time;
		}else{
			return -1;
		}
	}

	// dummy shell_execute command
	function shell_execute($cmd){
		return;
	}

	function refresh(){
	// Reload entire web page from frame
	echo "<body onload=\"parent.window.location.reload(true)\">";
	}

	//returns time in seconds from records listed in frequency table
	function GetTimePeriod($PD,$T){ // Period, times per period
		if($T > 0){
			if($PD == "Minute" || strcasecmp($PD,"MINUTE") == 0){
				return 60 / $T;
			}elseif($PD == "Hour" || strcasecmp($PD,"HOURLY") == 0){
				return 60*60 / $T;
			}elseif($PD == "Day" || strcasecmp($PD,"DAILY") == 0){
				return 24*60*60 / $T;
			}elseif($PD == "Week" || strcasecmp($PD,"WEEKLY") == 0){
				return 7*24*60*60 / $T;
			}elseif($PD == "Month" || strcasecmp($PD,"MONTHLY") == 0){
				// Get month from date (i.e. month now at run time)
				$mn = date('n');
				if($mn == 2){
					$yr = date("Y");
					if(is_leap_year($yr)){
						$days = 29;
					}else{
						$days = 28;
					}
				}elseif($mn == 1 || $mn == 3 || $mn == 5 || $mn == 7 || $mn == 8 || $mn == 10 || $mn == 12){
					$days = 31;
				}else{
					$days = 30;
				}

				// return number of seconds in the present month
				return $days * 24 *60 * 60;
			}elseif($PD == "Year"){
				return 365*24*60*60;
			}else{
				return -9;
			}
		}
	}

	function is_leap_year($year){
		return ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));
	}

// Delete directory
function delTree($dir){
	  if(!file_exists($dir))return;
    $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
        }
    return rmdir($dir);
}

// Get matched entities static and dynamic that are scoped on by a scope
function getMatchedEntities($attribute,$rule,$text,$con,$mode){

	// Get number of entities that match this attribute
	$MatchedSID = array();
	$MatchedDID = array();
	$UniqueMatchedSID = array();
	$UniqueMatchedDID = array();
	$MaxMatches = 0;
	$result = mysql_query("SELECT COUNT(source_id) FROM Source",$con);
	while($rowA = mysql_fetch_array($result))$MaxMatches = $rowA[0];

	$MaxStaticMatches = 0;
	$StaticMatches = 0;
	$result = mysql_query("SELECT COUNT(source_id) FROM Static",$con);
	while($rowA = mysql_fetch_array($result))$MaxStaticMatches = $rowA[0];
	if($MaxStaticMatches > 0){
		$result = mysql_query("	SELECT attribute,value,static_id FROM Static",$con);
		while($rowA = mysql_fetch_array($result)){
			$AttFromStatic = $rowA[0];
			$ValueFromStatic = $rowA[1];
			$SID = $rowA[2];
			if($attribute == $AttFromStatic){
				if($rule == "-"){ // get this scope without any checks
						$StaticMatches++;
						$MatchedSID[] = $SID;
						//echo("<td>1 Matched {$AttFromStatic} & {$ValueFromStatic} & SID = {$SID}</td>");
				}elseif($rule == "="){ // get this scope if Static.value equals Scope.text
					if($text == $ValueFromStatic){
						$StaticMatches++;
						$MatchedSID[] = $SID;
						//echo("<td>2 Matched {$AttFromStatic} & {$ValueFromStatic}</td>");
					}
				}elseif($rule == "Contains"){ // get this scope if Static.value contains Scope.text
					if(gettype(strpos($ValueFromStatic,$text)) == "integer"){
						$StaticMatches++;
						$MatchedSID[] = $SID;
						//echo("<td>3 Matched {$AttFromStatic} & {$ValueFromStatic} w/ {$text}</td>");
					}
				}
			}// More rules to be added here
		}
	}

	$MaxDynamicMatches = 0;
	$DynamicMatches = 0;
	$result = mysql_query("	SELECT COUNT(source_id) FROM Dynamic",$con);
	while($rowA = mysql_fetch_array($result))$MaxDynamicMatches = $rowA[0];
	if($MaxStaticMatches > 0){
		$result = mysql_query("	SELECT attribute,value,dynamic_id FROM Dynamic",$con);
		while($rowA = mysql_fetch_array($result)){
			$AttFromDynamic = $rowA[0];
			$ValueFromDynamic = $rowA[1];
			$DID = $rowA[2];
			if($attribute == $AttFromDynamic){
				if($rule == "-"){ // get this scope without any checks
						$DynamicMatches++;
						$MatchedDID[] = $DID;
				}elseif($rule == "="){ // get this scope if Static.value equals Scope.text
					if($text == $ValueFromDynamic){
						$DynamicMatches++;
						$MatchedDID[] = $DID;
					}
				}elseif($rule == "Contains"){ // get this scope if Static.value contains Scope.text
					if(gettype(strpos($ValueFromDynamic,$text)) == "integer"){
						$DynamicMatches++;
						$MatchedDID[] = $DID;
					}
				}
			}// More rules to be added here
		}
	}

	//echo("</tr><tr><td>");
	unset($UniqueMatchedSID);
	unset($UniqueMatchedDID);
	$UniqueMatchedSID = (array_unique($MatchedSID));
	$UniqueMatchedDID = (array_unique($MatchedDID));
	unset($MatchedFR_SID);
	unset($MatchedFR_DID);
	$MatchedFR_SID = array();
	$MatchedFR_DID = array();
	foreach($UniqueMatchedSID as $i) array_push($MatchedFR_SID,$i);
	foreach($UniqueMatchedDID as $i) array_push($MatchedFR_DID,$i);

	//foreach($UniqueMatchedSID as $child)echo $child . "<br/>";
	//echo count($UniqueMatchedSID) . "= count <br/>";
	//echo("</td>");
	if($attribute == "entity"){
		$BothMatches = $MaxMatches;
	}else{
		$BothMatches = $StaticMatches + $DynamicMatches; // if matching attributes
		$BothMatches = count($UniqueMatchedSID) + count($UniqueMatchedDID); // if matching entities
	}
	//echo ("returning {$Matches}");
	if($mode == "both"){
		return $BothMatches;
	}elseif($mode == "static"){
		return $StaticMatches;
	}elseif($mode == "dynamic"){
		return $DynamicMatches;
	}elseif($mode == "SID"){
		//return $MatchedSID;
		return $MatchedFR_SID;
	}elseif($mode == "DID"){
		//return $MatchedDID;
		return $MatchedFR_DID;
	}else{
		return "error called with wrong mode";
	}
}

// function to get earliest associated timestamp in dynamic data if output_id is known
// function returns seconds from epoch
// it can also return all the DID or SID associated with a service
function get_DID_TS($output_id,$con,$which){

	$resAA = mysql_query("SELECT scope_id FROM Scope WHERE output_id = {$output_id}",$con);
	$earliest_time = strtotime('now');
	$latest_time = strtotime('1970-01-01');
	while($rowAA = mysql_fetch_array($resAA)){
		$scope_id = $rowAA[0];
		$res = mysql_query("SELECT attribute,rule,text FROM Scope WHERE scope_id = {$scope_id}",$con);
		while($row = mysql_fetch_array($res)){
			if($row[0] != "entity"){
				$Matches    = getMatchedEntities($row[0],$row[1],$row[2],$con,"DID");
				$MatchesDID = getMatchedEntities($row[0],$row[1],$row[2],$con,"DID");
				$MatchesSID = getMatchedEntities($row[0],$row[1],$row[2],$con,"SID");

				if(count($Matches) > 0){
					//echo "for attribute {$row[0]} total matched DID = " . count($Matches) ."<br/>";
					foreach($Matches as $matched_items){
						//echo "matched DID = $matched_items with attr,rule,text = {$row[0]},{$row[1]},{$row[2]},\n";
						$res1 = mysql_query("SELECT MIN(timestamp),MAX(timestamp) FROM DynamicValue WHERE dynamic_id={$matched_items}",$con);
						while($row1 = mysql_fetch_array($res1)){
							$mintim = $row1[0];
							$maxtim = $row1[1];
							//echo("Earliest timestamp for DID {$matched_items} is {$mintim} <br/>");
							//echo("Latest timestamp for DID {$matched_items} is {$maxtim} <br/>");
							if(strtotime($maxtim) > $latest_time)$latest_time = strtotime($mintim);
							if(strtotime($mintim) < $earliest_time)$earliest_time = strtotime($mintim);
						}
					}
				}
			}
		}
	}

	if($which == "earliest"){
		return $earliest_time;
	}elseif($which == "latest"){
		return $latest_time;
	}elseif($which == "DID"){
		return $MatchesDID;
	}elseif($which == "SID"){
		return $MatchesSID;
	}else{
		return "ERROR get_DID_TS called with wrong parameters";
	}
}

function CurrentlyFetchingData($conn){
	$fetching = false;
	$res = mysql_query("SELECT status FROM Dynamic",$conn);
	while($row = mysql_fetch_array($res)){
		if($row[0] != "stopped")$fetching = true;
		if($fetching)break;
	}

	$res = mysql_query("SELECT value FROM HighLevInfo WHERE name = 'MDF_status (fet or not)'",$conn);
	while($row = mysql_fetch_array($res)){
		if(trim($row[0]) == "fet")$fetching = true;
		if($fetching)break;
	}

	return $fetching;
}

function CurrentlyRunningES($conn){
	$running = false;
	$res = mysql_query("SELECT status FROM Output",$conn);
	while($row = mysql_fetch_array($res)){
		if($row[0] == "running")$running = true;
		if($running)break;
	}
	return $running;
}

function VersionOnESRUSite(){
	$Ver=0;
	if(is_connected()){
		$file = 'http://www.esru.strath.ac.uk/Downloads/downloads.htm';
		$handle = fopen($file, "r");

		if ($handle) {
			// Read file line-by-line
			while (($buffer = fgets($handle)) !== false) {
				if (strpos($buffer,"EnTrak_V") == true){
					$Ver = substr($buffer,strpos($buffer,"V") + 1,4);
					break;
				}
			}
		}
		fclose($handle);
	}
	return $Ver;
}

// Get substring between two strings

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

// function to round time in minutes up to the nearest x minutes as specified
// by round_to
function round_minute($round_to, $TZone){
	date_default_timezone_set($TZone);
	$current_hour = date('H');
	$current_min = date('i');
	$current_TS = date('Y-m-d H:i:s');
}

// This function displayes advanced frequency options it works in conjunction with
// a js function to toggle all <p> html tags from visible to invisible as given in
// examples in AddEditFetcher
function echo_advanced_frequency_options($form_name,$start_time_day,$stop_time_day,$day_of_week,$day_of_month,$oper_sys){
global $StandardRendering;
$StdRend = $StandardRendering;
$data = explode(':',$start_time_day);
$start_time_day_hr = $data[0];
$start_time_day_min = $data[1];
$data = explode(':',$stop_time_day);
$stop_time_day_hr = $data[0];
$stop_time_day_min = $data[1];
$DOW = explode(',',$day_of_week);
$DOM = explode(',',$day_of_month);
$days_week = array("", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

echo ("
	<button>Advanced frequency options</button>
	<p style = 'display:none;'>
		<table>
			<tr>
				<td><span title=''><button type='submit' {$StdRend} > Start each day at</button></span></td>
				<td><select name='start_hour' form='{$form_name}'>");
echo ("<option value='' ></option>");
for($i = 0; $i < 24; $i++){
	if($i == $start_time_day_hr && is_numeric($start_time_day_hr)){
		$selected = "selected";
	}else{
		$selected = " ";
	}
	if($i < 10){
		$zero = "0";
	}else{
		$zero = "";
	}
	echo ("<option value='{$zero}{$i}' {$selected}>{$zero}{$i}</option>");
}
echo("			</select></td>
				<td>:</td>
				<td><select name='start_minute' form='{$form_name}'>");
echo ("<option value='' ></option>");
if($oper_sys == "windows"){
    for($i = 0; $i < 60; $i+=5){
        if($i == $start_time_day_min && is_numeric($start_time_day_min)){
            $selected = "selected";
        }else{
            $selected = " ";
        }
        if($i < 10){
            $zero = "0";
        }else{
            $zero = "";
        }
        echo ("<option value='{$zero}{$i}' {$selected}>{$zero}{$i}</option>");
    }
}elseif($oper_sys == "linux"){
    echo ("<option value=''>00</option>");
}
echo("				</select></td>
			</tr>
			<tr>
				<td><span title=''><button type='submit' {$StdRend} >Stop each day at</button></span></td>
				<td><select name='stop_hour' form='{$form_name}'>");
echo ("<option value='' ></option>");

for($i = 0; $i < 24; $i++){
	if($i == $stop_time_day_hr && is_numeric($stop_time_day_hr)){
		$selected = "selected";
	}else{
		$selected = " ";
	}
	if($i < 10){
		$zero = "0";
	}else{
		$zero = "";
	}
	echo ("<option value='{$zero}{$i}' {$selected}>{$zero}{$i}</option>");
}

echo("				</select></td>
				<td>:</td>
				<td><select name='stop_minute' form='{$form_name}'>");
echo ("<option value='' ></option>");
if($oper_sys == "windows"){
    for($i = 0; $i < 60; $i+=5){
        if($i == $stop_time_day_min && is_numeric($stop_time_day_min)){
            $selected = "selected";
        }else{
            $selected = " ";
        }
        if($i < 10){
            $zero = "0";
        }else{
            $zero = "";
        }
        echo ("<option value='{$zero}{$i}' {$selected}>{$zero}{$i}</option>");
    }
}elseif($oper_sys == "linux"){
    echo ("<option value=''>00</option>");
}
echo("				</select></td>
			</tr>
			<tr>
				<td><button type='submit' {$StdRend} >Day of week</button></td>
				<td colspan='3'><select name='day_of_week[]' multiple size='8' style='overflow:hidden' form='{$form_name}'>");

foreach($days_week as $day){
	foreach($DOW as $selected_day){
		if(strcasecmp($day,$selected_day) == 0){
			$selected = "selected";
		}else{
			$selected = "";
		}
		if($selected == "selected")break;
	}
	echo("<option value='{$day}' {$selected}>{$day}</option>");
}

echo("				</select></td>
				<td><button type='submit' {$StdRend} >Day of month</button></td>
				<td colspan='3'><select name='day_of_month' size='8' style='overflow:hidden' form='{$form_name}'>
				<option></option>");

for($i = 1; $i <32; $i++){
	foreach($DOM as $selected_date){
		if($i == $selected_date){
			$selected = "selected";
		}else{
			$selected = "";
		}
		if($selected == "selected")break;
	}
	echo ("<option value='{$zero}{$i}' {$selected}>{$zero}{$i}</option>");
}

// Display string options for day of month
if($oper_sys == "windows"){
    $first_sel 		= "";
    $second_sel 	= "";
    $third_sel 		= "";
    $fourth_sel 	= "";
    $last_sel 		= "";
    $lastday_sel 	= "";
    foreach($DOM as $selected_date){
        if($selected_date == "FIRST"){
            $first_sel = "selected";
        }elseif($selected_date == "SECOND"){
            $second_sel = "selected";
        }elseif($selected_date == "THIRD"){
            $third_sel = "selected";
        }elseif($selected_date == "FOURTH"){
            $fourth_sel = "selected";
        }elseif($selected_date == "LAST"){
            $last_sel = "selected";
        }elseif($selected_date == "LASTDAY"){
            $lastday_sel = "selected";
        }
    }
    echo ("<option value='FIRST'   {$first_sel}		>FIRST</option>");
    echo ("<option value='SECOND'  {$second_sel}	>SECOND</option>");
    echo ("<option value='THIRD'   {$third_sel}		>THIRD</option>");
    echo ("<option value='FOURTH'  {$fourth_sel}	>FOURTH</option>");
    echo ("<option value='LAST'    {$last_sel}		>LAST</option>");
    echo ("<option value='LASTDAY' {$lastday_sel}	>LASTDAY</option>");
}
echo("			</select></td>
			</tr>
		</table>
	</p>
");
}

function human_filesize($bytes, $decimals = 2) {
    $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}

// Returns Scope.attribute ($sel = +ve scope_id) or
//          Operation.name ($sel = -ve operation_id)
// or error message if not a number
function get_operand_name($con,$sel,$mode){
	$name = "ERROR: redefine";
	$sel = intval($sel);

	if(is_integer($sel)){
		if($sel > 0){
			$res = mysql_query("SELECT attribute,rule,text FROM Scope WHERE scope_id = {$sel}",$con);
			while($row = mysql_fetch_array($res)){
				$name = $row[0];
				$rule = $row[1];
				$value = $row[2];
			}
		}elseif($sel < 0){
			$sel = -1 * $sel;
			$sel = intval($sel);
			$res = mysql_query("SELECT name,selectionA,operation,selectionB FROM Operation WHERE operation_id = {$sel}",$con);
			while($row = mysql_fetch_array($res)){
				$name = $row[0];
				$operA = $row[1];
				$oper = $row[2];
				$operB = $row[3];
			}
			$sel = -1 * $sel;
		}elseif($sel == 0){
			$name = "";
		}
	}

	if($mode == "name"){
		return $name;
	}elseif($mode == "help"){
		if($name != "ERROR: redefine"){
			if($sel > 0){
				if($rule = "-"){
					return "Scoped on tag {$name} (select all dynamic and static entities with this tag)";
				}elseif($rule = "="){
					return "Scoped on tag {$name} (select all dynamic and static entities with value = {$value})";
				}elseif($rule = "Contains"){
					return "Scoped on tag {$name} (select all dynamic and static entities whose value contains {$value})";
				}
			}elseif($sel < 0){
				return "Using previously defined input (look in name column on this page)";
			}
		}elseif($name == "" || $name == NULL){
			return "nothing selected for this operand";
		}else{
			return "ERROR: redefine >>>>{$name}<<<<";
		}
	}else{
		return "ERROR: bad call to get_operand_name()";
	}
}

function get_days_in_prev_mnth($mnth,$year){
	if($mnth == "January"){
		$prev_mnth == "December";

	}elseif($mnth == "February"){
		$prev_mnth == "January";

	}elseif($mnth == "March"){
		$prev_mnth == "February";

	}elseif($mnth == "April"){
		$prev_mnth == "March";

	}elseif($mnth == "May"){
		$prev_mnth == "April";

	}elseif($mnth == "June"){
		$prev_mnth == "May";

	}elseif($mnth == "July"){
		$prev_mnth == "June";

	}elseif($mnth == "August"){
		$prev_mnth == "July";

	}elseif($mnth == "September"){
		$prev_mnth == "August";

	}elseif($mnth == "October"){
		$prev_mnth == "September";

	}elseif($mnth == "November"){
		$prev_mnth == "October";

	}elseif($mnth == "December"){
		$prev_mnth == "November";
	}



	if($prev_mnth == "January" || $prev_mnth == "March" || $prev_mnth == "May" || $prev_mnth == "July" || $prev_mnth == "August" || $prev_mnth == "October" || $prev_mnth == "December"){
		return 31;
	}elseif($prev_mnth == "February"){
		$leap = is_leap_year($year);
		if($leap){
			return 29;
		}else{
			return 28;
		}
	}else{
		return 30;
	}
}

// Get percentile in array $data
function mypercentile($data,$percentile){
    if( 0 < $percentile && $percentile < 1 ) {
        $p = $percentile;
    }else if( 1 < $percentile && $percentile <= 100 ) {
        $p = $percentile * .01;
    }else {
        return "";
    }
    $count = count($data);
    $allindex = ($count-1)*$p;
    $intvalindex = intval($allindex);
    $floatval = $allindex - $intvalindex;
    sort($data);
    if(!is_float($floatval)){
        $result = $data[$intvalindex];
    }else {
        if($count > $intvalindex+1)
            $result = $floatval*($data[$intvalindex+1] - $data[$intvalindex]) + $data[$intvalindex];
        else
            $result = $data[$intvalindex];
    }
    return $result;
}
/**
 * Returns the mode value(s) for an array.
 *
 * @param array The array of values to determine the mode.
 * @return mixed Return mode value if there is only one, array of values if bimodel or FALSE if no mode.
 */
function array_mode(array $set)
{
    $counts = array_count_values($set);
    arsort($counts); // Sort counts in descending order
    $modes  = array_keys($counts, current($counts), TRUE);

    // If each value only occurs once, there is no mode
    if (count($set) === count($counts))
        return FALSE;

    // Only one modal value
    if (count($modes) === 1)
        return $modes[0];

    // Multiple modal values
    return $modes;
}


function standard_deviation_population ($a)
{
  //variable and initializations
  $the_standard_deviation = 0.0;
  $the_variance = 0.0;
  $the_mean = 0.0;
  $the_array_sum = array_sum($a); //sum the elements
  $number_elements = count($a); //count the number of elements

  //calculate the mean
  $the_mean = $the_array_sum / $number_elements;

  //calculate the variance
  for ($i = 0; $i < $number_elements; $i++)
  {
    //sum the array
    $the_variance = $the_variance + ($a[$i] - $the_mean) * ($a[$i] - $the_mean);
  }

  $the_variance = $the_variance / $number_elements;

  //calculate the standard deviation
  $the_standard_deviation = pow( $the_variance, 0.5);

  //return the variance
  return $the_standard_deviation;
}

// Get schedule command return command to be passed to windows scheduler or linux cron so that a task
// is run according to the inputs given in a particular record in the Frequency table
// more detail can be found at https://technet.microsoft.com/en-us/library/cc725744.aspx
function GetSchedulerCmd($FID, $TZone, $DID, $DB, $con, $oper_sys){
    date_default_timezone_set($TZone);
		$res = mysql_query("SELECT * FROM Frequency WHERE frequency_id = {$FID}",$con);

	while($row = mysql_fetch_array($res)){
	    $nameF = $row[1];
	    $period = $row[2];
	    $times = $row[3];
	    $start_datetime = $row[4];
	    $stop_datetime = $row[5];
	    $start_time_day = $row[6];
	    $stop_time_day = $row[7];
	    $day_of_week = $row[8]; // comma separated list of days of week
	    $day_of_month = $row[9]; // comma separated list of days of mnth
    }

	// if user has half specified time of day then complete it with 00
	if($start_time_day != ":"){
        if(substr($start_time_day,0,1) == ':')$start_time_day = "00" . $start_time_day;
        if(substr($start_time_day, -1) == ':')$start_time_day .= "00";
	}
	if($stop_time_day != ":"){
		if(substr($stop_time_day,0,1) == ':')$stop_time_day = "00" . $stop_time_day;
		if(substr($stop_time_day, -1) == ':')$stop_time_day .= "00";
	}

	$DOW = explode(',',$day_of_week);
	$DOM = $day_of_month;
	$data = explode(':',$start_time_day);
	$start_time_day_hr = $data[0];
	$start_time_day_min = $data[1];
	$data = explode(':',$stop_time_day);
	$stop_time_day_hr = $data[0];
	$stop_time_day_min = $data[1];

    // get start and stop dates
    if($start_datetime != NULL && !startsWith($start_datetime, "0000")){
        $year = date('Y',strtotime($start_datetime));
        $mnth = date('m',strtotime($start_datetime));
        $day  = date('d',strtotime($start_datetime));
        $start_DT = " /sd " . $day . "/" . $mnth . "/" . $year . " ";
    }
    if($stop_datetime != NULL && !startsWith($stop_datetime, "0000")){
        $year = date('Y',strtotime($stop_datetime));
        $mnth = date('m',strtotime($stop_datetime));
        $day  = date('d',strtotime($stop_datetime));
        $stop_DT = " /ed " . $day . "/" . $mnth . "/" . $year . " ";
    }

    // get start and stop time of day values
    $st_switch = "no";
    $et_switch = "no";
    if($start_time_day_hr != "" || $start_time_day_min != "" )$st_switch = "yes";
    if($stop_time_day_hr != "" || $stop_time_day_min != "")$et_switch = "yes";

    // Figure out is start time is after stop time in which case add the /k switch
    $k_switch = "";
    if($st_switch == "yes" && $et_switch == "yes"){
        if(($start_time_day_hr * 60 + $start_time_day_min) >
        ($stop_time_day_hr * 60 + $stop_time_day_min))$k_switch = "/k";
    }
    $start_cmd = " ";
    $end_cmd   = " ";
    if($st_switch == "yes")	$start_cmd = " /st " . $start_time_day . " ";
    if($et_switch == "yes")	$end_cmd   = " /et " . $stop_time_day . " " . $k_switch . " ";

    // Make checks regarding /sc and /mo (schedule (period in DB) and modifier (times in DB))
    // Start to make the command
    $lin_min  = "*";
    $lin_hour = "*";
    $lin_day  = "*";
    $lin_mnth = "*";
    $lin_wkdy = "*";
    $error_state = 0;
    if($period == "MINUTE"){
        if($times < 1 || $times > 60){
            $error_state = "unsupported number of minutes as {$times} with FID = {$FID}";
            goto exit_w_error;
        }
		$lin_min = "*/".$times; // hopefully user has inserted a factor of 60

    }elseif($period == "HOURLY"){
        if($times < 1 || $times > 23){
            $error_state = "unsupported number of hours";
            goto exit_w_error;
        }
		$lin_min = "0"; // hopefully user has inserted a factor of 60
		$lin_hour = "*/".$times; // hopefully user has inserted a factor of 24

    }elseif($period == "DAILY"){
        if($times < 1 || $times > 365){
            $error_state = "unsupported number of days";
            goto exit_w_error;
        }
    }elseif($period == "WEEKLY"){
        if($times < 1 || $times > 52){
            $error_state = "unsupported number of weeks";
            goto exit_w_error;
        }
    }elseif($period == "MONTHLY"){
        if(is_numeric($times)){
            if($times < 1 || $times > 60){
                $error_state = "unsupported number of months";
                goto exit_w_error;
            }
        }
    }

    // get day of week
    $d_switch = " ";
    if($period == "WEEKLY" || $period == "MONTHLY" || $oper_sys == "linux"){
        $use_d = true;
        if($day_of_week == "")$use_d = false;
        if($day_of_week == NULL)$use_d = false;
        if($day_of_week == ",")$use_d = false;
        if($use_d){
			$tmpstr = rtrim($day_of_week,",");  // remove last character which is ,
			$tmpstr = trim($day_of_week,","); // remove first character which may be ,
			$d_switch = " /d " . $tmpstr . " ";
			$lin_wkdy = $tmpstr;
		}
    }

    // set up modifier value
    $mo_value = $times;

    // d_switch becomes day of month if a numeric day of month is given, m_switch is set on (but is used only on linux side
	// because d_switch is used for both day of week and day of month on windows side)
	$m_switch = " ";
    if(is_numeric($day_of_month)){
        $d_switch = " /d " . $day_of_month . " "; // overrides /d switch
		$m_switch = "numeric";
		$lin_day = $day_of_month;
    }elseif($day_of_month != NULL){
        $mo_value = $day_of_month; // overrides /mo switch
        if($day_of_month == "LASTDAY")$mo_value = " lastday /m * "; // need to put /m switch for lastday (i.e.of every month)
		$m_switch = "string";
    }

    // get modifier (times_per_period) in database
    if(!is_numeric($times)){
        $error_state = "frequency ill defined as " . $times;
        goto exit_w_error;
    }

	// Windows TaskScheduler
	if($oper_sys == "windows"){

    // Make command
    $command = "schtasks.exe /create /tn {$DID}{$DB} /sc {$period} /mo {$mo_value} " ;
    $command .= $start_cmd;
    $command .= $end_cmd;
    $command .= $start_DT;
    $command .= $stop_DT;
    $command .= $d_switch;
    return $command;

	// Linux crontab
	}elseif($oper_sys == "linux"){
		$command = "";
		if($st_switch == "no" && $et_switch == "no"){
		}elseif($st_switch != "no" && $et_switch == "no"){
			if($lin_hour == "*"){
                $lin_hour = $start_time_day_hr . "-23";
			}else{
				$lin_hour = $start_time_day_hr . "-23" . "/" . $times;;
			}
		}elseif($st_switch == "no" && $et_switch != "no"){
            if($lin_hour == "*"){
                $lin_hour = "0-" . $stop_time_day_hr;
            }else{
                $lin_hour = "0-" . $stop_time_day_hr . "/" . $times;
            }
		}elseif($st_switch != "no" && $et_switch != "no"){
			if($k_switch == "/k"){ // start time is after end time
				if($lin_hour == "*"){
					$lin_hour = "0-" . $stop_time_day_hr;
					$command = $lin_min ." ". $lin_hour ." ". $lin_day ." ". $lin_mnth ." ". $lin_wkdy . " <br/>";
					$lin_hour = $start_time_day_hr . "-23";
				}else{
                    $lin_hour = "0-" . $stop_time_day_hr . "/" . $times;;
                    $command = $lin_min ." ". $lin_hour ." ". $lin_day ." ". $lin_mnth ." ". $lin_wkdy . " <br/>";
                    $lin_hour = $start_time_day_hr . "-23" . "/" . $times;;
				}
			}else{
				if($lin_hour == "*"){
                    $lin_hour = $start_time_day_hr . "-" . $stop_time_day_hr;
                }else{
                    $lin_hour = $start_time_day_hr . "-" . $stop_time_day_hr . "/" . $times;;
                }
            }
        }

		$command .= $lin_min ." ". $lin_hour ." ". $lin_day ." ". $lin_mnth ." ". $lin_wkdy . " <br/>";
		return $command;
    }

	// exit with error statement
	exit_w_error:
	echo ("ERROR IN GetSchedulerCmd: Error state = " . $error_state . " End of error statement");
}

// Function to copy file $in to $out while replacing $foo with $bar
function FileCopier($in,$out,$foo,$bar){
	$rf = fopen($in,"r") or die ("Could not open $in from FileCopier for reading");
	$wf = fopen($out,"w") or die ("Could not open $out from FileCopier for writing");
	while ($line = fgets($rf)) {
		$out_line = str_replace($foo,$bar,$line);
		fwrite($wf,$out_line);
	}
	fclose($rf);
	fclose($wf);
}

// add line to crontab
function add_to_cron($line){
	$mycron = shell_exec("crontab -l"); // output current cron jobs
	$mycron .= $line; 				// add this cron job still to add full path
	$handle = fopen("tmpfile", "w");
	fwrite($handle,$mycron);
	fclose($handle);
	shell_exec("crontab tmpfile");		// add jobs in this file to crontab
	unlink("tmpfile");
}

// remove line containing D_O_IDDB from crontab
function rm_from_cron($D_O_IDDB){
	$mycron = shell_exec("crontab -l"); // output current cron jobs
	$lines = explode("\n", $mycron);
	$exclude = array();
	foreach ($lines as $line) {
		if (strpos($line, $D_O_IDDB) !== FALSE){
			continue;
		}
		$exclude[] = $line;
	}
	$mycron = implode("\n", $exclude);
	$handle = fopen("tmpfile", "w");
	fwrite($handle,$mycron);
	fclose($handle);
	shell_exec("crontab tmpfile");
	unlink("tmpfile");
}

// is internet access available?
function is_connected(){
	$response = null;

	// ob start and clean ensure there is no output from system command
	// by setting on output buffering to store to internal buffer and then
	// cleaning it
	ob_start();
	system("ping google.com", $response);
	ob_clean();
	if($response == 0){ // this means you are connected
	  return true;
	}else{
		return false;
	}
}



function getOS() {

    global $user_agent;

    $os_platform    =   "Unknown OS Platform";

    $os_array       =   array(
                            '/windows nt 10/i'     =>  'Windows 10',
                            '/windows nt 6.3/i'     =>  'Windows 8.1',
                            '/windows nt 6.2/i'     =>  'Windows 8',
                            '/windows nt 6.1/i'     =>  'Windows 7',
                            '/windows nt 6.0/i'     =>  'Windows Vista',
                            '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                            '/windows nt 5.1/i'     =>  'Windows XP',
                            '/windows xp/i'         =>  'Windows XP',
                            '/windows nt 5.0/i'     =>  'Windows 2000',
                            '/windows me/i'         =>  'Windows ME',
                            '/win98/i'              =>  'Windows 98',
                            '/win95/i'              =>  'Windows 95',
                            '/win16/i'              =>  'Windows 3.11',
                            '/macintosh|mac os x/i' =>  'Mac OS X',
                            '/mac_powerpc/i'        =>  'Mac OS 9',
                            '/linux/i'              =>  'Linux',
                            '/ubuntu/i'             =>  'Ubuntu',
                            '/iphone/i'             =>  'iPhone',
                            '/ipod/i'               =>  'iPod',
                            '/ipad/i'               =>  'iPad',
                            '/android/i'            =>  'Android',
                            '/blackberry/i'         =>  'BlackBerry',
                            '/webos/i'              =>  'Mobile'
                        );

    foreach ($os_array as $regex => $value) {

        if (preg_match($regex, $user_agent)) {
            $os_platform    =   $value;
        }

    }

    return $os_platform;

}

function getBrowser() {

    global $user_agent;

    $browser        =   "Unknown Browser";

    $browser_array  =   array(
                            '/msie/i'       =>  'Internet Explorer',
                            '/firefox/i'    =>  'Firefox',
                            '/safari/i'     =>  'Safari',
                            '/chrome/i'     =>  'Chrome',
                            '/edge/i'       =>  'Edge',
                            '/opera/i'      =>  'Opera',
                            '/netscape/i'   =>  'Netscape',
                            '/maxthon/i'    =>  'Maxthon',
                            '/konqueror/i'  =>  'Konqueror',
                            '/mobile/i'     =>  'Handheld Browser'
                        );

    foreach ($browser_array as $regex => $value) {

        if (preg_match($regex, $user_agent)) {
            $browser    =   $value;
        }

    }

    return $browser;

}

// Get outputs from an operation that are conditional
function get_conditional_OID($operation_id,$con){

}


// Uncomment the following to display OS and browser information etc.
//$device_details =   "<strong>Browser: </strong>".$user_browser."<br /><strong>Operating System: </strong>".$user_os."";
//print_r($device_details);
//echo("<br /><br /><br />".$_SERVER['HTTP_USER_AGENT']."");
?>
