<?php 
class cls_ctl_data_back
{
	private $arr_config=array();
    function __construct()
    {
		global $obj_db;
		$this->arr_config["back_root"]="/".DATA_DIR."/back";
    }
	function __get($name){
		if(isset($this->arr_config["$name"])){
			return $this->arr_config["$name"];
		}
	}
	function __set($name,$value){
		if($this->arr_config["$name"]){
			$this->arr_config["$name"]=$value;
		}else{
		}
	}

	function on_del($msg_backname){
		$msg_return=array();
		$str_path=self::get_real_path($msg_backname);
		$msg_return["err"]=dir_delete($str_path);
		if(!$msg_return["err"]){
			$msg_return["err"]="删除失败！请确定备份文件存在，及有权限删除";
		}else{
			$msg_return["err"]="";
		}
		return $msg_return;
	}
	function get_real_path($msg_path=""){
		$str_path=$msg_path;
		if(!is_dir($msg_path) && !is_file($msg_path)){
			$str_path=get_real_path("",$this->arr_config["back_root"]."/".$msg_path);
		}
		return $str_path;
	}
	function get_back_list(){
		$arr_return=array();
		$str_path=self::get_real_path();
		$arr_return=get_dirs($str_path);
		return $arr_return;
	}
	function get_tables($msg_backname,$msg_isinstall=0){
		$arr_return=array("err"=>"");
		$str_path=self::get_real_path($msg_backname);
		if(!is_dir($str_path)){
			$arr_return["err"]="数据备份目录不存在！";
		}
		$arr_dir=get_dirs($str_path);
		$arr_table=array();
		foreach($arr_dir as $item){
			$str_name=substr($item["name"],4);
			if($msg_isinstall==0&&(stripos($str_name,"sys_admin_log")||stripos($str_name,"sys_session"))){
				continue;
			}
			$arr_table[]=$str_name;
		}
		$arr_return["tables"]=$arr_table;
		return $arr_return;
	}
	function on_create($msg_backname,$msg_table){
		global $obj_db;
		$arr_return=array("err"=>"");
		$str_path=self::get_real_path($msg_backname);
		if(!is_dir($str_path)){
			$arr_return["err"]="数据备份目录不存在！";
			return $arr_return;
		}
		$str_path=self::get_real_path($msg_backname."/tab_".$msg_table."/create.sql");
		if(!is_file($str_path)){
			$arr_return["err"]="数据备份文件不存在！".$str_path;
			return $arr_return;
		}
		$str_sql=str_replace("{DB_PRE}",DB_PRE,file_get_contents($str_path));
		$arr_msg=self::on_exesql($str_sql);
		$arr_return["err"]=$arr_msg["err"];
		return $arr_return;
	}
	function on_exesql($str_sql,$arr_replace=array()){
		global $obj_db;
		$arr_return=array("err"=>"");
		$str_sql=str_replace("{DB_PRE}",DB_PRE,$str_sql);
		foreach($arr_replace as $item=>$key){
			$str_sql=str_replace($item,$key,$str_sql);
		}
		$arr_sql=explode(";".chr(10),$str_sql);
		$err_msg="";
		foreach($arr_sql as $item){
			$item=trim($item);
			if(empty($item)) continue;
			$str_msg=$obj_db->execute($item);
			if($str_msg!="") $arr_return["err"].=$str_msg.";";
		}
		return $arr_return;
	}
	function on_insert($msg_backname,$msg_table,$msg_page=1)
	{
		global $obj_db;
		$arr_return=array("err"=>"");
		if($msg_page<1)$msg_page=1;
		$str_path=self::get_real_path($msg_backname."/tab_".$msg_table."/".$msg_page.".sql");
		if(!is_file($str_path)){
			$arr_return["err"]="数据备份文件不存在！";
			return $arr_return;
		}

		$str_sql=str_replace("{DB_PRE}",DB_PRE,file_get_contents($str_path));

		$arr_msg=self::on_exesql($str_sql);
		$arr_return["err"]=$arr_msg["err"];

		$lng_page=$msg_page+1;
		$str_next_sql=self::get_real_path($msg_backname."/tab_".$msg_table."/".$lng_page.".sql");
		if(is_file($str_next_sql)){
			$arr_return["next_page"]=$lng_page;
		}else{
			$arr_return["next_page"]=0;
		}
		return $arr_return;
	}
	function on_back_insert($msg_backname,$msg_table,$msg_page=1,$msg_pagesize=10000)
	{
		$arr_return=array("err"=>"");
		global $obj_db;
		$obj_rs   = $obj_db->get_one("SELECT count(*) as num FROM ".$msg_table);
		$int_total=$obj_rs["num"];
		$int_pages= ceil($int_total/$msg_pagesize);
		$msg_page = min($int_pages, $msg_page);
		$msg_page = max($msg_page, 1);
		$int_offset = $msg_pagesize*($msg_page-1);
		$result = $obj_db->query("select * from ".$msg_table." limit ".$int_offset.",".$msg_pagesize);
		$str_keys="";
		$str_values="";
		$str_insert_sql="";
		$str_newtable='{DB_PRE}'.substr($msg_table,strlen(DB_PRE));
		while($obj_rs = $obj_db->fetch_array($result))
		{
			$str_keys="";
			$str_values="";
			foreach($obj_rs as $item=>$key)
			{
				$str_keys.="`".$item."`,";
				$str_values.="'".mysql_real_escape_string($key)."',";
				//$str_key=str_replace("\\","\\\\",$key);
				//$str_key=str_replace("'","''",$str_key);
				//$str_values.=$str_key;
			}
			$str_keys=substr($str_keys,0,-1);
			$str_values=substr($str_values,0,-1);
			$str_insert_sql.="INSERT INTO `".$str_newtable."` (".$str_keys.") values(".$str_values.");".chr(10);
		}
		$str_sql="#-----------------添加记录表--- ".$msg_table.chr(10).$str_insert_sql;
		$str_path=self::get_real_path($msg_backname."/tab_".$msg_table."/".$msg_page.".sql");
		$str_dir=self::get_real_path($msg_backname."/tab_".$msg_table);
		dir_create($str_dir);
		$arr_return=file_create($str_path,$str_sql);
		$arr_return["page_count"]=$int_pages;
		$arr_return["next_page"]=$msg_page+1;
		return $arr_return;
	}
	function on_back_create($msg_backname,$msg_table){
		$arr_return=array("err"=>"");
		global $obj_db;
		$str_backname=$msg_backname;
		$str_table=$msg_table;
		$result = $obj_db->query("SHOW COLUMNS FROM ".$str_table);
		$str_fields="";
		$str_primary_key="";
		$str_union_key="";
		$str_key="";
		$arr_primary_key=array();
		while($obj_rs = $obj_db->fetch_array($result))
		{
			(strtolower($obj_rs["Null"])=="yes")? $str_default="default NULL":$str_default="NOT NULL";
			$str_extra="";
			if($obj_rs["Extra"]!=""){
				$str_extra=" ".$obj_rs["Extra"];
			}
			if($obj_rs["Key"]!=""){
				if($obj_rs["Key"]=="PRI"){
					$arr_primary_key[]=$obj_rs["Field"];
				}else if($obj_rs["Key"]=="UNI"){
					$str_union_key="UNIQUE KEY `".$obj_rs["Field"]."` (`".$obj_rs["Field"]."`),".chr(10);
				}else{
					if($str_key==""){
						$str_key="KEY `".$obj_rs["Field"]."` (`".$obj_rs["Field"]."`)";
					}else{
						$str_key.=",".chr(10)."KEY `".$obj_rs["Field"]."` (`".$obj_rs["Field"]."`)";
					}
				}
			}
			$str_fields.="`".$obj_rs["Field"]."` ".$obj_rs["Type"]." ".$str_default.$str_extra.",";
		}
		$result = $obj_db->query("show table status ");
		while($obj_rs = $obj_db->fetch_array($result))
		{
			$arr_table_status[$obj_rs["Name"]]=$obj_rs;
		}
		if(count($arr_primary_key)>0){
			$str_primary_key="PRIMARY KEY (`".implode("`,`",$arr_primary_key)."`),".chr(10);
		}
		$str_table_key=$str_primary_key.$str_union_key.$str_key;
		$arr_charset=explode("_",$arr_table_status[$str_table]["Collation"]);
		$str_charset=$arr_charset[0];
		if($str_table_key!=""){
			$str_table_key=trim($str_table_key);
			if(substr($str_table_key,-1)==",") $str_table_key=substr($str_table_key,0,-1);
			$str_fields.=$str_table_key;
		}else{
			$str_fields=trim($str_fields);
			if(substr($str_fields,-1)==",") $str_fields=substr($str_fields,0,-1);
		}

		$str_newtable='{DB_PRE}'.substr($msg_table,strlen(DB_PRE));
		$str_create_sql="DROP TABLE IF EXISTS `".$str_newtable."`;".chr(10)."CREATE TABLE IF NOT EXISTS `".$str_newtable."` (".chr(10).$str_fields.chr(10).") ENGINE=".$arr_table_status[$str_table]["Engine"]."  DEFAULT CHARSET=".$str_charset;
		if(isset($arr_table_status[$str_table]["Auto_increment"])&&$arr_table_status[$str_table]["Auto_increment"]>0){
			$str_create_sql.=" AUTO_INCREMENT=".$arr_table_status[$str_table]["Auto_increment"];
		}

		$str_sql="#-----------------创建表--- ".$msg_table.chr(10).$str_create_sql.chr(10).chr(10);
		$str_path=self::get_real_path($msg_backname."/tab_".$msg_table."/create.sql");
		$str_dir=self::get_real_path($msg_backname."/tab_".$msg_table);
		dir_create($str_dir);
		$arr_return=file_create($str_path,$str_sql);
	}
}
?>
