<?php
# Name: PHP版程氏音乐CMS管理系统 v3.0
# Author: 程氏<web@chshcms.com> [QQ:848769359]
# Homepage:http://www.chshcms.cn/
include_once("../../lib/cs_label.php");
include_once("../../lib/cs_phpzip.php");
include_once("../loginstate.php");
SystemPer('0_1');
$ac=CS_Request("ac");
$op=CS_Request("op");
?>
<!doctype html>
<html>
<head>
<meta charset="gbk">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>chshdjcms management</title>
<link href="../res/css/admin_style.css" rel="stylesheet" />
<link href="../../public/css/webox.css" rel="stylesheet" />
<script type="text/javascript" src="../res/js/ajax.js"></script>
<script language="javascript" src="../res/js/jquery.js"></script>
<script src="../../public/js/webox.js"></script>
<script type="text/javascript">
function del(_name){ 
  if (confirm("确定删除吗？")){
    window.location='?ac=hy&op=del&name='+_name;
    return true;
  }else{
     return false;
  }		
}
//单个还原
function Dbhy(_name){ 
  if (confirm("确定导入还原吗？")){
    window.location='?ac=hy&op=hy&name='+_name;
    return true;
  }else{
     return false;
  }		
}
</script>
</head>
<body>
<div class="wrap">
	<div class="nav">
		<ul class="cc">
			<li <?php if($ac=='') echo 'class="current"';?>><a href="?">数据库备份</a></li>
			<li <?php if($ac=='hy') echo 'class="current"';?>><a href="?ac=hy">数据库还原</a></li>
		</ul>
	</div>
<?php if($ac=='hy'){ ?>
	<form action="?ac=hy&op=delall" method="post" class="J_ajaxForm" >
	<div class="table_list">
		<table width="100%">
			<thead>
				<tr>
					<td><label>全选</label></td>
					<td>文件名</td>
					<td>大小</td>
					<td>备份时间</td>
					<td>操作</td>
				</tr>
			</thead>
<?php 
	$d='../../lib/sqlbackup/';
	if (is_dir($d)) {
	  	$dh=opendir($d);//打开目录
  		 //列出目录中的所有文件并去掉 . 和 ..
 		 while (false !== ( $file = readdir ($dh))) {
   			if($file!="." && $file!="..") { 
      			$fullpath=$d."/".$file;
?>
			<tr>
				<td><input type="checkbox" name="CS_ID[]" id="CS_ID" value="<?php echo $file?>" class="J_check" data-xid="J_check_x"></td>
				<td><a style="cursor:pointer;" onclick="Dbhy('<?php echo $file?>')"><?php echo $file?></a></td>
				<td><?php echo round(filesize($fullpath)/1204,2)."Kb"?></td>
				<td><?php echo date('Y-m-d H:i:s',filemtime($fullpath))?></td>
				<td><a href="../../lib/sqlbackup/<?php echo $file?>">下载</a> &nbsp;&nbsp;<a style="cursor:pointer;" onclick="Dbhy('<?php echo $file?>')">还原</a> &nbsp;&nbsp;<a style="cursor:pointer;" onclick="del('<?php echo $file?>')">删除</a></td>
			</tr>
<?php
      			}
 		 }
	  	closedir($dh);
	}
?>
		</table>
	</div>
	<div class="btn_wrap">
		<div class="btn_wrap_pd">
			<label class="mr10"><input type="checkbox" class="J_check_all" id="chkall" onClick="return CheckAll(this.form)" value="on">全选</label>
			<button class="btn btn_submit J_ajax_submit_btn" type="button" onClick="DelInfo(this.form)">删除</button>
		<div id="Msg"></div>
		</div>
	</div>
	</form>
</div>
<?php 
  //还原
  if($op=='hy'){
        $name=CS_Request("name");
        echo dbrestore($name);
  }
  //删除
  if($op=='del'){
        $name=CS_Request("name");
	$backupDir = _CSDJ_ROOT_.'lib/sqlbackup/';
        @unlink($backupDir.$name);
        echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,删除成功!").css("color","#026E12");</script>';
	echo "<script>setTimeout(\"window.location='javascript:history.go(-1);'\",2000);</script>";
  }
  //全选删除
  if($op=='delall'){
	$CS_ID=CS_RequestBox("CS_ID");
	$Arr=explode(',',$CS_ID);
	$backupDir = _CSDJ_ROOT_.'lib/sqlbackup/';
	for($i=0;$i<count($Arr);$i++){
              @unlink($backupDir.$Arr[$i]);
        }
        echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,全部删除成功!").css("color","#026E12");</script>';
	echo "<script>setTimeout(\"window.location='javascript:history.go(-1);'\",3000);</script>";
  }
}else{ 
?>
	<div class="h_a">数据表</div>
	<form action="?op=backup" method="post" class="J_ajaxForm" id="J_backup_form">
	<div class="table_full">
		<table width="100%">
			<col class="th" />
			<tr>
				<th>数据表列表</th>
				<td>
					<div class="sql_list J_check_wrap">
						<dl>
							<dt>
								<span class="span_1"><label><input checked type="checkbox" class="J_check_all" id="chkall" onClick="return CheckAll(this.form)" value="on">全选</label></span>
								<span class="span_2">数据表</span>
								<span class="span_3">描述</span>
							</dt>
							<dd>
<?php
		$rs=mysql_query("show tables like '".CS_SqlPrefix.""."%'");
		while ($row = mysql_fetch_array($rs)) {
?>
								<p>
									<span class="span_1"><input type="checkbox" name="CS_ID[]" id="CS_ID" value="<?php echo $row[0]?>" class="J_check" data-xid="J_check_x" checked="checked"></span>
									<span class="span_2"><?php echo $row[0]?></span>
									<span class="span_3"><?php echo Tablems($row[0])?></span>
								</p>
<?php
		}	
?>  
							</dd>
						</dl>
					</div>
				</td>
			</tr>
		</table>
		<div class="h_a">数据备份选项</div>
		<table width="100%">
			<col class="th" />
			<col width="400" />
			<col />
			<tr>
				<th>分卷备份</th>
				<td>
					<input type="text" class="input length_5 mr5" name="size" value="1024">KB
				</td>
				<td><div class="fun_tips">每个分卷文件长度（单位：KB）</div></td>
			</tr>

			<tr>
				<th>压缩备份文件</th>
				<td>
					<ul class="switch_list cc">
						<li><label><input type="radio" name="compress" value="1" checked><span>开启</span></label></li>
						<li><label><input type="radio" name="compress" value="0"><span>关闭</span></label></li>
					</ul>
				</td>
				<td><div class="fun_tips">压缩备份文件以减少占用的空间</div></td>
			</tr>
		</table>
	</div>
	<div class="btn_wrap">
		<div class="btn_wrap_pd">
		<button class="btn btn_submit J_ajax_submit_btn" id="J_backup_btn" type="submit">备份</button>
		<button class="btn J_ajax_submit_btn" type="button" onClick="DBInfo(this.form,'xf')">修复</button>
		<button class="btn J_ajax_submit_btn" type="button" onClick="DBInfo(this.form,'yh')">优化</button>
		<div id="Msg"></div>
		</div>
	</div>
	</form>
</div>
<?php 
}
  //修复数据表
  if($op=='xf'){
	$CS_ID=CS_Request("id");
	$Arr=explode(',',$CS_ID);
	for($i=0;$i<count($Arr);$i++){
                 $sql="REPAIR TABLE `$Arr[$i]`";
	         $db->query($sql);
        }
        echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,数据表修复完成!").css("color","#026E12");</script>';
	echo "<script>setTimeout(\"window.location='?ac'\",5000);</script>";
  }
  //优化数据表
  if($op=='yh'){
	$CS_ID=CS_Request("id");
	$Arr=explode(',',$CS_ID);
	for($i=0;$i<count($Arr);$i++){
                 $sql="OPTIMIZE TABLE `$Arr[$i]`";
	         $db->query($sql);
        }
        echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,数据表优化完毕...!").css("color","#026E12");</script>';
	echo "<script>setTimeout(\"window.location='?ac'\",5000);</script>";
  }

  //备份数据结构
  if($op=='backup'){
        $size=CS_Request("size");
        $compress=CS_Request("compress");
        echo dbbackup($size,$compress);
  }
  //备份数据
  if($op=='dbbkdata'){
        $size=CS_Request("size");
        $compress=CS_Request("compress");
        echo dbbkdata($size);
        if($compress==1){
	     $backupDir = _CSDJ_ROOT_."lib/sqlbackup/";
             $ZipName='CSDjcms_' . date("YmdHis") . '_' . rand(10000, 99999);
             $phpZip = new PHPZip();
             $phpZip->Zip($backupDir.CS_Sqlname, $backupDir.$ZipName.'.zip');
        }
        //删除目录 
        $wm_chief=new del_path(); 
        $wm_chief_ok=$wm_chief->wm_chief_delpath($backupDir.CS_Sqlname."/"); 
        echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,备份成功，备份文件在:'.$backupDir.$ZipName.'.zip!").css("color","#026E12");</script>';
	echo "<script>setTimeout(\"window.location='?ac=hy'\",8000);</script>";
  }

//备份数据表
function dbbackup($size,$compress){
        global $db;
        $Table='';
	$result=$db->list_tables(CS_Sqlname);
	if($result){
	  $dirs = "../../lib/sqlbackup/".CS_Sqlname."/";
	  $bkfile = $dirs."CSDjcms_tables_struct_".substr(md5(time().mt_rand(1000,5000)),0,16).".txt";  
	   $rs=mysql_query("show tables like '".CS_SqlPrefix.""."%'");   
	   while ($row = mysql_fetch_array($rs)){   
			 $sql="SHOW CREATE TABLE `$row[0]`";
			  $tableStruct=$db->getAll($sql);
			  if($tableStruct){
				  //去除AUTO_INCREMENT
				   $tableStruct[0]['Create Table']= eregi_replace("AUTO_INCREMENT=([0-9]{1,})[ \r\n\t]{1,}","",$tableStruct[0]['Create Table']);
				   $Table.=$tableStruct[0]['Create Table']."\r\n";
			  }else{
				 echo '<script>$("#Msg").text("抱歉，数据表结构备份失败!").css("color","red");</script>';
			  }
	   }	  
           if(write_file($bkfile, $Table)){
                     echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,数据表结构备份成功,3秒后开始备份数据!").css("color","#026E12");</script>';
	             echo "<script>setTimeout(\"window.location='?op=dbbkdata&size=".$size."&compress=".$compress."'\",3000);</script>";
           }else{
                     echo '<script>$("#Msg").text("抱歉，备份写入失败!").css("color","red");</script>';
           }
	} 
}

//备份数据内容
function dbbkdata($size){
	if(empty($size)) $size=1024;
	$bakStr='';
        global $db;
	$tabelresult=$db->list_tables(CS_Sqlname);
	if($tabelresult){
	   $rs=mysql_query("show tables like '".CS_SqlPrefix.""."%'");   
	   while ($tabelrow = mysql_fetch_array($rs)) { 
	         $intable = "INSERT INTO `$tabelrow[0]` VALUES(";							 
	         $fieldresult=$db->list_fields(CS_Sqlname,$tabelrow[0]);
		 $i=0;
		 if($fieldresult){
			//分析表里的字段信息
	  		 while($fieldrow=mysql_fetch_field($fieldresult)){
		 		$fs[$i] = trim($fieldrow->name);
				$i++;
			 }
				$fsd=$i-1;
				////读取表的内容
				$sql="select * from `$tabelrow[0]`";
				$result=$db->getAll($sql);
				for($j=0;$j<count($result);$j++){
					$line = $intable;
					for($k=0;$k<=$fsd;$k++){
						if($k < $fsd){
							$line.="'".mysql_escape_string($result[$j][$fs[$k]])."',";
						}else{
							$line.="'".mysql_escape_string($result[$j][$fs[$k]])."');\r\n";
						}							
				        }
					if(strlen($bakStr)>$size*1024){
						$dirs = "../../lib/sqlbackup/".CS_Sqlname."/";
                                                $bkfile = "CSDjcms_tables_datas_".substr(md5(time().mt_rand(1000,5000)),0,16).".txt";
						write_file($dirs.$bkfile, $bakStr);
						echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,数据库'.$bkfile.'备份成功!").css("color","#026E12");</script>';						
						$bakStr='';
					}
				        $bakStr.=$line;						
				}
		 }	
	   }
	   if(!empty($bakStr)&&strlen($bakStr)<$size*1024){
			  $dirs = "../../lib/sqlbackup/".CS_Sqlname."/";
                          $bkfile = "CSDjcms_tables_datas_".substr(md5(time().mt_rand(1000,5000)),0,16).".txt";
			  write_file($dirs.$bkfile, $bakStr);
                          echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,数据库'.$bkfile.'备份成功!").css("color","#026E12");</script>';						
	   }
	}		
}

//还原数据
function dbrestore($name){
        global $db;
	$backupDir = _CSDJ_ROOT_.'lib/sqlbackup/';
        $phpZip = new PHPZip();
        $result=$phpZip->Extract($backupDir.$name,$backupDir.CS_Sqlname);
        if($result==-1){
                 echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("抱歉。文件解压出错!").css("color","#026E12");</script>';
        }else{
            //开始还原数据
		$d=$backupDir.CS_Sqlname;
		if (is_dir($d)) {
			$dh=opendir($d);//打开目录
			//列出目录中的所有文件并去掉 . 和 ..
                        //--------------------------------还原数据表结构----------------------------------------------//
			 while (false !== ( $file = readdir ($dh))) {
				if($file!="." && $file!="..") { 
					$fullpath=$d."/".$file;
					//还原表结构
					if(stristr($fullpath,"CSDjcms_tables_struct_")) {
						$tabel_stru=file_get_contents($fullpath);
						$tabelarr=explode(";",$tabel_stru);
							for($i=0;$i<count($tabelarr)-1;$i++){
							  $db->query($tabelarr[$i]);					  							 
							}
						echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("恭喜,数据表结构已还原成功,即将还原数据...!").css("color","#026E12");</script>';						
					} 
      			               if(stristr($fullpath,"CSDjcms_tables_datas_") ) {
         		 	                //数据列表
					        $filearr[]=$fullpath;
     			               } 
				}
			 }
                        //--------------------------------开始还原数据----------------------------------------------//
		         for($i=0;$i<count($filearr);$i++){
			        $tabel_datas=file_get_contents(trim($filearr[$i]));
			         $dataarr=explode("\n",$tabel_datas);
			          for($j=0;$j<count($dataarr);$j++){
				          $db->query($dataarr[$j]);
			          }
			          echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("已经还原<font color=red>'.$j.'</font>条数据．．．").css("color","#026E12");</script>';						
			  
		          }	
		  closedir($dh);
		}

            //删除目录 
            $wm_chief=new del_path(); 
            $wm_chief_ok=$wm_chief->wm_chief_delpath($backupDir.CS_Sqlname); 
            echo '<script>document.getElementById("Msg").className="tips_success";$("#Msg").text("数据库已全部数据还原成功!").css("color","#026E12");</script>';
	    echo "<script>setTimeout(\"window.location='javascript:history.go(-1);'\",2000);</script>";
        }
}

function Tablems($bame){
      $Bname=CS_ReplaceStr($bame,CS_SqlPrefix,'');
      switch($Bname){
         case 'admin':  $Titms="后台管理员";break;
         case 'ads':  $Titms="广告表";break;
         case 'blog':  $Titms="微薄表";break;
         case 'news':  $Titms="文章表";break;
         case 'caiji':  $Titms="采集规则";break;
         case 'class':  $Titms="分类表";break;
         case 'dance':  $Titms="歌曲表";break;
         case 'down':  $Titms="下载记录";break;
         case 'dt':  $Titms="会员动态";break;
         case 'fans':  $Titms="粉丝表";break;
         case 'fav':  $Titms="歌曲收藏";break;
         case 'friend':  $Titms="好友表";break;
         case 'funco':  $Titms="访客表";break;
         case 'fwqip':  $Titms="歌曲服务器";break;
         case 'gbook':  $Titms="留言表";break;
         case 'label':  $Titms="自定义标签";break;
         case 'link':  $Titms="友情链接";break;
         case 'pay':  $Titms="支付记录";break;
         case 'photo':  $Titms="图片表";break;
         case 'pic':  $Titms="相册表";break;
         case 'pl':  $Titms="评论表";break;
         case 'skins':  $Titms="模版表";break;
         case 'tags':  $Titms="标签表";break;
         case 'topic':  $Titms="专集表";break;
         case 'user':  $Titms="会员用户";break;
         case 'xiaoxi':  $Titms="会员消息";break;
         case 'error':  $Titms="歌曲报错";break;
      }
     return $Titms;
}
?>
</body>
</html>
