<?php
# * Panel to View the VNC Nodes List and connect to them.

#	* Records Node Inforatmion in Database
#	* Uses Workgroup as Group.
#	* If "DetectNodeNumber" is turned on.  The Node ID will be created from a combination of the Group Number (Generated from the vnc_groups table)
#		and the Node number in the computer name after the last hyphen "NODE-02".  So if the group DM is "1" the node ID is 000102.
# * Automatic NodeID's that are generated from the number counter (If "DetectNodeNumber" is set to false) are taken from 99999999 counting backwards.
# * If Matching computer UniqueComputerID is found in the database then that record is used and the data is overwritten/updated.
# * If Matching NodeID is found in the Database then that record is used and the data is overwritten/updated.  (This is check after the UniqueComputerID does not match)
# * Preceeding Zero's "00023" are ignored by the viewer and repeater at the time of the connection.  Putting them there or not there have no effect other than visual.

/*
* Variables in Computer Node List
* %ComputerType% = W - Workstation | L - Laptop | M - MultiFunction | S - Server | T - Tablet
*/

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

	Include('inc/IncludeLib.php');
	
	$Settings['Debug'] = True;
	$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");

	$aTemplateVariables["Title"] = "Desktop Masters Computers";

#> 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'] = 3; //> Will group any results equal to or larger than this number.  Otherwise the results go into RogueNodesList.
	$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"; // Padding of zeros's in front of the Group's Number.
	$Settings['GroupPadding'] = 4; // Padding of zeros's in front of the Group's Number.
	$Settings['PathToLauncherFiles'] = "uvnc";
	$Settings['ViewerURL'] = "DM-S01:55900";

#> For DMMT
	$Settings['DisplayDMMTStatus'] = True; //-> Enable/Disable the DMMT Update Status of Nodes
	$Settings['DMMTOptionsTable'] = 'dmss_options'; //-> Enable/Disable the DMMT Update Status of Nodes
	$Settings['DMMTStatusIconHTML'] = '<img src="images/%IconName%.gif" style="width: 21px;">'; //-> Image HTML to show the status of the DMMT

	
#> For Backup Checking.....
	$Settings['DisplayBackupStatus'] = True; //-> Enable/Disable the Duplicati backupstatus column
	$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['DB_BackupNodesTable'] = "dmss_backup_status";
	$Settings['BackupIconHTML'] = '<img src="images/%IconName%.gif" style="width: 21px;">'; //-> Image HTML to show the status of the backup

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

	OpenDatabase();
	DisplayPage();
#	ReplaceText();
	
	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'] = "visble";
	} 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";
	}

	If ($Settings['DisplayBackupStatus']) {  //-> Changes style to show the Duplicati backup status column.
		LogEvent($LocalDebugLevel+1, "Duplicati Backup Status Column being displayed");
		$aTemplateVariables['DisplayBackupStatus'] = "visble";
	} Else { //-> Changes style to hide the Duplicati backup status column
		LogEvent($LocalDebugLevel+1, "Duplicati Backup Status Column is being HIDDEN");
		$aTemplateVariables['DisplayBackupStatus'] = "none";
	}

	If ($Settings['DisplayDMMTStatus']) {  //-> Changes style to show the Duplicati backup status column.
		LogEvent($LocalDebugLevel+1, "DMMT Update Status Column being displayed");
		$aTemplateVariables['DisplayDMMTStatus'] = "visble";
		//-> Get the Current Status Number for the DMMT System
		$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DMMTOptionsTable'].' WHERE OptionName="DMMT_StatusNo"; ');
			if (!$Result) {
				If ($bDebug) { LogEvent(1, "Connection failed: " . $Settings['hDB'] -> connect_error); }
				die("Connection failed: " . $Settings['hDB'] -> connect_error . "<br />\r\n");
			}
		$aRecord = MySQLi_Fetch_Array($Result);
#		Print Print_R($aRecord)."<br />\r\n";
		$DMMT_StatusNo = $aRecord['Value'];
	} Else { //-> Changes style to hide the Duplicati backup status column
		LogEvent($LocalDebugLevel+1, "DMMT Update Status Column is being HIDDEN");
		$aTemplateVariables['DisplayDMMTStatus'] = "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 Visible LIKE "Y" ORDER BY '.$Settings['OrderNodesBy'].' ASC;'); //-> Read nodes in the currently selected group where visible is "Y".
			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 ]-----------
#					Print Print_R($aNodeRow)."<br />\n"."<br />\n"."<br />\n";
					If ($Settings['DisplayBackupStatus']) {
						$aNodeRow['%BackupStatusIcon%'] = CheckBackupExperation($aNodeRow['%NodeID%']);
					}
					If ($Settings['DisplayDMMTStatus']) {
						$aNodeRow['%BackupDMMTIcon%'] = CheckDMMTStatus($aNodeRow['%NodeID%']);
					}
#>#> ------[/ 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 Visible LIKE "Y" ORDER BY '.$Settings['OrderNodesBy'].' ASC;'); //-> All Nodes where "Visible" is "Y".
		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 ]-----------
#				Print Print_R($aNodeRow)."<br />\n";
				If ($Settings['DisplayBackupStatus']) {
					$aNodeRow['%BackupStatusIcon%'] = CheckBackupExperation($aNodeRow['%NodeID%']);
				}
				If ($Settings['DisplayDMMTStatus']) {
					If ($DMMT_StatusNo == $NodeRow['StatusNo']) {
						$aNodeRow['%DMMTStatusIcon%'] = Str_iReplace("%IconName%", "DMMTCurrent", $Settings['DMMTStatusIconHTML']);
					} Else {
						$aNodeRow['%DMMTStatusIcon%'] = Str_iReplace("%IconName%", "DMMTBehind", $Settings['DMMTStatusIconHTML']);
					}
				}
#> ------[/ 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 CheckBackupExperation($NodeID) {
	Global $Settings;

	$LocalDebugLevel = 3;

	$bExpired = False;
	$NodesFromDB = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_BackupNodesTable'].' WHERE NodeID LIKE "'.$NodeID.'" ');
		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 ($NodesFromDB->num_rows > 0) {
		While ($NodeRow = MySQLi_Fetch_Array($NodesFromDB)) {
			$aNodeRow = ConvertArrayToVariables($NodeRow);
			If ($Settings['ExpirationTime'] <= HowManyDays("@".$aNodeRow['%LastBackupDateUnix%'])) {
				LogEvent($LocalDebugLevel, 'Returning "Expired" for NodeID: '.$NodeID);
				Return Str_iReplace("%IconName%", "Expired", $Settings['BackupIconHTML']);
			}
			If ($aNodeRow['%ParsedResult%'] == "Failed") {
				LogEvent($LocalDebugLevel, 'Returning "Failed" for NodeID: '.$NodeID);
				Return Str_iReplace("%IconName%", $aNodeRow['%ParsedResult%'], $Settings['BackupIconHTML']);
			}
		}
		LogEvent($LocalDebugLevel, 'Returning "Success" for NodeID: '.$NodeID);
		Return Str_iReplace("%IconName%", "Success", $Settings['BackupIconHTML']);
	} Else {
			LogEvent($LocalDebugLevel, 'Returning "NoBackup" for NodeID: '.$NodeID);
			Return Str_iReplace("%IconName%", "NoBackup", $Settings['BackupIconHTML']);
#		LogEvent($LocalDebugLevel+1, "Grouping toggled off.  Building a Flat List.");
	}
	Return "";
}


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