<?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[clear]){
		$delete_table_array[]=array(	"table_name"=>"boxes_stock_indent",
										"id_name"	=>"si_id");
		$delete_table_array[]=array(	"table_name"=>"boxes_stock_receive",
										"id_name"	=>"sr_id");	
		$delete_table_array[]=array(	"table_name"=>"boxes_stock_money",
										"id_name"	=>"fms_id");
		$delete_table_array[]=array(	"table_name"=>"boxes_stock_sendback",
										"id_name"	=>"ssb_id");																							
		$delete_table_array[]=array(	"table_name"=>"boxes_vendition_indent",
										"id_name"	=>"vi_id");	
		$delete_table_array[]=array(	"table_name"=>"boxes_vendition_send",
										"id_name"	=>"vs_id");																
		$delete_table_array[]=array(	"table_name"=>"boxes_vendition_money",
										"id_name"	=>"vm_id");	
		$delete_table_array[]=array(	"table_name"=>"boxes_vendition_sendback",
										"id_name"	=>"vsb_id");
		$delete_table_array[]=array(	"table_name"=>"boxes_account_payable",
										"id_name"	=>"bap_auto_id");	
		$delete_table_array[]=array(	"table_name"=>"boxes_account_receivable",
										"id_name"	=>"bar_auto_id");																																
		//连接数据库
		include "../account/boxes_".$_POST[db_dbname].".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); 
		
		for($i=0;$i<count($delete_table_array);$i++){
			$boxesDB->setTableName($delete_table_array[$i][table_name]);
			$sql="order by ".$delete_table_array[$i][id_name]." desc";

			$boxesDB->setCondition($sql);
			
			$boxes_result=$boxesDB->selectResult();
			$temp_row=$boxes_result[0];

			$sql="where ".$delete_table_array[$i][id_name]." !='".$temp_row[$delete_table_array[$i][id_name]]."'";
			$boxesDB->setCondition($sql);
			$boxes_result=$boxesDB->deleteRow();
		}
		echo"<script>alert(\"业务单据已经清空完毕，按确定关闭！\");self.close();</script>";
		exit;
		
	}
	elseif($_POST[do_step_5] or $_REQUEST[do_backup]){
		
		//备份
		global $dumpstring;
		global $c_num;
		
		//连接数据库
		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); 
		
		$dir="./backupfile/".$_POST[db_dbname]."/".$time;
		
		if(!is_dir("$dir"))	
			@mkdir("$dir",0777);
		
		function escape_string($str){
			$str=mysql_escape_string($str);
			$str=str_replace('\\\'','\'\'',$str);
			$str=str_replace("\\\\","\\\\\\\\",$str);
			$str=str_replace('$','\$',$str);
			return $str;
		}
		function sqldumptable($table_name,$dir) {
			global $boxesDB;
			$dumpstring = "create(\"$table_name\",\"";
			$dumpstring .= "(";
			$firstfield=1;
			
			$boxesDB->setTableName($table_name);
			$fields=$boxesDB->showFields();
			for($i=0;$i<count($fields);$i++){
				$field =$fields[$i];
				if (!$firstfield) {
					$dumpstring .= ",";
				}
				else {
					$firstfield=0;
				}
				$dumpstring .= " $field[Field] $field[Type]"; 
				if (!empty($field["Default"])) {
					$dumpstring .= " DEFAULT '$field[Default]'";
				}
				if ($field['Null'] != "YES") {
					$dumpstring .= " NOT NULL";
				}
				if ($field['Extra'] != "") {
					$dumpstring .= " $field[Extra]";
				}
			}
			//mysql_free_result($fields);
			
			$boxesDB->setTableName($table_name);
			$keys=$boxesDB->showKeys();
			for($i=0;$i<count($keys);$i++){
				$key = $keys[$i];
				$kname=$key['Key_name'];
				if ($kname != "PRIMARY" and $key['Non_unique'] == 0) {
					$kname="UNIQUE|$kname";
				}
				if(!is_array($index[$kname])) {
					$index[$kname] = array();
				}
				$index[$kname][] = $key['Column_name'];
			}
//			mysql_free_result($keys);
				
			while(list($kname, $columns) = @each($index)){
				$dumpstring .= ",";
				$colnames=implode($columns,",");
				if($kname == "PRIMARY"){
					$dumpstring .= " PRIMARY KEY ($colnames)";
				}
				else {
					if (substr($kname,0,6) == "UNIQUE") {
						$kname=substr($kname,7); 
					}
					$dumpstring .= " KEY $kname ($colnames)";
				}
			}
			$dumpstring .= ") ";
			
			$statuses=$boxesDB->showTable();
			for($i=0;$i<count($statuses);$i++){
				$status=$statuses[$i];
				if($status[Name]==$table_name){
					$dumpstring .=" Type=$status[Type] COMMENT='$status[Comment]';\");\n\n";
//					mysql_free_result($statuses);
					break;
				}
				else
				continue;
			}
			
			$boxesDB->setTableName($table_name);
			$rows =$boxesDB->selectResult();
			for($j=0;$j<count($rows);$j++){
				$row=$rows[$j];
				$dumpstring .= "insert(\"$table_name\",\"";
				$firstfield=1;
				for ($i=0;$i<count($fields);$i++) {
					if($part) $HTTP_POST_VARS[fin]+=strlen($row[$i]); //这个方法计算完成量不是很准确
					if (!$firstfield) {
						$dumpstring.=",";
					}
					else {
						$firstfield=0;
					}
					
					if (!isset($row[$i])) {
						$dumpstring .= "NULL";
					}
					else {
						$dumpstring .= "'".escape_string($row[$i])."'";
					}
				}
				$dumpstring .= "\");\n\n";
			}
//			mysql_free_result($rows);
			$file="$dir/{$table_name}.table.php";
			$fp=fopen($file,"w");
			flock($fp,2);
			fwrite($fp,"<?\n");
			fwrite($fp,$dumpstring);
			fwrite($fp,"?>");
			fclose($fp);
		}
		$c_num=$_REQUEST[c_num];
		if(!$c_num)$c_num=0;
		
		$table=$_POST[table];
		$table_name=$table[$c_num];
		$c_num++;
		if($table_name)
			sqldumptable($table_name,$dir);

		//隐藏字段
		while(list($key,$val)=each($HTTP_POST_VARS)){
			$HTTP_POST_VARS[$key]=$val;
			$$key=$val;
			if(is_array($HTTP_POST_VARS[$key])){
				while(list($key2,$val2)=each($HTTP_POST_VARS[$key])){
					$hidden_field.="<input name='{$key}[]' value='$val2' type='hidden'>\n";
				}
			}
		}
		reset($HTTP_POST_VARS);
		
		$module_name="备份数据第五步";
		
		if($c_num<$_POST[table_num]){
			$state_message="正在备份 ".$table[$c_num]." ……";
			$continue_action="<script language='Javascript'>myform.submit();</script>";
			$action_file.="?c_num=$c_num&&do_backup=true";
			$finish_disable=" disabled";
			$dl_disable=" disabled";
			$clear_disable=" disabled";
		}	
		else{
			$state_message="备份完毕，点击“下载备份数据包”下载数据保存到本地硬盘";
			$clear_disable=" disabled";
//			require"./phpzip.inc.php";
//			$z = new PHPZip(); 
//			$z -> Zip("./backupfile/{$_POST[db_dbname]}/{$time}/", "./backupfile/{$_POST[db_dbname]}/{$_POST[db_dbname]}_{$time}.zip"); //添加指定目录 
			//删除文件夹
			
		}
		
		$smart->assign(array("action_file"		=>	$action_file,
							 "module_name"		=>	$module_name,
							 "table_num"		=>	count($_POST[table]),
							 "db_dbname"		=>	$_POST[db_dbname],
							 "username"			=>	$_POST[username],
							 "password"			=>	$_POST[password],
							 "state_message"	=>	$state_message,
							 "continue_action"	=>	$continue_action,
							 "hidden_field"		=>	$hidden_field,
							 "finish_disable"	=>	$finish_disable,
							 "dl_disable"		=>	$dl_disable,
							 "clear_disable"	=>	$clear_disable));
		
		$smart->display('backup/step_5.tpl.htm');
	}
	elseif($_POST[do_step_4]){
		
		//隐藏字段
		while(list($key,$val)=each($HTTP_POST_VARS)){
			$HTTP_POST_VARS[$key]=$val;
			$$key=$val;
			if(is_array($HTTP_POST_VARS[$key])){
				while(list($key2,$val2)=each($HTTP_POST_VARS[$key])){
					$hidden_field.="<input name='{$key}[]' value='$val2' type='hidden'>\n";
				}
			}
		}
		reset($HTTP_POST_VARS);
		
		//目录
		$dir="./backupfile/".$_POST[db_dbname];
		
		if(!is_dir("./backupfile"))	
			@mkdir("./backupfile",0777);
		if(!is_dir("$dir") and !@mkdir("$dir",0777)){
			echo "<script>alert(\"目录'$dir'不存在且不能自动创建！请检查目录权限（权限为 777 方可写文件）\");</script>";
		}
		else{
			
			$module_name="备份数据第四步";
			$smart->assign(array("action_file"		=>	$action_file,
								 "module_name"		=>	$module_name,
								 "table_num"		=>	count($_POST[table]),
								 "db_dbname"		=>	$_POST[db_dbname],
								 "username"			=>	$_POST[username],
								 "password"			=>	$_POST[password],
								 "hidden_field"		=>	$hidden_field));
			
			$smart->display('backup/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=backup.php>";
			exit;	
		}
		else{												//比较密码成功
			
			//检查权限
			checkRole($boxesDB,"〖备份帐套〗",$_POST[username],"EXECUTE");
			
			$showResult=$boxesDB->showTable();
			for($i=0;$i<count($showResult);$i++){
				$row=$showResult[$i];
				$table_array[]=array(	"Name"		=>	$row[Name],
										"Comment"	=>	$row[Comment],
//										"Size"		=>	num_chunk($row[Data_length],
										"Size"		=>	num_chunk($row[Data_length]));
			}
			
			$module_name="备份数据第三步";
			$smart->assign(array("action_file"		=>	$action_file,
								 "module_name"		=>	$module_name,
								 "db_dbname"		=>	$DATABASE,
								 "table_array"		=>	$table_array,
								 "table_num"		=>	count($table_array),
								 "username"			=>	$_POST[username],
								 "password"			=>	$_POST[password]));
			
			$smart->display('backup/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/step_2.tpl.htm');
	}
	else{
		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/step_1.tpl.htm');
	}
	?>