<?php
#> Checkin to GetID Post file for uvnc installer.
#>   This will give the installer an ID and record or update the information about the workstation in the database.

#> ReWrite This

/*
	* 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 dmss_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.
*/

/*
  ToDo..
		*  Create remove record button using "ID" field.
		*  Create hide field using "ID" field.
		*  Make JSON import automatically import to MySQL fields if they exist.
*/

	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");

#> App Settings
	$Settings['AuthTokenKey'] = "12365548844523357";
	$Settings['GroupPadding'] = 4; // Padding of zeros's in front of the Group's Number.
	$Settings['PathToLauncherFiles'] = "uvnc";
	$Settings['ViewerURL'] = "dm-07:55900";

#> 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_OptionsTable'] = "dmss_options";
	$Settings['DB_Port'] = 3306;


	$aPostData = GetJSondata();

#	LogEvent(1, "PostData: ".Print_R($aPostData));

	
	If (StrToLower($aPostData['Action']) == "install") {
		Install($aPostData);
	}
	
	If (StrToLower($aPostData['Action']) == "update") {
		UpdateClient($aPostData);
	}
	

	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 UpdateClient($aPostData) {
	Global $Settings, $NodeDisplayName, $iNodeRecordID;

	LogEvent(1, "In UpdateClient()");

	OpenDatabase();
		
	$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE UniqueComputerID LIKE "'.$aPostData['UniqueComputerID'].'";');
	If(! $Result ) {
  	Die('(1) Could not get data: ' . $Settings['hDB']->error ."\r\n");
	}

	$RowsReturned = $Result -> num_rows;
	
	If ($RowsReturned > 0) {
		$Result -> Data_Seek(0);
		$Row = $Result -> Fetch_Assoc();
	
#		Print_R($Row)."\r\n";
		
		$aJSONData = new stdClass();
		$aJSONData->Visible = $Row['Visible'];
		$aJSONData->NodeID = $Row['NodeID'];
		$aJSONData->Location = $Row['Location'];
		$aJSONData->ComputerType = $Row['ComputerType'];
		$aJSONData->DisplayName = $Row['DisplayName'];

		$sJSON = JSON_Encode($aJSONData);

		Print "JSON:".$sJSON;
	}
	
	CloseDatabase();
}
#----------------------------------------------------------------------------------------------------------
Function Install($aPostData) {
	Global $Settings, $NodeDisplayName, $iNodeRecordID;

	LogEvent(1, "In Install()");

		$Settings['Group'] = $aPostData['DomainName'];
		$Settings['NodeID'] = $aPostData['NodeID'];
			If ($Settings['NodeID'] == 0) {
				$Settings['NodeID'] = "";
				LogEvent(2, 'NodeID supplied by POST was "0" Changing to ""');
			} Else {
				LogEvent(2, 'NodeID supplied by POST: "'.$Settings['NodeID'].'"');
			}

	#	Var_Dump($decoded);
	#	Print_R($aPostData);

		LogEvent(2, "ComputerName: ".$aPostData['ComputerName']);
		LogEvent(2, "Group: ".$Settings['Group']);
		LogEvent(2, "UniqueComputerID: ".$aPostData['UniqueComputerID']);

	#------------------------------------------------------------------------------------
	# Main Code
	# Exclude: UniqueComputerID|COMPUTERNAME|DOMAINNAME|UniqueComputerID|NODEID|COMPUTERDESCRIPTION|ProxyHost|ProxyPort

		OpenDatabase();

		$GroupID = GetGroupID($Settings['Group']);
			LogEvent(2, "Found GroupID=".$GroupID);
		$Settings['NodeID'] = RecordNodeID($aPostData, $GroupID);
		SaveLauncherFile($aPostData);

		CloseDatabase();

	//-> Give NodeID for the client connection (The Necessary Output) <----------
		Echo "The NodeID is ".$Settings['NodeID'];
	#Do not change to a logentry ^^^^^
}
#----------------------------------------------------------------------------------------------------------
Function RecordNodeID($aPostData, $GroupID) {
	Global $Settings, $NodeDisplayName, $iNodeRecordID;

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

#> Read Fields availabe to record to
#	$FieldsList = $Settings['hDB']->Query('SHOW COLUMNS FROM '.$Settings['DB_NodesTable'].';');
#		If(! $FieldsList ) { Die('(1) Could not get data: ' . $Settings['hDB']->error ."\r\n");	}
#	While ($FieldListRow = MySQLi_Fetch_Array($FieldsList)) {
#		$NodesTableFields[] = $FieldListRow['Field'];
#		LogEvent(1, "Field: ".$FieldListRow['Field']);
#	}

	$UniqueComputerID = $aPostData['UniqueComputerID'];
	$ComputerName = $aPostData['ComputerName'];
	$NodeNumber = "";
	$qSQL = "";
		
// Build NodeID
	If (Trim($Settings['NodeID']) == "") { //Checks to see if a NodeID was submitted.
		LogEvent($LocalDebugLevel+1, "Submitted NodeID is empty.  Trying to build a new one");
		If (($aPostData['DetectNodeNumber']) AND (StrPos($ComputerName, "-") !== False)) { // If the Detect node number switch is turned on and computer name has a hyphen it will read the number hafter the hyphen so "NODE-02" would return "02".
			LogEvent($LocalDebugLevel+1, "NodeID is empty and computer name has a hyphen.  Building a new one...");
			$aComputerName = Explode("-", $ComputerName);
			If (Is_Numeric($aComputerName[Count($aComputerName)-1])) {
				$NodeNumber = $aComputerName[Count($aComputerName)-1];
				$Settings['NodeID'] =  Str_Pad($GroupID, $Settings['GroupPadding'], "0", STR_PAD_LEFT).$NodeNumber;
				LogEvent($LocalDebugLevel+2, "Built NodeID: ".$Settings['NodeID']);
			}
		} Else { // Get Generic NodeID Number
			$Result = $Settings['hDB']->Query('SELECT * FROM '.$Settings['DB_OptionsTable'].'  WHERE OptionName="NextGenericNodeID";'); // Get next generic NodeID number from the Database.
			$RowsReturned = $Result -> num_rows;
			LogEvent($LocalDebugLevel+1, "Rows Returned from ".$Settings['DB_OptionsTable'].": ". $RowsReturned);
			$Result -> Data_Seek(0);
			$Row = $Result -> Fetch_Assoc();
			If ($RowsReturned == 0) { // If there is no id 1 make a new one.  (First time run?)
				LogEvent($LocalDebugLevel+2, "No Generic NodeID number found in the database.  Creating a new line");
				$Settings['NodeID'] = 999999999;
				$qSQL = "INSERT INTO ".$Settings['DB_OptionsTable']." (OptionName, Value) VALUES ('NextGenericNodeID', '". ($Settings['NodeID'] - 1) ."');"; // Create new/first record with next node ID.
			} Else {
				$Settings['NodeID'] = $Row['Value'];
				LogEvent($LocalDebugLevel+2, "Found Generic Node ID '".$Settings['NodeID']."' in the database..");
				$qSQL = "UPDATE ".$Settings['DB_OptionsTable']." SET Value=". ($Settings['NodeID'] - 1) ." WHERE ID=".$Row['ID'].";"; // Create new/first record with next node ID.
			}
			If ($Settings['hDB'] -> Query($qSQL) !== True) {
				LogEvent(1, "Error: " . $qSQL . "\r\n" . $Settings['hDB']->error, False, False);
				Echo "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error . "\r\n";
			}
		}
	} Else {
		LogEvent($LocalDebugLevel+1,   "'".$Settings['NodeID']."' Was previously submitted.  Using this instead of creating one.");
	}

	$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE UniqueComputerID LIKE "'.$UniqueComputerID.'";');
	If(! $Result ) {
  	Die('(1) Could not get data: ' . $Settings['hDB']->error ."\r\n");
	}

	$NodeDisplayName = GetNodeDisplayName($aPostData);
		
	$Result -> Data_Seek(0);
	$Row = $Result -> Fetch_Assoc();

// Compare to existing records or make a new one.
	If ($Row['UniqueComputerID'] == "") {
		LogEvent($LocalDebugLevel+1,  "No UniqueComputerID in records found");
 		If ($Settings['NodeID'] != "")	{
			LogEvent($LocalDebugLevel+1,  "NodeID has a value to work with");
			LogEvent($LocalDebugLevel+2,  'Searching for records with: "'.$Settings['NodeID'].'"'."");
			$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE NodeID="'.$Settings['NodeID'].'";');
				If(! $Result ) {
	  			Die('(2) Could not get data: ' . $Settings['hDB']->error ."\r\n");
				}
			$Result -> Data_Seek(0);
			$Row = $Result -> Fetch_Assoc();
			If ($Row['NodeID'] <> $Settings['NodeID']) {
				LogEvent($LocalDebugLevel+1,  "No NodeID Value Found");
				$qSQL = "INSERT INTO ".$Settings['DB_NodesTable']." (ID, NodeID, ComputerName, Location, ComputerType, DisplayName, NodeGroup, DomainName, AppVersion UniqueComputerID) VALUES (0, '".$Settings['NodeID']."', '".$aPostData['ComputerName']."', '".$aPostData['ComputerLocation']."', '".$aPostData['ComputerType']."', '".Str_Replace("'", "\\'", $aPostData['ComputerDescription'])."', '".$aPostData['DomainName']."', '".$aPostData['DomainName']."', '".$aPostData['AppVersion']."', '".$aPostData['UniqueComputerID']."');";
			} Else {
				LogEvent($LocalDebugLevel+1,  "Found a matching NodeID Value: ".$Row['NodeID']."");
				$qSQL = "UPDATE ".$Settings['DB_NodesTable']." SET NodeID='".$Settings['NodeID']."', ComputerName='".$aPostData['ComputerName']."', Location='".$aPostData['ComputerLocation']."', ComputerType='".$aPostData['ComputerType']."', DisplayName='".Str_Replace("'", "\\'", $aPostData['ComputerDescription'])."', NodeGroup='".$aPostData['DomainName']."', DomainName='".$aPostData['DomainName']."' AppVersion='".$aPostData['AppVersion']."', UniqueComputerID='".$aPostData['UniqueComputerID']."' WHERE ID=".$Row['ID'].";";
			}
		} Else {
			LogEvent($LocalDebugLevel+1,  "Submitted NodeID is empty.  Adding new record");
			$qSQL = "INSERT INTO ".$Settings['DB_NodesTable']." (ID, NodeID, ComputerName, Location, ComputerType, DisplayName, NodeGroup, DomainName, AppVersion, UniqueComputerID) VALUES (0, '".$Settings['NodeID']."', '".Str_Replace("'", "\\'", $aPostData['ComputerDescription'])."', '".$aPostData['ComputerName']."', '".$aPostData['DomainName']."', '".$aPostData['AppVersion']."', '".$aPostData['UniqueComputerID']."');";
		}
	} Else {
		LogEvent($LocalDebugLevel+1,  "UniqueComputerID matches database.  Updating Record");
		$qSQL = "UPDATE ".$Settings['DB_NodesTable']." SET NodeID='".$Settings['NodeID']."', ComputerName='".$aPostData['ComputerName']."', Location='".$aPostData['ComputerLocation']."', ComputerType='".$aPostData['ComputerType']."', DisplayName='".Str_Replace("'", "\\'", $aPostData['ComputerDescription'])."', NodeGroup='".$aPostData['DomainName']."', DomainName='".$aPostData['DomainName']."', AppVersion='".$aPostData['AppVersion']."', UniqueComputerID='".$aPostData['UniqueComputerID']."' WHERE ID=".$Row['ID'].";";
	}

	If ($Settings['hDB'] -> Query($qSQL) === True) {
		LogEvent($LocalDebugLevel+1,  "New record created/updated successfully");
		Return $Settings['NodeID'];
	} Else {
		LogEvent(1, "Error: " . $qSQL . "\r\n" . $Settings['hDB']->error, False, False);
		Echo "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error . "\r\n";
	}
}
#----------------------------------------------------------------------------------------------------------
Function GetGroupID($Group) {
	Global $Settings;

	$LocalDebugLevel = 1;
	LogEvent($LocalDebugLevel, "In GetGroupID() Function...");
		
	$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_GroupsTable'].' WHERE name LIKE "'.$Group.'";');
		If(! $Result ) {
	  	Die('(3) Could not get data: ' . $Settings['hDB']->error ."\r\n");
		}
	$RowsReturned = $Result -> num_rows;
	LogEvent($LocalDebugLevel+1, "Rows Returned from ".$Settings['DB_GroupsTable'].": ". $RowsReturned);
	$Result -> Data_Seek(0);
	$Row = $Result -> Fetch_Assoc();
	$ID = $Row['ID'];
	If ($ID > 0) {
		Return $ID;
	}
		
	$qSQL = "INSERT INTO ".$Settings['DB_GroupsTable']." (ID, name, displayname) VALUES (0, '".$Group."', '".$Group."');";
	If ($Settings['hDB'] -> Query($qSQL) === True) {
#		LogEvent($LocalDebugLevel+1, "New record created successfully);
	} Else {
		LogEvent(1, "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error, False, False);
		Echo "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error . "\r\n";
	}

	$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_GroupsTable'].' WHERE name LIKE "'.$Group.'";');
		If(! $Result ) {
	  	Die('(4) Could not get data: ' . $Settings['hDB']->error ."\r\n");
		}
	$Result -> Data_Seek(0);
	$Row = $Result -> Fetch_Assoc();
	$ID = $Row['ID'];
	If ($ID > 0) {
		Return $ID;
	}

			
	Return "X";
#	while($row = mysql_fetch_array($Results, MYSQL_ASSOC)) {			
#		Print_R($Row);
#		echo "EMP ID :{$row['emp_id']}  <br> ".			         "EMP NAME : {$row['emp_name']} <br> ".			         "EMP SALARY : {$row['emp_salary']} <br> ".			         "--------------------------------<br>";
#	}
}
#----------------------------------------------------------------------------------------------------------
Function GetNodeDisplayName($aPostData) {
	Global $Settings;

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

	If (IsSet($aPostData['DisplayNameTemplate'])) {
		$sDisplayNameTemplate = $aPostData['DisplayNameTemplate'];
	} Else {
		$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_OptionsTable'].' WHERE OptionName="DisplayNameTemplate";');
			If(! $Result ) {	Die('(5) Could not get data: ' . $Settings['hDB']->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 ".$Settings['DB_OptionsTable']." (OptionName, Value) VALUES ('DisplayNameTemplate', '".$sDisplayNameTemplate."');") !== True) {
				LogEvent(1, "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error, False, False);
				Echo "Error: " . $qSQL . "\r\n" . $Settings['hDB'] -> error . "\r\n";
			}
		}
	}
	
	$NodeDisplayName = Str_iReplace("%NODEID%", $Settings['NodeID'], $sDisplayNameTemplate);
	$aKeys = Array_Keys(ConvertArrayToVariables($aPostData));
	$NodeDisplayName = Str_iReplace($aKeys, $aPostData, $NodeDisplayName);
		
	LogEvent($LocalDebugLevel+1, "Display Name: " . $NodeDisplayName);
#	Echo Print_R($aKeys)."\r\n";

	Return $NodeDisplayName;
}
#----------------------------------------------------------------------------------------------------------
Function SaveLauncherFile($aPostData) {
	Global $Settings, $NodeDisplayName;

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


#	$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);
	}

	LogEvent($LocalDebugLevel+1, "Deleteing ".$Settings['PathToLauncherFiles']."/*(".$Settings['NodeID'].")*");
	ForEach (Glob($Settings['PathToLauncherFiles']."/*(".$Settings['NodeID'].")*") as $FileName) {
		LogEvent($LocalDebugLevel+2, "Deleting: ".$FileName);
		UnLink($FileName);
	}

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

	INI_Write($sVNCFile, "connection", "host", "ID");
	INI_Write($sVNCFile, "connection", "port", $Settings['NodeID']);
	If (IsSet($Settings['ViewerURL'])) {
		LogEvent($LocalDebugLevel+1, 'Writing Viewer Config Files with: "'.$Settings['ViewerURL'].'"');
		$aViewerURL = Explode(":", $Settings['ViewerURL']);
		INI_Write($sVNCFile, "connection", 'proxyhost', $aViewerURL[0]);
		INI_Write($sVNCFile, "connection", 'proxyport', $aViewerURL[1]);
	} Else {
		If (IsSet($aPostData['ProxyHost'])) { INI_Write($sVNCFile, "connection", 'proxyhost', $aPostData['ProxyHost']); }
		If (IsSet($aPostData['ProxyPort'])) { INI_Write($sVNCFile, "connection", 'proxyport', $aPostData['ProxyPost']); }
	}
}
#----------------------------------------------------------------------------------------------------------
Function SavePostDataExtraInfo($aPostData) {
	
	$LocalDebugLevel = 1;
	LogEvent($LocalDebugLevel, "In SavePostDataExtraInfo() Function...");

	$aKeys = Array_Keys($aPostData);

	For ($iRow = 0; $iRow < Count($aPostData); $iRow++) {
		$qSQL = "";
		$qSQL = $qSQL . "";
		$aNewArray["%".$aKeys[$iRow]."%"] = $aArray[$aKeys[$iRow]];
	}
#	Print_R($aArray);
#	Print_R($aNewArray);
	Return $aNewArray;
}



#==========================================================================================================
#INSERT Competitors (cName) SELECT DISTINCT Name FROM CompResults cr WHERE NOT EXISTS (SELECT * FROM Competitors c WHERE cr.Name = c.cName)
#MERGE INTO Competitors AS Target USING (SELECT DISTINCT Name FROM CompResults) AS Source ON Target.Name = Source.Name WHEN NOT MATCHED THEN INSERT (Name) VALUES (Source.Name);
#$qSQL = "insert into ".$Settings['DB_NodesTable']."(NodeID) select "'.$Settings['NodeID'].'" from ".$Settings['DB_NodesTable']." where not exists (select * from TABLE_TESTING where R_COMPONENT_ID='1942' and oprid ='Test');
#$qSQL = "INSERT INTO ".$Settings['DB_NodesTable']." (ID, NodeID, DisplayName, ComputerName, NodeGroup, DomainName, UniqueComputerID) VALUES (0, '".$Settings['NodeID']."', '".Str_Replace("'", "\\'", $NodeDisplayName)."', '".$aPostData['ComputerName']."', '".$aPostData['DomainName']."', '".$aPostData['DomainName']."', '".$aPostData['UniqueComputerID']."');";
?>