<?php
# Check-In Module for Duplicati Backup System

/*
* Records are added automatically when the backup checks in.
* Records are based on the NodeID and BackupName.
* Group and ComputerName are optional arguments.
* Group Name and Computer Name are initially grabbed from the URL.
*/

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

# 002405 - REG-05
	$Settings['ExcludeNodes'] = "|002405|";
	$Settings['ExcludeComputers'] = "||";

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

#	http://support.desktopmasters.com/BackupCheckin/index.php?AuthToken=55645645223789711&Group=X&ComputerName=X&NodeID=000102

	GetValueFromURL('AuthToken', "", True); //-> Get Authentification Token from URL
		If ($Settings['AuthToken'] == "") {  //-> Make sure the AuthToken has a value.  If not kill script with fake password (Why?  For fun!)
			LogEvent(1, "Aborting: No AuthToken supplied in URL", False, False);
			die("(1) Error: No AuthToken supplied in URL<br />\r\nThe password is \"123123123123\"<br />\r\n");
		}
	
	GetValueFromURL('BackupID', '!'); //-> Get Backup ID (Unique Identifier for that session usually from the backup URL commandline)	
	GetValueFromURL('NodeID'); //-> Get NodeID from URL	
	If ($Settings['NodeID'] == "") {
		LogEvent(1, "Aborting: No NodeID supplied in URL", False, False);
		Die("(2) Error: No NodeID supplied in URL\r\n<br />");
	}
	GetValueFromURL('ComputerName'); //-> Get Computername from URL
	GetValueFromURL('Group', '!'); //-> Get Group from URL	
		
	If (StriStr($Settings['ExcludeNodes'] , "|".$Settings['NodeID']."|") !== False) {
		LogEvent(1, "Aborting: NodeID '".$Settings['NodeID']."' found in Exclude List", False, False);
		Die("Aborting: NodeID found in Exclude List\r\n<br />");
	}
	
	If (StriStr($Settings['ExcludeComputers'] , "|".$Settings['ComputerName']."|") !== False) {
		LogEvent(1, "Aborting: Computer Name '".$Settings['ComputerName']."' found in Exclude List", False, False);
		Die("Aborting: Computer Name found in Exclude List\r\n<br />");
	}



	$aPostData = ReadAndProcessPostData( $Settings['AuthToken'] );

	OpenDatabase();

	$Settings['GroupID'] = GetGroupID($Settings['Group']);

	SaveToDB();

	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 ReadAndProcessPostData( $AuthToken ) {
#> Reads the posted information and processes it.

	Global $Settings;
	$LocalDebugLevel = 1;
	LogEvent($LocalDebugLevel, "In ReadAndProcessPostData()");
	
	$aPostData = GetJSondata( $AuthToken );
#	$sSomething = $aPostData['Something'];

# $today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
	$Settings['BackupName'] = $aPostData['Extra']['backup-name'];
	
	If (IsSet($aPostData['Data']['EndTime'])) {
		$Settings['LastBackupDateUnix'] = ConvertToUnixTimeStamp($aPostData['Data']['EndTime']);
		$Settings['LastBackupDate'] = date("Y-m-d H:i:s", $Settings['LastBackupDateUnix']);
	} Else {
		$Settings['LastBackupDateUnix'] = "0";
		$Settings['LastBackupDate'] = "";
	}
	If (IsSet($aPostData['Data']['Duration'])) {
		$Settings['Duration'] = RoundUpTimer($aPostData['Data']['Duration']);
	} Else {
		$Settings['Duration'] = "";
	}
	If (IsSet($aPostData['Data']['Version'])) {
		$Settings['Version'] = $aPostData['Data']['Version'];
	} Else {
		$Settings['Version'] = "";
	}
	If (IsSet($aPostData['Data']['ParsedResult'])) {
		$Settings['ParsedResult'] = $aPostData['Data']['ParsedResult'];
	} Else {
		$Settings['ParsedResult'] = "Failed";
	}
	If (IsSet($aPostData['Data']['SizeOfExaminedFiles'])) {
		$Settings['SourceSize'] = Human_FileSize($aPostData['Data']['SizeOfExaminedFiles']);
	} Else {
		$Settings['SourceSize'] = "";
	}
	If (IsSet($aPostData['Data']['BackendStatistics']['KnownFileSize'])) {
		$Settings['BackupSize'] = Human_FileSize($aPostData['Data']['BackendStatistics']['KnownFileSize']);
	} Else {
		$Settings['BackupSize'] = "";
	}
	If (IsSet($aPostData['Data']['Message'])) {
		$Settings['Message'] = $aPostData['Data']['Message'];
	} Else {
		$Settings['Message'] = "";
	}
	
	If (IsSet($aPostData['LogLines'][0])) {
#		$ErrorMessage = SubStr($aPostData['LogLines'][0], ( StrPos($aPostData['LogLines'][0], "]:")+3 ), (StrPos($aPostData['LogLines'][0], "\n")-StrPos($aPostData['LogLines'][0], "]:")-3) );
		$Settings['ErrorMessage'] = StrTok($aPostData['LogLines'][0], "\n")."\n";
		$Settings['ErrorMessage'] .= Str_iReplace("\r", "", StrTok("\n"));
		$Settings['LogLines'] = $aPostData['LogLines'][0];
	} Else {
		$Settings['ErrorMessage'] = "";
		$Settings['LogLines'] = '';
	}

	LogEvent($LocalDebugLevel, "Data Collected....");
	LogEvent($LocalDebugLevel+1, "BackupID: ".$Settings['BackupID']);
	LogEvent($LocalDebugLevel+1, "NodeID: ".$Settings['NodeID']);
	LogEvent($LocalDebugLevel+1, "Computer Name: ".$Settings['ComputerName']);
	LogEvent($LocalDebugLevel+1, "Group: ".$Settings['Group']);
	LogEvent($LocalDebugLevel+1, "Backup Name: ".$Settings['BackupName']);
	LogEvent($LocalDebugLevel+1, "Result: ".$Settings['ParsedResult']);
	LogEvent($LocalDebugLevel+1, "Last Backup Unix-Date: ".$Settings['LastBackupDateUnix']);
	LogEvent($LocalDebugLevel+1, "Last Backup Date: ".$Settings['LastBackupDate']);
	LogEvent($LocalDebugLevel+1, "Duration: ".$Settings['Duration']);
	LogEvent($LocalDebugLevel+1, "Software Version: ".$Settings['Version']);
	LogEvent($LocalDebugLevel+1, "Source Size: ".$Settings['SourceSize']);
	LogEvent($LocalDebugLevel+1, "Backup Size: ".$Settings['BackupSize']);
#	LogEvent($LocalDebugLevel+1, ": ".$Settings['']);

	LogEvent($LocalDebugLevel+1, "Message: ".$Settings['Message']);
	LogEvent($LocalDebugLevel+1, 'Error: "'.$Settings['ErrorMessage'].'"');
	LogEvent($LocalDebugLevel+1, "First LogLine: ".$Settings['LogLines']);
#	LogEvent($LocalDebugLevel+1, "-------------------------------------------------------------------");
#	LogEvent($LocalDebugLevel+2, Print_R($aPostData, True));
	
	Return $aPostData;
}
#----------------------------------------------------------------------------------------------------------
Function SaveToDB() {
	Global $Settings;
	$LocalDebugLevel = 1;
	
	
	LogEvent($LocalDebugLevel, "In SaveToDB()");
	
	$hDB = $Settings['hDB'];

	If ( $Settings['NodeID'] != "" ) {
		$Result = $hDB->Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE NodeID="'.$Settings['NodeID'].'" AND BackupID="'.$Settings['BackupID'].'";'); // Get next generic NodeID number from the Database.
			If ( ! $Result ) {
				LogEvent(1, "(3) Error: " . $qSQL . "\r\n" . $hDB -> error . "\r\n");
			}
		If ( ($Result -> num_rows) == 0 ) {
			$Result = $hDB->Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE NodeID="'.$Settings['NodeID'].'" AND BackupName="'.$Settings['BackupName'].'";'); // Get next generic NodeID number from the Database.
		}
			If ( ! $Result ) {
				LogEvent(1, "(3) Error: " . $qSQL . "\r\n" . $hDB -> error . "\r\n");
			}
	} Else {
		$Result = $hDB->Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE NodeID="'.$Settings['NodeID'].'" AND BackupName="'.$Settings['BackupName'].'";'); // Get next generic NodeID number from the Database.
			If ( ! $Result ) {
				LogEvent(1, "(3) Error: " . $qSQL . "\r\n" . $hDB -> error . "\r\n");
			}
	}
	$RowsReturned = $Result -> num_rows;
	$Result -> Data_Seek(0);
	$Row = $Result -> Fetch_Assoc();
	If ($RowsReturned == 0) { //-> If there is no ID make a new one.  (First time run?)
		If ($Settings['ParsedResult'] == "Success") { //-> Backup Succeeded record info into Database
			LogEvent($LocalDebugLevel+1, "Creating New DB Entry for Successfull Backup");
			$qSQL = 'INSERT INTO '.$Settings['DB_NodesTable'].' (ComputerName, NodeGroup, NodeID, BackupID, BackupName, ParsedResult, LastBackupDate, LastBackupDateUnix, Duration, Version, SourceSize, BackupSize, Message, ErrorMessage, LogLines) VALUES ("'.$Settings['ComputerName'].'", "'.$Settings['Group'].'", "'.$Settings['NodeID'].'", "'.$Settings['BackupID'].'", "'.$Settings['BackupName'].'", "'.$Settings['ParsedResult'].'", "'.$Settings['LastBackupDate'].'", "'.$Settings['LastBackupDateUnix'].'", "'.$Settings['Duration'].'", "'.$Settings['Version'].'", "'.$Settings['SourceSize'].'", "'.$Settings['BackupSize'].'", "'.$Settings['Message'].'", "'.$Settings['ErrorMessage'].'", "'.$Settings['LogLines'].'");';
		} Else { //-> Record/Create record info into database for a failed database
			LogEvent($LocalDebugLevel+1, "Creating New DB Entry for Successfull Backup");
			$qSQL = 'INSERT INTO '.$Settings['DB_NodesTable'].' (ComputerName, NodeGroup, NodeID, BackupID, BackupName, ParsedResult, Version, SourceSize, BackupSize, Message, ErrorMessage, LogLines) VALUES ("'.$Settings['ComputerName'].'", "'.$Settings['Group'].'", "'.$Settings['NodeID'].'", "'.$Settings['BackupID'].'", "'.$Settings['BackupName'].'", "'.$Settings['ParsedResult'].'", "'.$Settings['Version'].'", "'.$Settings['SourceSize'].'", "'.$Settings['BackupSize'].'", "'.$Settings['Message'].'", "'.$Settings['ErrorMessage'].'", "'.$Settings['LogLines'].'");';
		}			
	} Else {
		LogEvent($LocalDebugLevel+1, "Updating DB Entry");
		If ($Settings['ParsedResult'] == "Success") { //-> Backup Succeeded record info into Database
			LogEvent($LocalDebugLevel+2, "Recording a Successful Backup");
			$qSQL = 'UPDATE '.$Settings['DB_NodesTable'].'  SET  ComputerName="'.$Settings['ComputerName'].'", NodeGroup="'.$Settings['Group'].'", BackupID="'.$Settings['BackupID'].'", BackupName="'.$Settings['BackupName'].'", ParsedResult="'.$Settings['ParsedResult'].'", LastBackupDate="'.$Settings['LastBackupDate'].'", LastBackupDateUnix="'.$Settings['LastBackupDateUnix'].'", Duration="'.$Settings['Duration'].'", Version="'.$Settings['Version'].'", SourceSize="'.$Settings['SourceSize'].'", BackupSize="'.$Settings['BackupSize'].'", Message="'.$Settings['Message'].'", ErrorMessage="'.$Settings['ErrorMessage'].'", LogLines="'.$Settings['LogLines'].'"  WHERE ID='.$Row['ID'].';';
		} Else { //-> Backup Failed update failure info
			LogEvent($LocalDebugLevel+2, "Recording a Failed Backup");
			$qSQL = 'UPDATE '.$Settings['DB_NodesTable'].'  SET  ComputerName="'.$Settings['ComputerName'].'", NodeGroup="'.$Settings['Group'].'", BackupID="'.$Settings['BackupID'].'", BackupName="'.$Settings['BackupName'].'", ParsedResult="'.$Settings['ParsedResult'].'", Message="'.$Settings['Message'].'", ErrorMessage="'.$Settings['ErrorMessage'].'", LogLines="'.$Settings['LogLines'].'"  WHERE ID='.$Row['ID'].';';
		}
	}
	If ($hDB -> Query($qSQL) !== True) {
		LogEvent(1, "(4) Error: " . $qSQL . "\r\n" . $hDB -> error . "\r\n");
	}
}
#----------------------------------------------------------------------------------------------------------
Function GetGroupID($Group) {
#> Fetches the Group ID from the Database

	Global $Settings;
	$CurrentLogLevel = 1;
	LogEvent($CurrentLogLevel, "In GetGroupID() Function");


	$hDB = $Settings['hDB'];
	
	$Result = $hDB -> Query('SELECT * FROM '.$Settings['DB_GroupsTable'].' WHERE name LIKE "'.$Group.'";');
		If(! $Result ) {
			LogEvent($CurrentLogLevel+1, "Error Could not get database data: ' . mysql_error()");
			LogEvent(1, 'Script Abort (3): Database Error', False, False);
	  	Die('(2) Could not get data: ' . mysql_error()."\r\n");
		}
	$RowsReturned = $Result -> num_rows;
		LogEvent($CurrentLogLevel+1, "Rows Returned from ".$Settings['DB_GroupsTable'].": ". $RowsReturned);
	
	$Result -> Data_Seek(0);
	$Row = $Result -> Fetch_Assoc();
	$ID = $Row['ID'];
	If ($ID > 0) { //-> Got Group ID, return it
		LogEvent($CurrentLogLevel+2, "Found and Returning Group ID: " . $ID);
		Return $ID;
	}

#> No existing group found.  Creating a new one in the DB.
	LogEvent($CurrentLogLevel+1, "No existing group found.  Creating a new one in the DB");
	$qSQL = "INSERT INTO ".$Settings['DB_GroupsTable']." (ID, name, displayname) VALUES (0, '".$Group.'", "'.$Group."');";
		If ($hDB -> Query($qSQL) === True) {
			LogEvent($CurrentLogLevel+2, "New record created successfully");
		} Else {
			LogEvent($CurrentLogLevel+2, "(5) Error: " . $qSQL);
			LogEvent($CurrentLogLevel+3, $hDB -> error);
			LogEvent(1, "Script Aborted:  Error creating database record.", False, False);
	  	Die('(3) Could not get data: '.$qSQL."<br />\r\n".$hDB -> error."<br />\r\n");
		}

	$Result = $hDB -> Query('SELECT * FROM '.$Settings['DB_GroupsTable'].' WHERE name LIKE "'.$Group.'";');
		If( ! $Result ) {
			LogEvent($CurrentLogLevel+2, "(6) Error: " . $qSQL);
			LogEvent($CurrentLogLevel+3, $hDB -> error);
			LogEvent(1, "(4) Script Aborted:  Error getting new Group ID from DB.", False, False);
	  	Die('(4) Error getting new Group ID from DB: '.error."<br />\r\n");
		}
	$Result -> Data_Seek(0);
	$Row = $Result -> Fetch_Assoc();
	$ID = $Row['ID'];
	If ($ID > 0) {
		LogEvent($CurrentLogLevel+2, "Created and Returning Group ID: " . $ID);
		Return $ID;
	}

	Return "X";
}


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


