<?php
/***********************************************************************************/
/* MassCRM客户关系管理系统							   */
/* ========================      						   */
/* 欢迎使用 MassCRM ,在您开始使用之前,请务必完整阅读本软件附带的全部说明档	   */
/***********************************************************************************/
/* Welcome to http://www.massboxes.com & http://masscrm.massboxes.com		   */
/***********************************************************************************/
	require_once "../includes/check_login.inc.php";
	//页面基本设置
	require_once '../includes/config.inc.php';
	//Smarty模板库
	require_once '../smarty/Smarty.class.php';
	$account=$HTTP_SESSION_VARS["account"];
	
	function checkRole($boxesDB,$module_name,$bu_name,$role_name){
	 	global $smart;
	 			
	 	$boxesDB->setTableName("boxes_user");
		$sql="where bu_name='".$bu_name."'";
		$boxesDB->setCondition($sql);
		$boxes_check=$boxesDB->selectResult();
		
		$bu_role=$boxes_check[0][bu_role];
		
		$boxesDB->setTableName("boxes_role");
		$sql="where br_name='".$bu_role."'";
		$boxesDB->setCondition($sql);
		$boxes_check=$boxesDB->selectResult();
	 	
		$br_value=$boxes_check[0][br_value];
	 	
	 	$boxesDB->setTableName("boxes_function");
		$sql="where (bf_module='".$module_name."' and bf_ename='".$role_name."')";
		$boxesDB->setCondition($sql);
		$boxes_check=$boxesDB->selectResult();
	 	
		$bf_auto_id=$boxes_check[0][bf_auto_id];
		
		if($bf_auto_id and substr($br_value,$bf_auto_id-1,1)!=1){
			echo"<script>alert(\"请求失败：请确定你有此操作的权限！\");self.close();</script>";
			$smart->display('error.tpl.htm');
			exit;
		}
	 }
	 
	$smart=new smarty;
	
	//路径+模板风格路径
	$smart->template_dir = '../templates/'.$TEMPLATE_STYLE.'/';
	$smart->compile_dir = '../smarty/templates_c/';
	$smart->config_dir = '../smarty/configs/';
	$smart->cache_dir = '../smarty/cache/';
	$smart->left_delimiter = '{/';
	$smart->right_delimiter = '/}';
	
	
	$action_file=$_SERVER['PHP_SELF'];
	$time=date("Y-m-d",time());
	
	function num_chunk($num){
		$num=strrev(chunk_split(strrev($num),3,","));
		$num=substr("$num",1);
		return $num;
	}
	
	if($totalsize){
		$totalsize_chunk=num_chunk($totalsize);
	}
	

	
	
	if($_POST[do_step_6] or $_REQUEST[do_back]){
		function query($sql){
		  if(!mysql_query($sql)) echo "<BR>语句：<XMP>$sql</XMP>错误信息： ".mysql_error()." </font>" ;
		}
		function create($table,$sql){
			query("DROP TABLE IF EXISTS `$table`;");
			query("CREATE TABLE `$table` ".$sql);
		}
		function insert($table,$data){
			query("INSERT INTO `$table` VALUES ($data);");
		}
		function deldir($dir) {
			$dh=opendir($dir);
			while ($file=readdir($dh)) {
				if($file!="." && $file!=".."){
					$fullpath=$dir."/".$file;
					if(!is_dir($fullpath)){
				      unlink($fullpath);
					}
					else {
				      deldir($fullpath);
					}
				}
			}
				
			closedir($dh);
				
			if(rmdir($dir)) {
				return true;
			}
			else {
				return false;
			}
		}
		
		//连接数据库
		include "../account/".$account.".boxes.inc.php";
		//包含adodb.inc.php
		require_once('../adodb/adodb.inc.php');
		//mysql数据库
		$conn = &ADONewConnection('mysql');

		//显示debug过程
		$conn->debug=true;
	
		//不显示debug过程
		$conn->debug=false;
		
		//连接数据库
		$conn->PConnect($MYSQL_HOSTNAME, $MYSQL_USERNAME, $MYSQL_PASSWORD, $DATABASE);
		
		require_once '../includes/BiaoCommon.class.php';
		
		$boxesDB=new BiaoCommon($conn); 
		
		//表名数组
		$d= dir("./backupfile/{$_POST[db_dbname]}/{$_POST[db_backup_time]}");

		while ($entry=$d->read())
		{
			if ($entry!="" and $entry!="." and $entry!="..") {
					$arr_fname=explode(".",$entry);
					$ext=$arr_fname[1];
					if (($ext=="table")){
						$table_array[]=$arr_fname[0];
					}
			}
		}
		$d->close();
		
		$c_num=$_REQUEST[c_num];
		if(!$c_num)$c_num=0;
		
		$table_name=$table_array[$c_num];
		$c_num++;
		if($table_name){
			include("./backupfile/{$_POST[db_dbname]}/{$_POST[db_backup_time]}/{$table_name}.table.php");	
		}
		
		$module_name="恢复数据第六步";
		
		if($c_num<count($table_array)){
			$state_message="正在恢复 ".$table_array[$c_num]." ……";
			$continue_action="<script language='Javascript'>myform.submit();</script>";
			$action_file.="?c_num=$c_num&&do_back=true";
			$finish_disable=" disabled";
		}	
		else{
			$state_message="完毕";
			
			//删除解压文件
			deldir("./backupfile/{$_REQUEST[db_dbname]}/{$_POST[db_backup_time]}/");		
		}
		
		$smart->assign(array("action_file"		=>	$action_file,
							 "module_name"		=>	$module_name,
							 "table_num"		=>	count($_POST[table]),
							 "db_dbname"		=>	$_POST[db_dbname],
							 "db_backup_time"	=>	$_POST[db_backup_time],
							 "username"			=>	$_POST[username],
							 "password"			=>	$_POST[password],
							 "state_message"	=>	$state_message,
							 "continue_action"	=>	$continue_action,
							 "finish_disable"	=>	$finish_disable));
		
		$smart->display('backup/b_step_6.tpl.htm');
	}
	elseif($_POST[do_step_5]){
		$db_dbname=$_POST[db_dbname];

		$d= dir("./backupfile/{$db_dbname}");
		while ($entry=$d->read())
		{
			if ($entry!="" and $entry!="." and $entry!="..") {
				$arr_fname=explode(".",$entry);
				if(!$arr_fname[1]){
					$db_backup_time_array[]=array(	"name"	=>	$entry,
													"value"	=>	$entry);
				}
			}
		}
		$d->close();
		
		$module_name="恢复数据第五步";
		$smart->assign(array("action_file"		=>	$action_file,
							 "module_name"		=>	$module_name,
							 "display_dbname"	=>	$_POST[display_dbname],
							 "db_dbname"		=>	$_POST[db_dbname],
							 "db_backup_time_array"		=>	$db_backup_time_array,
							 "username"			=>	$_POST[username],
							 "password"			=>	$_POST[password]));
		
		$smart->display('backup/b_step_5.tpl.htm');

	}
	elseif($_POST[do_step_4]){
		function unzip($tmpfile){
			
			$bgzExist = FALSE ;
			if ( function_exists("gzopen") )
			{
				$bgzExist = TRUE ;
			}
			
			$alldata = "" ;
			$pos = 0 ;
			
			$gzp = $bgzExist ? @gzopen($tmpfile, "rb") : @fopen($tmpfile, "rb") ;
			$szReaded = "has" ;
			
			while ( $szReaded )
			{
				$szReaded = $bgzExist ? @gzread($gzp, 2*1024*1024) : @fread($gzp, 2*1024*1024) ;
				$alldata .= $szReaded ;
			}
			$bgzExist ? @gzclose($gzp) : @fclose($gzp) ;
			
			$nFileCount = substr($alldata, $pos, 16) ;
			$pos += 16 ;
			
			$size = substr($alldata, $pos, 16) ;
			$pos += 16 ;
			
			$info = substr($alldata, $pos, $size-1) ;		// strip the last '\n'
			$pos += $size ;
			
			$info_array = explode("\n", $info) ;
			
			$c_file = 0 ;
			$c_dir = 0 ;
			
			foreach ($info_array as $str_row)
			{
				
				list($filename, $attr) = explode("|", $str_row);
				if ( substr($attr,0,6) == "[/dir]" )
				{
//					echo "End of dir $filename<br>";
					continue;
				}
				
				if ( substr($attr,0,5)=="[dir]" )
				{
					if ( @mkdir($filename, 0777) )
					{
//						echo "Make dir $filename<br>";
						if ( $_POST['chmod777'] == "chmod777" ) 
						{
							@chmod($filename, 0777);
						}
					}
					$c_dir++ ;
				}
				else
				{
					$fp = @fopen($filename, "wb") or exit("不能新建文件 $filename ,因为没有写权限，请修改权限");
					@fwrite($fp, substr($alldata, $pos, $attr) );
					$pos += $attr ;
					fclose($fp);
//					echo "Create file $filename<br>";
					if ( $_POST['chmod777'] == "chmod777" ) 
					{
						@chmod($filename, 0777);
					}
					$c_file++ ;
				}
//				echo"$str_row";
			}
			
			if ( $_POST['file_type'] == 'upload' )
			{
				if ( @unlink($tmpfile) ) echo "删除临时文件 $tmpfile...<br>" ;
			}
			$result_mes="上传接压完毕，共有文件 $c_file 个，文件夹 $c_dir 个！";
			return $result_mes;
//			echo "<h1>操作完毕! 共解出文件 $c_file 个， 文件夹 $c_dir 个，谢谢使用!</h1><p>" ;
		}

		//上传文件
		$uploaddir = './backupfile/';
		$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
		
		$textfname=strrchr($_FILES['userfile']['name'],".");
		if($textfname!=".gz"){
			echo"<script>alert(\"文件类型错误，文件类型必须为GZ类型\");</script>";
			echo"<META HTTP-EQUIV=Refresh CONTENT=0.2;URL=load_information.php?table_name=$table_name&&module_name=$module_name>";
			exit;
		}

		if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
//		   echo "文件有效，并且已经上传服务器！\n";
		} else {
			echo"<script>alert(\"文件上传失败！\");</script>";
			echo"<META HTTP-EQUIV=Refresh CONTENT=0.2;URL=load_information.php?table_name=$table_name&&module_name=$module_name>";
			exit;
		}
		
		//解压文件
		$upload_mes=unzip($uploadfile);
		
		if(!$upload_mes){
			$upload_mes="文件上传解压失败！";
		}

		$module_name="恢复数据第四步";
		$smart->assign(array("action_file"		=>	$action_file,
							 "module_name"		=>	$module_name,
							 "display_dbname"	=>	$_POST[display_dbname],
							 "db_dbname"		=>	$_POST[db_dbname],
							 "username"			=>	$_POST[username],
							 "password"			=>	$_POST[password],
							 "upload_mes"		=>	$upload_mes));
		
		$smart->display('backup/b_step_4.tpl.htm');

	}
	elseif($_POST[do_step_3]){
	
		include "../account/".$account.".boxes.inc.php";
		//包含adodb.inc.php
		require_once('../adodb/adodb.inc.php');
		//mysql数据库
		$conn = &ADONewConnection('mysql');

		//不显示debug过程
		$conn->debug=false;
		
		//连接数据库
		$conn->PConnect($MYSQL_HOSTNAME, $MYSQL_USERNAME, $MYSQL_PASSWORD, $DATABASE);
		//类
		require_once '../includes/BiaoCommon.class.php';
		
		$boxesDB=new BiaoCommon($conn); 
		
		//验证身份
		//设置表名
		$boxesDB->setTableName("boxes_user");
		
		//设置筛选的字段
		$boxesDB->setSelectField("*");
	
		//设置查询条件
		$boxesDB->setCondition("where bu_name='$_POST[username]'");
		
		
		
		$boxes_result=$boxesDB->selectResult();
		
		
		//只有一行结果的
		$row=$boxes_result[0];
				
		$p=$row[bu_password];
		$password=md5($_POST[password]);//用MD5加密密码
		if($password!=$p){										//比较密码失败
			echo"<script>";
			echo"alert(\"您输入的密码有误，请重新输入，输入时注意大小写！\");";		
			echo"</script>";
			echo"<META HTTP-EQUIV=Refresh CONTENT=0.2;URL=back.php>";
			exit;	
		}
		else{
			//检查权限
			checkRole($boxesDB,"〖恢复帐套〗",$_POST[username],"EXECUTE");
			
			$module_name="恢复数据第三步";
			$smart->assign(array("action_file"		=>	$action_file,
								 "module_name"		=>	$module_name,
								 "display_dbname"	=>	$ACCOUNT_NAME,
								 "db_dbname"		=>	$_POST[db_dbname],
								 "username"			=>	$_POST[username],
								 "password"			=>	$_POST[password]));
			
			$smart->display('backup/b_step_3.tpl.htm');
		}

	}
	elseif($_POST[do_step_2]){
		include "../account/".$account.".boxes.inc.php";
		//包含adodb.inc.php
		require_once('../adodb/adodb.inc.php');
		//mysql数据库
		$conn = &ADONewConnection('mysql');

		//不显示debug过程
		$conn->debug=false;
		
		//连接数据库
		$conn->PConnect($MYSQL_HOSTNAME, $MYSQL_USERNAME, $MYSQL_PASSWORD, $DATABASE);
		//类
		require_once '../includes/BiaoCommon.class.php';
		
		$boxesDB=new BiaoCommon($conn); 
		
		//读取用户列表
		//设置表名
		$boxesDB->setTableName("boxes_user");
		//设置筛选的字段
		$boxesDB->setSelectField("bu_name");
	
		$boxes_result=$boxesDB->selectResult();

		for($i=0;$i<count($boxes_result);$i++){
			$user_name_array[]=array("user_name" =>$boxes_result[$i][bu_name]);
		}
		
		$module_name="恢复数据第二步";
		$smart->assign(array("action_file"		=>	$action_file,
							 "module_name"		=>	$module_name,
							 "display_dbname"	=>	$ACCOUNT_NAME,
							 "db_dbname"		=>	$DATABASE,
							 "user_name_array"	=>	$user_name_array));
		
		$smart->display('backup/b_step_2.tpl.htm');
	}
	else{
/*		$NO=0;
		$d= dir("../account/");
		$num=0;
		while ($entry=$d->read())
		{
			  if ($entry!="" and $entry!="." and $entry!="..") {
			  		
					$arr_fname=explode(".",$entry);
					$ext=$arr_fname[1];
					
					if (($ext=="boxes")){
						
						$account_array[$num]=$arr_fname[0];
						$ACCOUNT_NAME="";
						include "../account/".$arr_fname[0].".boxes.inc.php";
						$account_array[$num]=array( "value"	=>$DATABASE,
													"name"	=>$ACCOUNT_NAME);
						//读入数据库帐号密码
						$db_host=$MYSQL_HOSTNAME; 
						$db_username=$MYSQL_USERNAME;
						$db_password=$MYSQL_PASSWORD;
						$num++;
					}
			}
		}
		$d->close();
*/
		include "../account/".$account.".boxes.inc.php";
		$account_array[0]=array( "value"	=>$DATABASE,
									"name"	=>$ACCOUNT_NAME);				
		$module_name="恢复数据第一步";
		$smart->assign(array("action_file"		=>	$action_file,
							 "module_name"		=>	$module_name,
							 "account_array"	=>	$account_array));
		
		$smart->display('backup/b_step_1.tpl.htm');
	}
	?>