<?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'] = 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-07:55900";

	OpenDatabase();
	$Settings['NodeDisplayNameTemplate'] = GetNodeDisplayNameTemplate();
	RebuildFiles();
	
	$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 GetNodeDisplayNameTemplate() {
	Global $bDebug, $Settings;

	If (IsSet($Settings['NodeDisplayNameTemplate'])) {
		$sDisplayNameTemplate = $Settings['NodeDisplayNameTemplate'];
	} Else {
		$Result = $Settings['hDB'] -> Query('SELECT * FROM vnc_options WHERE OptionName="DisplayNameTemplate";');
			If(! $Result ) {	Die('(5) Could not get data: ' . mysql_error()."\r\n");	}
		$RowsReturned = $Result -> num_rows;
		If ($RowsReturned > 0) {
			$Result -> Data_Seek(0);
			$Row = $Result -> Fetch_Assoc();
			$sDisplayNameTemplate = $Row['Value'];
		} Else {
			$sDisplayNameTemplate = "%DomainName%.%ComputerName% - %ComputerDescription% (%NodeID%)"; //-> Default value to set because no option was found.
			If ($Settings['hDB'] -> Query("INSERT INTO vnc_options (OptionName, Value) VALUES ('NodeDisplayNameTemplate', '".$sDisplayNameTemplate."');") !== True) {
				Echo "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error . "\r\n";
			}
		}
	}
	
	Return $sDisplayNameTemplate;
}


Function GetNodeDisplayName($aComputerData) {
	Global $bDebug, $Settings;

	If (IsSet($Settings['NodeDisplayNameTemplate'])) {
		$sDisplayNameTemplate = $Settings['NodeDisplayNameTemplate'];
	} Else {
		$Result = $Settings['hDB'] -> Query('SELECT * FROM vnc_options WHERE OptionName="DisplayNameTemplate";');
			If(! $Result ) {	Die('(5) Could not get data: ' . mysql_error()."\r\n");	}
		$RowsReturned = $Result -> num_rows;
		If ($RowsReturned > 0) {
			$Result -> Data_Seek(0);
			$Row = $Result -> Fetch_Assoc();
			$sDisplayNameTemplate = $Row['Value'];
		} Else {
			$sDisplayNameTemplate = "%DomainName%.%ComputerName% - %ComputerDescription% (%NodeID%)"; //-> Default value to set because no option was found.
			If ($Settings['hDB'] -> Query("INSERT INTO vnc_options (OptionName, Value) VALUES ('NodeDisplayNameTemplate', '".$sDisplayNameTemplate."');") !== True) {
				Echo "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error . "\r\n";
			}
		}
	}
	
#	$NodeDisplayName = Str_iReplace("%NODEID%", $NodeID, $sDisplayNameTemplate);
	$aKeys = Array_Keys(ConvertArrayToVariables($aComputerData));
	$NodeDisplayName = Str_iReplace($aKeys, $aComputerData, $sDisplayNameTemplate);
		
#	Echo "Display Name: " . $NodeDisplayName . "\r\n";
#	Echo Print_R($aKeys)."\r\n";

	Return $NodeDisplayName;
}

#########################################
Function SaveLauncherFile($aComputerData) {
	Global $bDebug, $Settings, $NodeDisplayName;

	$NodeDisplayName = GetNodeDisplayName($aComputerData);

#	$hVNCFile = FOpen($Settings['PathToLauncherFiles']."/".$NodeDisplayName.".vnc", "w");
	$sVNCFile = $Settings['PathToLauncherFiles']."/".Str_Replace("/", "-", $NodeDisplayName).".vnc";
			
	If (! File_Exists(DirName($Settings['PathToLauncherFiles']))) {
		MkDir(DirName($Settings['PathToLauncherFiles']), 0776, True);
	}

	Echo "Searching For: ".$Settings['PathToLauncherFiles']."/*(".$aComputerData['NodeID'].")*<br />\n";
	ForEach (Glob($Settings['PathToLauncherFiles']."/*(".$aComputerData['NodeID'].")*") as $FileName) {
		Echo "Deleting $FileName"."<br />\n";
		UnLink($FileName);
	}

	If (! File_Exists($sVNCFile)) {
		Copy($Settings['PathToLauncherFiles']."/Default.vnc", $sVNCFile);
	}

	INI_Write($sVNCFile, "connection", "host", "ID");
	INI_Write($sVNCFile, "connection", "port", $aComputerData['NodeID']);
	If (IsSet($Settings['ViewerURL'])) {
		Print 'Writing: '.$NodeDisplayName.'.vnc'."<br />\r\n";
#		Print '   with: "'.$Settings['ViewerURL'].'"'."<br />\r\n";
		$aViewerURL = Explode(":", $Settings['ViewerURL']);
		INI_Write($sVNCFile, "connection", 'proxyhost', $aViewerURL[0]);
		INI_Write($sVNCFile, "connection", 'proxyport', $aViewerURL[1]);
	} Else {
		If (IsSet($aComputerData['ProxyHost'])) { INI_Write($sVNCFile, "connection", 'proxyhost', $aComputerData['ProxyHost']); }
		If (IsSet($aComputerData['ProxyPort'])) { INI_Write($sVNCFile, "connection", 'proxyport', $aComputerData['ProxyPost']); }
	}
}

#########################################
Function INI_Write($FileName, $Section, $Key, $Value) {
#	echo Shell_Exec("ls -hal ".$FileName)."\r\n";
#	echo Shell_Exec("cat ".$FileName)."\r\n";
	$aIni = Parse_Ini_File($FileName, True); //-> Read File and convert to array
	
	If (IsSet($aIni[$Section][$Key])) { $aIni[$Section][$Key] = $Value; } //-> Set Value if in file.

	$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");
		}
	}
	FClose($hFile);
}

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

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

	$sComputerList = "";
	$sRogueNodesList = "";
	$Groups = Array();

	$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)) {
			SaveLauncherFile($NodeRow);
		}
	}

	Return;
}

?>