<?php
# Panel to view the Duplicti Backup Records

/*
  ToDo..
    *  Make it able to exclude weekends in counting expiration date.
		*  Create Readme with variables
		*  Create remove record button using "ID" field.
		
		
*/

	error_reporting(E_ALL);
	ini_set('display_errors', 1);

	Include('inc/IncludeLib.php');

	$Settings['Debug'] = False;
	$Settings['DebugLevel'] = 5;

	GetValueFromURL('Debug', $Settings['Debug']); //-> Get  from URL	

	If ($Settings['Debug']) {
		$Settings['hDebugLogFile'] = FOpen("DebugLog.txt", "w"); //-> Open NEW File for output
		LogEvent(1, "Okay, Starting things up....", True, False);
	}

	LogEvent(1, "Reading Configuration Settings");

#	If (IsSet($_GET['DeleteRecord'])) {
#		DeleteRecord($_GET['DeleteRecord']);
#		Exit;
#	}

	$aTemplateVariables['Title'] = "Desktop Masters Backups";

#> App Settings
	$Settings['DisplayTitleBar'] = True; //-> Display the title bar for the node list
	$Settings['GroupResults'] = False; //-> Toggle the grouping of the results.  False means no groups, just a flat list.
	$Settings['GroupResultsLimit'] = 0; //-> Will group any results equal to or larger than this number.  Otherwise the results go into RogueNodesList. Set to 0 (Zero) to turn off
	$Settings['RogueNodesListName'] = "Individual Workstations"; //> Will group any results equal to or larger than this number.  Otherwise the results go into a single container.
	$Settings['OrderNodesBy'] = "ComputerName"; //-> Sort order for the list
#	$Settings['DateFormat'] = "m/d/Y h:i a"; //-> Formatting for %LastBackupDateFormatted%

#> For Backup Checking.....
	$Settings['ExpirationTime'] = 3; //-> Time in days until the backup has expired (Backup expires on this day)
	$Settings['CountWeekends'] = False; //-> Time in days before the backup has expired
	$Settings['TimeZone'] = 'PST'; //-> Time Zone
	$Settings['FailedCSS'] = ' cursor: pointer;'; //-> CSS used in the style for a "Failed" backup Row.
	$Settings['FailedHTMLArguments'] = 'data-toggle="popover" data-placement="bottom" data-toggle="popover" title="%Message%" data-content="%ErrorMessage%"'; //-> HTML Arguments used on the line for a "Failed" Backup that make it a button.
	$Settings['FailIcon'] = '<img src="images/Warning.png" style="width: 21px;">'; //-> Image HTML to use for a fail icon when backup fails


#> Database Settings
	$Settings['DB_Host'] = "MySQL";
	$Settings['DB_User'] = "dm_dm";
	$Settings['DB_Password'] = "stupidputty";
	$Settings['DB_Name'] = "DesktopMasters.com";
	$Settings['DB_NodesTable'] = "dmss_backup_status";
	$Settings['DB_GroupsTable'] = "dmss_groups";
	$Settings['DB_Port'] = 3306;

	OpenDatabase();
	DisplayPage();
	CloseDatabase();

	If ($Settings['Debug']) {
		LogEvent(1, "Process Complete: Terminating Script Naturally...");
		LogEvent(1, "Bye!! Thanks for all the Fish!", False, False);
		FClose($Settings['hDebugLogFile']);
	}

	Exit;

#==========================================================================================================
Function DisplayPage() {
	Global $Settings, $aTemplateVariables;

	$LocalDebugLevel = 1;
	LogEvent($LocalDebugLevel, "In DisplayPage() Function...");

	Echo '<!doctype html5>';
	Echo '<html lang="en">';

	LogEvent($LocalDebugLevel+1, "Reading templates and setting default values");
	$sBodyTemplate = GetHTML("Templates/body.html");
	$sContainer = GetHTML("Templates/container.html");
	$sNodeGroupTemplate = GetHTML("Templates/nodegroup.html");
	$sNodeListTemplate = GetHTML("Templates/nodelist.html");
	$sNodeListWrapper =  GetHTML("Templates/nodelistwrapper.html");
	$iRogueComputerCount = 0;
	$sComputerList = "";
	$sRogueNodesList = "";
	$bShowGroupTitles = False;
	$Groups = Array();

	If ($Settings['DisplayTitleBar']) {  //-> Changes style to show the title bar of the Node list
		LogEvent($LocalDebugLevel+1, "TitleBar (Above Node List) being displayed");
		$aTemplateVariables['DisplayTitleBar'] = "visible";
	} Else { //-> Changes style to hide the title bar of the Node list
		LogEvent($LocalDebugLevel+1, "TitleBar (Above Node List) is being HIDDEN");
		$aTemplateVariables['DisplayTitleBar'] = "none";
	}

	$aTemplateVariableKeys = Array_Keys(ConvertArrayToVariables($aTemplateVariables));
	
	LogEvent($LocalDebugLevel+1, "Replacing Variables in the header.html template");
	Print Str_iReplace($aTemplateVariableKeys, $aTemplateVariables, GetHTML("Templates/header.html")); #> Replaces all variables in the template

	If ($Settings['GroupResults']) { //-> Switch: Display Results in Groups
		LogEvent($LocalDebugLevel+1, "Grouping Results");
		$GroupsFromDB = $Settings['hDB'] -> Query('SELECT name,displayname FROM '.$Settings['DB_GroupsTable'].' WHERE Visible LIKE "Y" ORDER BY name ASC;');
		While ($GroupRow = MySQLi_Fetch_Array($GroupsFromDB)) { //-> Loop through all the groups
			LogEvent($LocalDebugLevel+1, "Processing Group: ".$GroupRow['name']);
			$NodesFromDB = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE NodeGroup LIKE "'.$GroupRow['name'].'" AND NodeID LIKE "%" ORDER BY '.$Settings['OrderNodesBy'].' ASC;'); //-> Read nodes in the currently selected group.
			If ($NodesFromDB->num_rows > 0) {
				LogEvent($LocalDebugLevel+2, "Retrieved [".$NodesFromDB->num_rows."] Nodes From ".$GroupRow['name']." Group.");
				$sNodeList = ""; #> Reset Node List
				While ($NodeRow = MySQLi_Fetch_Array($NodesFromDB)) { //-> Read the rest of the nodes in the group
					$bFailedBackup = False; //-> Reset variable for each loop
					$aNodeRow = ConvertArrayToVariables($NodeRow);
#> ------[ Cleanup And add Variables for Grouped List ]-----------
#					$aNodeRow['%LastBackupDateFormatted%'] = Date($Settings['DateFormat'], $aNodeRow['%LastBackupDateUnix%']);
					$aNodeRow['%LastBackupDateFormatted%'] = TimeElapsed("@".$aNodeRow['%LastBackupDateUnix%'], False);
					$aNodeRow['%Version%'] = SubStr($aNodeRow['%Version%'], 0, StrPos($aNodeRow['%Version%'], " ")); //-> Crop the extra version version information after the first space.
					$aNodeRow['%Status%'] = $aNodeRow['%ParsedResult%'];
					$aNodeRow['%FailIcon%'] = '';
					If ($aNodeRow['%Status%'] == "Failed") { //-> Backup failed so make row a button so we can see the errors
						$bFailedBackup = True;
						$aNodeRow['%FailedCSS%'] = $Settings['FailedCSS']; //-> CSS used in the style for a "Failed" backup Row.
						$aNodeRow['%FailedHTMLArguments%'] = $Settings['FailedHTMLArguments']; //-> HTML Arguments used on the line for a "Failed" Backup that make it a button.
						$aNodeRow['%FailIcon%'] = $Settings['FailIcon'];
					}
					If ($Settings['ExpirationTime'] <= HowManyDays("@".$aNodeRow['%LastBackupDateUnix%'])) {
						$aNodeRow['%Status%'] = "Expired";
					}
#					Print Print_R($aNodeRow)."<br />\n"."<br />\n"."<br />\n";
#> ------[/ Cleanup And add Variables ]-----------
					If ($bFailedBackup) { //-> Failed Backup.  Run through the replace a second time to catch the secondary variables.
						$sNodeList .= Str_iReplace(Array_Keys($aNodeRow), $aNodeRow,  Str_iReplace(Array_Keys($aNodeRow), $aNodeRow,  $sNodeListTemplate)); //-> Add Current row to collection
					} Else { //-> Do it the normal way...
						$sNodeList .= Str_iReplace(Array_Keys($aNodeRow), $aNodeRow,  $sNodeListTemplate); //-> Add Current row to collection
					}
				}
				$sNodeGroup = Str_iReplace("%GroupName%", $GroupRow['name'], Str_iReplace("%GroupDisplayName%", $GroupRow['displayname'], $sNodeGroupTemplate)); //-> Apply the Display name for the group
				$sNodeListWrapped = Str_iReplace("%NodeList%", $sNodeList, $sNodeListWrapper); #> Add Group with Nodes to the ComputerList
				If ($NodesFromDB->num_rows >= $Settings['GroupResultsLimit']) {
					$sNodeGroup = Str_iReplace("%NodeListWrapper%", $sNodeListWrapped, $sNodeGroup); #> Add Group with Nodes to the ComputerList
					$sComputerList .= Str_iReplace("%NodeList%", $sNodeList, $sNodeGroup); #> Add Group with Nodes to the ComputerList
				} Else {
					LogEvent($LocalDebugLevel+2, "Under Threashold: Adding Nodes to Rouge Group Listing");
					$sRogueNodesList .= $sNodeList; //-> If Node/Computer list is below the threashold it adds it to the Rouge List.
					$iRogueComputerCount += 1;
				}
			}
		}
#		Print "Computer Count: ".$iRogueComputerCount."<br />\n";
		If ($iRogueComputerCount > 0) {
			LogEvent($LocalDebugLevel+1, "Printing Grouge Group List");
			$sRogueNodesList = Str_iReplace("%NodeList%", $sRogueNodesList, $sNodeListWrapper); #> Add Group with Nodes to the ComputerList
			$sRogueNodesGroup = Str_iReplace("%GroupDisplayName%", $Settings['RogueNodesListName'], $sNodeGroupTemplate);
			$sRogueNodesGroup = Str_iReplace("%NodeListWrapper%", $sRogueNodesList, $sRogueNodesGroup); #> Add Group with Nodes to the ComputerList
			$sContainer = Str_iReplace("%ROGUENODESLIST%", $sRogueNodesGroup, $sContainer); #> Insert Computer List into Container
		}
	} Else { //-> Display results as flat list
		$sNodeList = ""; #> Rest Node List
		$NodesFromDB = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE NodeID LIKE "%" ORDER BY '.$Settings['OrderNodesBy'].' ASC;');
		If ($NodesFromDB->num_rows > 0) {
			LogEvent($LocalDebugLevel+1, "Grouping toggled off.  Building a Flat List.");
			While ($NodeRow = MySQLi_Fetch_Array($NodesFromDB)) {
				$bFailedBackup = False; //-> Reset variable for each loop
				$aNodeRow = ConvertArrayToVariables($NodeRow);
#> ------[ Cleanup And add Variables for Flat, Ungrouped, List ]-----------
#				$aNodeRow['%LastBackupDateFormatted%'] = Date($Settings['DateFormat'], $aNodeRow['%LastBackupDateUnix%']);
				$aNodeRow['%LastBackupDateFormatted%'] = TimeElapsed("@".$aNodeRow['%LastBackupDateUnix%'], False);
				$aNodeRow['%Version%'] = SubStr($aNodeRow['%Version%'], 0, StrPos($aNodeRow['%Version%'], " ")); //-> Crop the extra version version information after the first space.
				$aNodeRow['%Status%'] = $aNodeRow['%ParsedResult%'];
				$aNodeRow['%FailIcon%'] = '';
				If ($aNodeRow['%Status%'] == "Failed") { //-> Backup failed so make row a button so we can see the errors
					$bFailedBackup = True;
					$aNodeRow['%FailedCSS%'] = $Settings['FailedCSS']; //-> CSS used in the style for a "Failed" backup Row.
					$aNodeRow['%FailedHTMLArguments%'] = $Settings['FailedHTMLArguments']; //-> HTML Arguments used on the line for a "Failed" Backup that make it a button.
					$aNodeRow['%FailIcon%'] = $Settings['FailIcon'];
				}
				If ($Settings['ExpirationTime'] <= HowManyDays("@".$aNodeRow['%LastBackupDateUnix%'])) {
					$aNodeRow['%Status%'] = "Expired";
				}
#Print HowManyDays("@".$aNodeRow['%LastBackupDateUnix%'])."<br />\n";
#				Print Print_R($aNodeRow)."<br />\n";
#> ------[/ Cleanup And add Variables ]-----------
				If ($bFailedBackup) { //-> Failed Backup.  Run through the replace a second time to catch the secondary variables.
					$sNodeList .= Str_iReplace(Array_Keys($aNodeRow), $aNodeRow,  Str_iReplace(Array_Keys($aNodeRow), $aNodeRow,  $sNodeListTemplate)); //-> Add Current row to collection
				} Else { //-> Do it the normal way...
					$sNodeList .= Str_iReplace(Array_Keys($aNodeRow), $aNodeRow,  $sNodeListTemplate); //-> Add Current row to collection
				}
			}
		}
		$sNodeListWrapped = Str_iReplace("%NodeList%", $sNodeList, $sNodeListWrapper); #> Add Group with Nodes to the ComputerList
		$sComputerList .= Str_iReplace("%NodeList%", $sNodeList, $sNodeListWrapped); #> Add Group with Nodes to the ComputerList
	}

		
	$sContainer = Str_iReplace("%COMPUTERLIST%", $sComputerList, $sContainer); #> Insert Computer List into Container
	$sContainer = Str_iReplace("%ROGUENODESLIST%", "", $sContainer); #> If no Rogue List it removes the tag
	$sBody = Str_iReplace("%CONTAINER%", $sContainer, $sBodyTemplate); #> Insert Container Into Body
	$sBody = Str_iReplace($aTemplateVariableKeys, $aTemplateVariables, $sBody); #> Replaces all variables in the template

	Print $sBody;
	Print Str_iReplace($aTemplateVariableKeys, $aTemplateVariables, GetHTML("Templates/footer.html")); #> Replaces all variables in the template

	Return;
}
#----------------------------------------------------------------------------------------------------------
Function DeleteRecord($RecordID) {
	LogEvent(1, "Deleting Record: ".$RecordID);
}



#==========================================================================================================
?>