<?php

#	Include('inc/IncludeLib.php');



#==========================================================================================================
Function ConvertArrayToVariables($aArray, $CurrentLogLevel = 3) {
#> This will convert the first table in an array so it has %Percent% signs around them for a search and replace	
	LogEvent($CurrentLogLevel, "In ConvertArrayToVariables() Function");

	$aNewArray = Array();
	$aKeys = Array_Keys($aArray);

	For ($iRow = 0; $iRow < Count($aArray); $iRow++) {
		$aNewArray["%".$aKeys[$iRow]."%"] = $aArray[$aKeys[$iRow]];
	}
#	Print_R($aArray);
#	Print_R($aNewArray);
	Return $aNewArray;
}
#----------------------------------------------------------------------------------------------------------
Function ConvertToUnixTimeStamp( $TimeStamp ) {
#> Converts a TimeStamp into a UnixTimestamp
# Note: Put an "@" in front of the Unix TimeStamp to make the system recognize it.
	Global $bDebug;
	
	If ($TimeStamp == "") {
		Return $TimeStamp;
	}
	
	$TimeStamp = new DateTime($TimeStamp, new DateTimeZone('GMT'));
	$TimeStamp->setTimezone(new DateTimeZone('PST'));
	$UnixTimeStamp = mktime($TimeStamp->Format('H'), $TimeStamp->Format('i'), $TimeStamp->Format('s'), $TimeStamp->Format('n'), $TimeStamp->Format('j'), $TimeStamp->Format('Y'))+(60*60);
#	If ($bDebug) { Print "Formated Date: ".date("Y-m-d h:i a", $UnixTimeStamp)."\n"; }
#	If ($bDebug) { Print "Unix TimeStamp: ".$UnixTimeStamp."\n"; }
	
	Return $UnixTimeStamp;
}
#----------------------------------------------------------------------------------------------------------
Function GetHTML($FileName) {
#> Reads HTML template and returns the data
	LogEvent(3, "Loading HTML Template: ".$FileName);

	$hFile = FOpen($FileName, "r") or die("Unable to open file! - ".$FileName);
	$HTML = FRead($hFile, FileSize($FileName));
	FClose($hFile);
	
	Return $HTML;
}
#----------------------------------------------------------------------------------------------------------
Function GetJSondata( $AuthToken = "" ) {
# Get JSON data
	Global $Settings, $bDebug;
	$LocalDebugLevel = 2;

// Make sure that it is a POST request.
	if(StrCaseCmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
		LogEvent(1, "Abort: Request method must be POST!", False, False);
		Die("Request method must be POST!<br />\r\n");
#		throw new Exception("Request method must be POST!");
	}
	
	LogEvent($LocalDebugLevel, "Reading JSON Data from remote host");
// Recieve and Attempt to decode the incoming RAW post data from JSON.
#	$aJSonData =  File_Get_Contents("php://input");
#	$aJSonData =  URLDecode(File_Get_Contents("php://input"));
	$aJSonData = JSon_Decode(Trim(File_Get_Contents("php://input")), True);
	
// If json_decode failed, the JSON is invalid.
	if(!is_array($aJSonData)){
		LogEvent(1, 'Aborting Script: $aJSonData is not an array.', False, False);
		Die("Received content contained invalid JSON!<br />\r\n");
	}

#	Print Print_R($aJSonData)."\r\n";

	If ($AuthToken == "") {
		If (IsSet($aJSonData['AuthToken'])) {
			$AuthToken = $aJSonData['AuthToken'];
		}
	}

	If ($Settings['AuthTokenKey'] != $AuthToken) {
		LogEvent(1, 'Aborting Script: AuthTokenKey and AuthToken do not match.\n AuthTokenKey='.$Settings['AuthTokenKey'].'\nAuthKey='.$AuthToken, False, False);
		Die("Internal Error. Now fuck off...!<br />\r\n");
	}

	Return $aJSonData;
}
#----------------------------------------------------------------------------------------------------------
Function GetValueFromURL($VariableName, $DefaultValue = "", $MaskInLog = False) {
#> Gets a Value from a Variable from the URL and saves it to the settings.
# Note: This Auto-accounts for UPPERCASE, lowercase, and CamelBack Variables.

	Global $Settings;

	LogEvent(2, "Checking URL for Variable: ".$VariableName, False, True, False);
	
	If ($DefaultValue != False) { //-> Creates an empty version of this Settings Variable if set to True in commandline
		$Settings[$VariableName] = $DefaultValue;
	}
		
	If (IsSet($_GET[$VariableName])) {
		$Settings[$VariableName] = $_GET[$VariableName]; 
	} ElseIf (IsSet($_GET[StrToLower($VariableName)])) {
		$Settings[$VariableName] = $_GET[StrToLower($VariableName)];
	} ElseIf (IsSet($_GET[StrToUpper($VariableName)])) {
		$Settings[$VariableName] = $_GET[StrToUpper($VariableName)];
	} Else {
		LogEvent(3, " = ".$DefaultValue." (Supplied Default)", False, False);
		Return;
	}

	If ($MaskInLog) {
		LogEvent(3, " = ".Str_Repeat("*", StrLen($Settings[$VariableName]))." (Masked)", False, False);
	} Else {
		LogEvent(3, " = ".$Settings[$VariableName], False, False);
	}
}
#----------------------------------------------------------------------------------------------------------
Function HowManyDays($DateStamp) {
	Global $Settings;
	$Date = new DateTime($DateStamp);
	$Now = new DateTime("now", new DateTimeZone($Settings['TimeZone']));
	$Difference = $Date->diff($Now);
	
	Return $Difference->Format('%a');	
}
#----------------------------------------------------------------------------------------------------------
Function Human_FileSize($Bytes, $Decimals = 2) {
#> Convert a number in Bytes to a Human Readable Format

  $Size = 'BKMGTP';
  $Factor = Floor((StrLen($Bytes) - 1) / 3);
	
  Return SprintF("%.{$Decimals}f", $Bytes / Pow(1024, $Factor)) . @$Size[$Factor];
}
#----------------------------------------------------------------------------------------------------------
Function INI_Write($FileName, $Section, $Key, $Value) {
	Global $Settings, $bDebug;
	
#	echo Shell_Exec("ls -hal ".$FileName);
#	echo Shell_Exec("cat ".$FileName);
	If (File_Exists($FileName)) {
		$aIni = Parse_Ini_File($FileName, True, INI_SCANNER_RAW); //-> Read File and convert to array
	}
	
	$aIni[$Section][$Key] = $Value; 

	$hFile = FOpen($FileName, "w"); //-> Open File for output
	While (List($xSection, $aKeys) = Each($aIni)) { //-> Write File Data back to file
		FWrite($hFile, "[".$xSection."]\r\n");
		While (List($xKey, $xValue) = Each($aKeys)) {
			FWrite($hFile, "  ".$xKey."=".$xValue."\r\n");
		}
		FWrite($hFile, "\r\n");
	}
	FClose($hFile);
	
	Return;
}
#----------------------------------------------------------------------------------------------------------
Function LogEvent($LocalDebugLevel, $EventText, $bTimeStamp=False, $AutoIndent=True, $AddReturnLine=True) {
	Global $Settings;

	If (IsSet($Settings['Debug']) == False  or  IsSet($Settings['DebugLevel']) == False) { Return; } //-> If not set do not use function
	If ($Settings['Debug'] == False) { Return; }
	If ($Settings['DebugLevel'] == 0 or $Settings['Debug']==False) { Return; }

	If (IsSet($Settings['hDebugLogFile'])) { //-> If a global debug log file is set then it uses that.  Otherwise it opens it just for the duration of the fuction.
		$hDebugLogFile = $Settings['hDebugLogFile'];
	} Else {
		$hDebugLogFile = FOpen("DebugLog.txt", "a"); //-> Open File to append output
	}

#----[ Copy Past to top of main script ]---------------------
#	If ($Settings['Debug']) {
#		$Settings['hDebugLogFile'] = FOpen("DebugLog.txt", "w"); //-> Open NEW File for output
#	}
#-------------------------------------------------------------
	
#	If ($bTimeStamp) {
#		$TimeStamp=@YEAR . "." . @MON . "." . @MDAY  . "+" . @HOUR . ":" . @MIN . ":" . @SEC . " - "
#	} Else {
		$TimeStamp="";
#	}

	$EventText = Str_iReplace("<br />", "", $EventText);

	If ($LocalDebugLevel <= $Settings['DebugLevel']) {
		If ($AutoIndent == True) {
			$EventText = Str_Repeat(" ", ($LocalDebugLevel - 1) * 2) . "* " . Trim($EventText);
		}
		If ($AddReturnLine) { $EventText .= "\r\n"; }
		FWrite($hDebugLogFile, $TimeStamp . $EventText);
	}

	If (IsSet($Settings['hDebugLogFile']) == False) { //-> If a global debug log file is set then it uses that.  Otherwise it opens it just for the duration of the fuction.
		FClose($hDebugLogFile);
	}

#----[ Copy Past to bottom of main script ]---------------------
#	$Settings['Debug'] = True;
#	$Settings['DebugLevel'] = 5;
#	If ($Settings['Debug']) {
#		FClose($Settings['hDebugLogFile']);
#	}
#-------------------------------------------------------------


}
#----------------------------------------------------------------------------------------------------------
Function OpenDatabase() {
	Global $Settings;

	LogEvent(1, "Opening Database ".$Settings["DB_Host"].":".$Settings['DB_Name']);
	
	$Settings['hDB'] = new MySQLi($Settings["DB_Host"], $Settings['DB_User'], $Settings['DB_Password'], $Settings['DB_Name'], $Settings['DB_Port']);
		If ($Settings['hDB'] -> connect_error) {
			If ($bDebug) { LogEvent(1, "Connection failed: " . $Settings['hDB'] -> connect_error); }
			die("Connection failed: " . $Settings['hDB'] -> connect_error . "<br />\r\n");
		}
	If ($Settings['Debug']) { LogEvent(2, "Connected to host via: " . $Settings['hDB'] -> host_info); }
}
#----------------------------------------------------------------------------------------------------------
Function CloseDatabase() {
#> Closes the Database opened from OpenDatabase()
	Global $Settings;
	
	LogEvent(1, "Closing Database ".$Settings["DB_Host"].":".$Settings['DB_Name']);
	$Settings['hDB'] -> Close();
}
#----------------------------------------------------------------------------------------------------------
Function ReplaceText() {
#> Goes through a field in a table and does a search and replace on the text.
	Global $Settings;

		$sNodeList = ""; #> Rest Node List
		$NodesFromDB = $Settings['hDB'] -> Query('SELECT * FROM vnc_nodes WHERE Visible LIKE "Y" OR Visible LIKE "N"  ORDER BY '.$Settings['OrderNodesBy'].' ASC;');
		If ($NodesFromDB->num_rows > 0) {
			While ($NodeRow = MySQLi_Fetch_Array($NodesFromDB)) {
				$SearchFor=$NodeRow['NodeID'];
				$ReplaceWith="";
				$InField='DisplayName';
				$NewValue = Str_iReplace($SearchFor, $ReplaceWith, $InField);
				Print $NewDisplayName ."<br />\n";
				$qSQL = "UPDATE vnc_nodes SET ". $InField ."='". $NewValue ."' WHERE id=". $NodeRow['id'] .";";
				If ($Settings['hDB'] -> Query($qSQL) !== True) {
					Echo "Error: " . $qSQL . "<br />\r\n" . $Settings['hDB'] -> error . "<br />\r\n";
				}
			}
		}
	Return;
}
#----------------------------------------------------------------------------------------------------------
Function RoundUpTimer( $Duration ) {
	Global $bDebug;

	If ( $Duration == "" ) {
		Return $Duration;
	}

	$aDuration = Explode(".", $Duration);
	$Partial = Round(".".$aDuration[1]);
	$aDuration = Explode(":", $aDuration[0]);
	$Duration = Str_Pad($aDuration[0], 2, "0", STR_PAD_LEFT).":".Str_Pad($aDuration[1], 2, "0", STR_PAD_LEFT).":".Str_Pad($aDuration[2]+$Partial, 2, "0", STR_PAD_LEFT);

	Return $Duration;
}
#----------------------------------------------------------------------------------------------------------
Function TimeElapsed($DateTime, $Full = False) {
    $Now = new DateTime;
    $Ago = new DateTime($DateTime);
    $Diff = $Now->diff($Ago);

    $Diff->w = Floor($Diff->d / 7);
    $Diff->d -= $Diff->w * 7;

    $Text = array(
        'y' => 'Year',
        'm' => 'Month',
        'w' => 'Week',
        'd' => 'Day',
        'h' => 'Hour',
        'i' => 'Minute',
        's' => 'Second',
    );
		
    ForEach ($Text as $k => &$v) {
        If ($Diff->$k) {
            $v = $Diff->$k . ' ' . $v . ($Diff->$k > 1 ? 's' : '');
        } Else {
            UnSet($Text[$k]);
        }
    }

    if (!$Full) $Text = array_slice($Text, 0, 1);
    return $Text ? implode(', ', $Text) . ' Ago' : 'Just Now!';
}

#==========================================================================================================


?>