<?php
	// no cache
	/*header('Pragma: no-cache');
	// HTTP/1.1
	header('Cache-Control: no-cache, must-revalidate');
	// date in the past
	header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
	// define XML content type
	header('Content-type: text/xml');
	// print XML header
	print '<?xml version="1.0"?>';
	// prepare demo progress value
	$progress = (mktime() % 50) * 2;*/
	
	session_start();
	ini_set('display_errors', 0);
	error_reporting(E_ALL & ~E_DEPRECATED);
	include_once("includes/config.php");
	include_once("includes/common_functions.php");
	$common = new General_Functions();
	
	$db_host = "192.168.168.5";
	$db_host = "10.10.5.118";
	$user = "yrgbs";
	$pass = "YRGbs123";
	
	$db_server = "localhost";
	$db_user = "yrgbs";
	$db_pass = "YRGbs123";
	$database = "yrgbs";
	$time = $time_limit = $endtime = $process = $last_bin_index = $f_name =  $directory = "";
	$mysql_home = "";
	
	$mysql_home = str_replace("\\", "/", $_SERVER['MYSQL_HOME']);
	$doc_root = $_SERVER['DOCUMENT_ROOT'];
	$doc_root = split("/", $doc_root);
	$doc_root = $doc_root[0];
	$mysql_home = substr($doc_root.$mysql_home, 0, -3)."data/";
	
	//$mysql_home = "C:/xampp/mysql/data/";
	$step = isset($_REQUEST['step']) ? $_REQUEST['step'] : "";
	
	switch($step)
	{
		case "0":
			$db_conn = connect_db($db_server, $db_user, $db_pass, $database);
			$process = "30%";
			
			if($db_conn != 0)
				echo "$process<br>Reading your transactions for replication untill $time. Dont close or Navigate away from this page.....<br />Preparing for Replicaiton with the Server.....<br>$time";
			else
				echo $db_conn;
		break;
		
		case "1":
			if(isset($_SESSION["time"]))
				$time = $_SESSION["time"];
			
			$log_process = true;
			$log_process = log_access($mysql_home);
			$old_process = $process;
			$process = "60%";
			
			if((int)$log_process)
				echo "$process<br>Transferring the data to Server ...... Please wait";
			else
				echo $log_process;
		break;
		
		case "2":
			if(isset($_SESSION["time"]))
			{
				$time = $_SESSION["time"];
				unset($_SESSION["time"]);
			}
			if(isset($_SESSION["last_bin_index"]))
			{
				$last_bin_index = $_SESSION["last_bin_index"];
				unset($_SESSION["last_bin_index"]);
			}
			if(isset($_SESSION["fname"]))
			{
				$fname = $_SESSION["fname"];
				unset($_SESSION["fname"]);
			}
			$data_trans = true;
			$data_trans = transfer_dat($db_host, $user, $pass);
			
			$old_process = $process;
			$process = "90%";
			
			if((int)$data_trans)
			{
				$old_process = $process;
				$process = "100%";
				$query = "INSERT INTO lastsync (location, lastindex, lasttime) VALUES ('".LCTN."', '$last_bin_index', '$time')";
				
				if($last_bin_index != "")
					$exec = mysql_query($query);
				else
					$exec = true;
				
				if($exec)
					echo $process."<br>Data Replicated Successfully to the Server.";
				else
					echo "Replication is not successful. please contact your administrator immediately. ".$exec;
			}
			else
				echo $data_trans;
		break;
		
		case "all":
			$db_conn = connect_db($db_server, $db_user, $db_pass, $database);
			$process = "30%";
			
			if($db_conn)
			{
				$log_process = true;
				$log_process = log_access($mysql_home);
				$old_process = $process;
				$process = "60%";
				
				if((int)$log_process)
				{
					$data_trans = true;
					$data_trans = transfer_dat($db_host, $user, $pass);
					$old_process = $process;
					$process = "90%";
					
					if((int)$data_trans)
					{
						$old_process = $process;
						$process = "100%";
						$query = "INSERT INTO lastsync (location, lastindex, lasttime) VALUES ('".LCTN."', '$last_bin_index', '$time')";
						
						if($last_bin_index != "")
							$exec = mysql_query($query);
					}
				}
			}
			if(isset($_SESSION["time"]))
				unset($_SESSION["time"]);
			
			if(isset($_SESSION["last_bin_index"]))
				unset($_SESSION["last_bin_index"]);
			
			if(isset($_SESSION["fname"]))
				unset($_SESSION["fname"]);
			
			echo '<script type="text/javascript">
				//alert("Hi");
				window.self.close();
				//self.close();
			</script>';
		break;
	}
	
	function connect_db($db_server, $db_user, $db_pass, $database)
	{
		global $time, $time_limit, $endtime, $process, $last_bin_index, $f_name;
		$link = mysql_connect($db_server, $db_user, $db_pass);
		if(!$link)
			return 'Unable to connect MYSQL. Check Server Connectivity / Configuration';
		else
		{
			$conn = mysql_select_db($database, $link);
			if(!$conn)
			{
				return $database." Database not available";
			}
			else
			{
				$result = mysql_query('SELECT CURRENT_TIMESTAMP');
				$row = mysql_fetch_row($result);
				$time = $row[0];
				$_SESSION["time"] = $time;
				return true;
			}
		}
	}
	
	function log_access($directory)
	{
		global $time, $time_limit, $endtime, $process, $last_bin_index, $f_name, $fname;
		$files = glob($directory."mysql-bin.*");
		$result = mysql_query('SELECT lastindex, lasttime FROM lastsync WHERE location = "'.LCTN.'" ORDER BY id DESC');
		$num_row = mysql_num_rows($result);
		$row = mysql_fetch_row($result);
		$file_list = "";
		
		foreach($files as $file)
		{
			$f_name = str_replace($directory, "", $file);
			$last_bin = str_replace("mysql-bin.", "", $f_name);
			$len = strlen($last_bin);
			
			if(($len == 6 && $num_row == 0) || ($len == 6 && $row[0] <= (int)$last_bin && $num_row != 0))
			{
				$file_list .= $file." ";
				$last_bin_index = $last_bin;
				$_SESSION["last_bin_index"] = $last_bin_index;
			}
		}
		
		if($file_list != "")
		{
			if($num_row == 0)
				$time_limit = '--stop-datetime="'.$time.'"';
			elseif($num_row > 0)
			{
				$result = mysql_query('SELECT lasttime, lastindex FROM lastsync WHERE location = "'.LCTN.'" ORDER BY id DESC');
				$num_row = mysql_num_rows($result);
				$row = mysql_fetch_row($result);
				
				$s_time = $row[0];
				$time_limit = '--start-datetime="'.$s_time.'" --stop-datetime="'.$time.'"';
			}
			
			$directory = str_replace("\\", "/", getcwd())."/SQL/";
			$f_name = str_replace(" ","_", $time);
			$f_name = str_replace(":","-", $f_name);
			//$f_name = $directory.$f_name.".sql";
			$f_name = $directory."rep-".$f_name.".sql";
			$fname = $f_name;
			$_SESSION["fname"] = $fname;
			$command = "mysqlbinlog $time_limit $file_list > $f_name";
			//echo $command."<br>";
			$op = shell_command($command);
			
			if((int)$op)
				return true;
			else
				return $op;
		}
		else
			return "No transactions available for Replication";
	}
	
	function transfer_dat($db_host, $user, $pass)
	{
		global $time, $time_limit, $endtime, $process, $last_bin_index, $f_name, $fname;
		$f_name = $fname;
		$command = "mysql --user=$user --password=$pass --host=$db_host < $f_name";
		$command = "mysql -f --user=$user --password=$pass --host=$db_host < $f_name";
		//echo $command."<br>";
		$op = shell_command($command);
		
		if((int)$op)
			return true;
		else
			return $op;
	}
	
	function shell_command($command)
	{
		global $time, $time_limit, $endtime, $process, $last_bin_index, $f_name;
		$f_name = str_replace(" ", "_", $time);
		$f_name = str_replace(":", "-", $f_name);
		$file = "Error/error-output-$f_name.txt";
		
		$descriptorspec = array(
		   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
		   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
		   2 => array("file", "Error/error-output-$f_name.txt", "a") // stderr is a file to write to
		);
		$cwd = NULL;
		$env = NULL;
		
		$output = proc_open($command, $descriptorspec, $pipes, $cwd, $env);
		if (is_resource($output)) {
			fwrite($pipes[0], '<?php $x = print_r($_ENV); ?>');
			fclose($pipes[0]);
			$err_log = stream_get_contents($pipes[1]);
			fclose($pipes[1]);
			$return_value = proc_close($output);
			$out_var = "Replication is not successful. please contact your administrator immediately.";
			if($return_value == 1)
				return $out_var."<br /><br />".file_get_contents($file);
			else
				return true;
		}
		else
			return true;
	}
?>