<?php
#	* 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


*/

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

	$bDebug = False;

	$Settings['DB_Host'] = "MySQL";
	$Settings['DB_User'] = "dm_dm";
	$Settings['DB_Pssword'] = "stupidputty";
	$Settings['DB_Name'] = "DesktopMasters.com";

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

	$Settings['GroupResults'] = True; //> Toggle the grouping of the results.  False means no groups, just a flat list.
	$Settings['GroupResultsLimit'] = 1; //> 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-07:55900";

	OpenDatabase();
	DisplayPage();
#	ReplaceText();
	
	$Settings['hDB'] -> Close();

	Exit;


#====================================================================================
Function OpenDatabase() {
	Global $bDebug, $Settings;
	
	$hDB = new MySQLi($Settings["DB_Host"], $Settings['DB_User'], $Settings['DB_Pssword'], $Settings['DB_Name'], 3306);
	$Settings['hDB'] = $hDB;
		if ($Settings['hDB'] -> connect_error) {
			die("Connection failed: " . $Settings['hDB'] -> connect_error . "\r\n");
		}
		If ($bDebug) { Echo "Host Connect Info: " . $Settings['hDB'] -> host_info . "<br />\r\n"; }
}
#------------------------------------------------------------------------------------
Function ConvertArrayToVariables($aArray) {
	$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 GetHTML($FileName) {
#> Reads HTML template and returns the data

	$hFile = FOpen($FileName, "r") or die("Unable to open file! - ".$FileName);
	$HTML = FRead($hFile, FileSize($FileName));
	FClose($hFile);
	
	Return $HTML;
}
#------------------------------------------------------------------------------------
Function DisplayPage() {
	Global $bDebug, $Settings, $aTemplateVariables;

	$aTemplateVariableKeys = Array_Keys(ConvertArrayToVariables($aTemplateVariables));

	Echo '<!doctype html5>';
	Echo '<html lang="en">';
	Print GetHTML("Templates/header.html");

	$sBody = 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['GroupResults']) {
		$GroupsFromDB = $Settings['hDB'] -> Query('SELECT name,displayname FROM vnc_groups WHERE Visible LIKE "Y" ORDER BY name ASC;');
		While ($GroupRow = MySQLi_Fetch_Array($GroupsFromDB)) {
			$NodesFromDB = $Settings['hDB'] -> Query('SELECT * FROM vnc_nodes WHERE NodeGroup LIKE "'.$GroupRow['name'].'" AND Visible LIKE "Y" ORDER BY '.$Settings['OrderNodesBy'].' ASC;');
			If ($NodesFromDB->num_rows > 0) {
				$sNodeList = ""; #> Rest Node List
				While ($NodeRow = MySQLi_Fetch_Array($NodesFromDB)) {
					$sNodeList .= Str_iReplace(Array_Keys(ConvertArrayToVariables($NodeRow)), $NodeRow,  $sNodeListTemplate);
				}
				$sNodeGroup = Str_iReplace("%GroupName%", $GroupRow['name'], Str_iReplace("%GroupDisplayName%", $GroupRow['displayname'], $sNodeGroupTemplate));
				$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 {
					$sRogueNodesList .= $sNodeList;
					$iRogueComputerCount += 1;
				}
			}
		}
#		Print "Computer Count: ".$iRogueComputerCount."<br />\n";
		If ($iRogueComputerCount > 1) {
			$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 {
		$sNodeList = ""; #> Rest Node List
		$NodesFromDB = $Settings['hDB'] -> Query('SELECT * FROM vnc_nodes WHERE Visible LIKE "Y" ORDER BY '.$Settings['OrderNodesBy'].' ASC;');
		If ($NodesFromDB->num_rows > 0) {
			While ($NodeRow = MySQLi_Fetch_Array($NodesFromDB)) {
				$sNodeList .= Str_iReplace(Array_Keys(ConvertArrayToVariables($NodeRow)), $NodeRow,  $sNodeListTemplate);
#				$sNodeList .= Str_iReplace(Array_Keys(ConvertArrayToVariables($NodeRow)), $NodeRow,  $sNodeListTemplate);
			}
		}
		$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, $sBody); #> Insert Container Into Body
	$sBody = Str_iReplace($aTemplateVariableKeys, $aTemplateVariables, $sBody); #> Replaces all variables in the template

	Print $sBody;
	Print GetHTML("Templates/footer.html");

	Return;
}

Function ReplaceText() {
	Global $bDebug, $Settings, $aTemplateVariables;

		$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;
}
?>