<?php

/*
'**************************************************************************************************
' 程序名称: CCTVAI开源音乐管理系统
' 官方网站: http://www.cctvai.com
' 联系 Q Q: 1542367792
' QQ交流群：136687984
' 版本：(终结版)
' 备注：未经书面授权，不得向任何第三方提供本软件系统！
' 功能，模板，插件，扩展，定制请联系QQ：1542367792
'**************************************************************************************************
*/
error_reporting(0);
include "../../include/cctvai.conn.php";
include "../function_common.php";
set_time_limit(0);
@ini_set('memory_limit','-1');
admincheck(9);
/*if(Smallfivesolution() == $_SERVER['SERVER_NAME']) {
} else {
    echo Smallfivesq();
    exit();
}*/
$action=SafeRequest("action", "get");
if($action=="del") {
$time=SafeRequest("time", "get");
deldir($time);
showmessage("备份目录".$time."已删除！", $_SERVER['HTTP_REFERER'], 0);
}
if($action=="backup") {
	echo "<style type='text/css'><!--body,td,th {background-color: #FFFFFF;font-size: 9pt;}a {font-size: 9pt;}a:link {text-decoration: none;color:#3F628C;}a:visited {text-decoration: none;color:#3F628C;}a:hover {text-decoration: none;color:#3F628C;}a:active {text-decoration: none;color:#3F628C;}--></style>";
	//echo("<div style='width:100%; background: #FAFBF7; border-top:4px solid #E2F5BC; border-bottom:1px solid #E2F5BC;color:#668E1B; font-size:10pt; height:30px; line-height:30px;font-weight:bold; margin:0 auto;'>&nbsp;正在备份数据...</div><br/>");
	//创建目录
	$dir='../backup/'.date('Y-m-d');
	if (!file_exists($dir)) {
		@mkdir($dir, 0777, true);
		}
	//删除旧文件
	deloldbk();
	$size=SafeRequest("sizes", "post");
	global $db;
	$result=$db->list_tables(cd_sqldbname);
	if($result) {
		$bkfile="../backup/".date('Y-m-d')."/tables_struct_" . substr(md5(time() . mt_rand(1000, 5000)), 0, 16) . ".txt";
		$fp=fopen($bkfile, "w");
		while($row=mysql_fetch_row($result)) {
			$cctvai_ID=explode("_", $row[0]);
			if($cctvai_ID[0]==ReplaceStr(cd_tablename, "_", "")) {
				fwrite($fp, "DROP TABLE IF EXISTS `$row[0]`;\r\n\r\n");
				$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']);
					fwrite($fp, '' . $tableStruct[0]['Create Table'] . ";\r\n\r\n");
					echo "&nbsp;<font style=\"font-size:10pt;\">数据表：<font color=red>$row[0]</font> 结构备份成功...</font><br/>";
				} else {
					echo "&nbsp;<font style=\"font-size:10pt;\">数据表：<font color=red>$row[0]</font> 结构备份失败...</font><br/>";
				}
			}
		}
		fclose($fp);
		die("<br/>&nbsp;<font style=font-size:10pt;><b>数据表结构已全部备份完毕，将暂停 " . cd_stoptime . " 秒后开始备份数据，请不要关闭或刷新...</b></font><script language='javascript'>setTimeout('ReadGo();'," . (cd_stoptime*1000) . ");function ReadGo(){location.href='?action=bkdata&size=" . $size . "';}</script>");
		mysql_free_result($result);
	}
} elseif($action=="bkdata") {
	echo "<style type='text/css'><!--body,td,th {background-color: #FFFFFF;font-size: 9pt;}a {font-size: 9pt;}a:link {text-decoration: none;color:#3F628C;}a:visited {text-decoration: none;color:#3F628C;}a:hover {text-decoration: none;color:#3F628C;}a:active {text-decoration: none;color:#3F628C;}--></style>";
	//echo("<div style='width:100%; background: #FAFBF7; border-top:4px solid #E2F5BC; border-bottom:1px solid #E2F5BC;color:#668E1B; font-size:10pt; height:30px; line-height:30px;font-weight:bold; margin:0 auto;'>&nbsp;正在备份数据...</div><br/>");
	$size=SafeRequest("size", "get");
	$a=2;
	if(!IsNum($size))
		$size=1024;
	$bakStr='';
	$tabelresult=$db->list_tables(cd_sqldbname);
	if($tabelresult) {
		while($tabelrow=mysql_fetch_row($tabelresult)) {
			$cctvai_ID=explode("_", $tabelrow[0]);
			if($cctvai_ID[0]==ReplaceStr(cd_tablename, "_", "")) {
				$intable="INSERT INTO `$tabelrow[0]` VALUES(";
				$fieldresult=$db->list_fields(cd_sqldbname, $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";
							}
						}
						$bakStr.=$line;
						if(strlen($bakStr)>$size*1024) {
							$a=$a+1;
							$b=$b+1;
							$bkfile="../backup/".date('Y-m-d')."/tables_datas_" . substr(md5(time() . mt_rand(1000, 5000)), 0, 16) . ".txt";
							$fp=fopen($bkfile, "w");
							fwrite($fp, $bakStr);
							fclose($fp);
							echo "&nbsp;<font style=\"font-size:10pt;\">数据库：<font color=red>../backup/".date('Y-m-d')."/" . rand(1000, 5000) . "" . rand(1000, 5000) . "" . rand(1000, 5000) . ".txt</font> 文件备份成功...</font></font><br/>";
							$bakStr='';
						}
					}
				}
			}
		}
		if(!empty($bakStr) && strlen($bakStr)<$size*1024) {
			$bkfile="../backup/".date('Y-m-d')."/tables_datas_" . substr(md5(time() . mt_rand(1000, 5000)), 0, 16) . ".txt";
			$fp=fopen($bkfile, "w");
			fwrite($fp, $bakStr);
			fwrite(fopen("../backup/".date('Y-m-d')."/1.txt", "wb"), date('Y-m-d H:i:s'));
			//echo "<br/>&nbsp;<font style=\"font-size:10pt;\">数据库：<font color=red>../backup/".date('Y-m-d')."/</font> 文件备份成功...</font></font><br/>";
			if($b){$backupsize=formatsize($b*1048576);}else{$backupsize='1MB';}
			die("<br/><br/>&nbsp;<font style=\"font-size:10pt;\"><b>恭喜您，数据库已全部备份完毕！</b></font>&nbsp;<font style=\"font-size:10pt;\"><b>备份".$a."个文件，占用空间：".$backupsize."</b></font><script language='javascript'>alert('恭喜您，数据库已全部备份完毕！请重新加载本页面！');</script>");
			fclose($fp);
		}
	}

} elseif($action=="restore") {
	echo "<style type='text/css'><!--body,td,th {background-color: #FFFFFF;font-size: 9pt;}a {font-size: 9pt;}a:link {text-decoration: none;color:#3F628C;}a:visited {text-decoration: none;color:#3F628C;}a:hover {text-decoration: none;color:#3F628C;}a:active {text-decoration: none;color:#3F628C;}--></style>";
	$time=SafeRequest("time", "get");
	if(!file_exists('../backup/'.$time.'/1.txt')){exit ("&nbsp;<font color=red></b>出错了，没有文件夹备份文件，请先备份数据！</b></font>");}
	if($time=="") {
		echo ("&nbsp;<font color=red></b>出错了，没有文件夹备份文件，请先备份数据！</b></font>");
	} else {
		$d='../backup/'.$time.'';
		if(is_dir($d)) {
			$dh=opendir($d); //打开目录
			//列出目录中的所有文件并去掉 . 和 ..
			while(false!==($file=readdir($dh))) {
				if($file!="." && $file!="..") {
					$fullpath=$d . "/" . $file;
					//还原表结构
					if(!is_dir($fullpath) && stristr($fullpath, "tables_struct_")) {
						$tabel_stru=file_get_contents($fullpath);
						$tabelarr=explode(";", $tabel_stru);
						for($i=0; $i<count($tabelarr)-1; $i++) {
							$db->query($tabelarr[$i]);
						}
						die("<br/>&nbsp;<font style=font-size:10pt;><b>数据表结构已还原完毕，将暂停 " . cd_stoptime . " 秒后开始恢复数据，请不要关闭或刷新...</b></font><script language='javascript'>setTimeout('ReadGo();'," . (cd_stoptime*1000) . ");function ReadGo(){location.href='?action=restoredata&time=".$time."';}</script>");
					}
				}
			}
			closedir($dh);
		}
	}

} elseif($action=="restoredata") {
	echo "<style type='text/css'><!--body,td,th {background-color: #FFFFFF;font-size: 9pt;}a {font-size: 9pt;}a:link {text-decoration: none;color:#3F628C;}a:visited {text-decoration: none;color:#3F628C;}a:hover {text-decoration: none;color:#3F628C;}a:active {text-decoration: none;color:#3F628C;}--></style>";
	$time=SafeRequest("time", "get");
	$d='../backup/'.$time.'';
	if(is_dir($d)) {
		$dh=opendir($d); //打开目录
		//列出目录中的所有文件并去掉 . 和 ..
		while(false!==($file=readdir($dh))) {
			if($file!="." && $file!="..") {
				$fullpath=$d . "/" . $file;
				if(!is_dir($fullpath) && stristr($fullpath, "tables_datas_")) {
					//数据列表
					$filearr[]=$fullpath;
				}
			}
		}
		for($i=0; $i<count($filearr); $i++) {
			$tabel_datas=file_get_contents(trim($filearr[$i]));
			//$db->query($tabel_datas);
			$dataarr=explode("\n", $tabel_datas);
			for($j=0; $j<count($dataarr); $j++) {
				$db->query($dataarr[$j]);
			}
			echo "<br/>&nbsp;<font style=\"font-size:10pt;\">已经还原 <font color=red>" . $j . "</font> 条数据...</font><br/>";
		}
		die("<br/><br/>&nbsp;<font style=\"font-size:10pt;\"><b>恭喜您，".$time."备份的数据库已全部还原完毕！</b></font><script language='javascript'>alert('恭喜您，".$time."备份的数据库已全部还原完毕！');</script>");
		closedir($dh);
	}
} else {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head> 
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
  <meta name="renderer" content="webkit" /> 
  <title>管理后台</title> 
  <link rel="stylesheet" href="../css/add.css" type="text/css" media="screen" /> 
 </head> 
 <body> 
  <div class="contents"> 
   <div class="panel"> 
    <div class="panel-head"> 
     <strong>数据库备份与还原</strong> 
    </div> 
    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="tb_style"> 
     <form method="post" name="SpanSel" action="" target="Html_Bottom">
     <tbody>
      <tr> 
       <td height="50" class="td_border"> &nbsp;&nbsp;数据分卷大小： <input type="text" size="5" name="sizes" value="1024" class="input input_hd length_2" /> &nbsp;KB&nbsp; &nbsp;&nbsp; <input type="checkbox" value="1" checked="checked" class="checkbox" style="display:none;"/> &nbsp;&nbsp;&nbsp; <input name="submit" type="submit" class="btn btn_submit J_ajax_submit_btn mr10" value="开始备份数据库" onclick="SpanSel.action='?action=backup';return confirm('确定开始备份数据库？');" /> </td> 
      </tr> 
      <tr> 
       <td height="30" class="td_border">&nbsp;&nbsp;数据库备份注意：备份将清空当天所有备份数据，写入新的备份数据。<br>&nbsp;&nbsp;备份占用空间容量，适当的删除旧备份文件能减少空间容量开支。</td> 
      </tr>  
     </tbody>
    </table> 
   </div> 
   </div> 
<div class="contents"> 
<div class="panel"> 
<div class="panel-head">
<strong>进行状态：<span style='color:#ff0000;'>在没看到提示完成的情况下不要刷新或关闭此页面</span></strong>
</div>
<div id="mdv" style="width:100%;height:200px;">
        <iframe name="Html_Bottom" frameborder="0" id="Html_Bottom" width="100%" height="100%"></iframe>
       </div>
  </div>  
  </div>  
  </div>  
  <style type="text/css">
.table2{width: 100%;max-width: 100%;border-collapse: collapse;border-spacing: 0;}
.table2 td{font-size: 12px;border-top: 1px solid #ddd;padding: 8px;vertical-align: top;}
.table2 tr:hover{text-decoration: none;background-color: #e6f2fb;}
.table2 th{border-bottom: 2px solid #ddd;vertical-align: bottom;padding: 2px;text-align: left;}
</style>
  <div class="contents" style="width: 300px;"> 
   <div class="panel"> 
    <div class="panel-head"> 
     <strong>还原数据库</strong> 
    </div> 
    <table class="table2"> 
     <tbody> 
      <tr> 
       <td width="120" align="left">备份创建日期</td> 
       <td align="left">操作</td> 
      </tr> 
<?php
$directory='../backup/';
$files=array();
if(is_dir($directory)) {
	if($dh=opendir($directory)) {
		while(($file=readdir($dh))!==false) {
			if($file!='.' && $file!='..') {
$time[] = $file;
			}
		}
		closedir($dh);
	}
}
rsort($time);
$arrlength=count($time);
for($x=0;$x<$arrlength;$x++){
echo'      <tr> 
       <td align="left">'.$time[$x].'</td> 
       <td align="left"><input name="submit" type="submit" class="btn btn-default" value="还原" onclick="SpanSel.action=\'?action=restore&time='.$time[$x].'\';return confirm(\'确定还原'.$time[$x].'的备份数据吗？\');" /> <a class="btn" href="?action=del&time='.$time[$x].'" onClick="return confirm(\'确定将'.$time[$x].'的备份删除吗?删除后不可恢复！\');">删除</a></td> 
      </tr>';
   }
?> 
     </tbody> 
    </table> 
   </div> 
  </div> 
	 </form> 
 </body>
</html>
<?php
}
function deloldbk() {
	$d='../backup/'.date('Y-m-d');
	if(is_dir($d)) {
		$dh=opendir($d); //打开目录
		//列出目录中的所有文件并去掉 . 和 ..
		while(false!==($file=readdir($dh))) {
			if($file!="." && $file!="..") {
				$fullpath=$d . "/" . $file;
				if(!is_dir($fullpath) && $file!="log.txt") {
					unlink($fullpath); //删除目录中的所有文件
				}
			}
		}
		closedir($dh);
	}
}
/*     // 获取文件夹大小  
    function getDirSize($dir)  {   
        $handle = opendir($dir);  
        while (false!==($FolderOrFile = readdir($handle)))  
        {   
            if($FolderOrFile != "." && $FolderOrFile != "..")   
            {   
                if(is_dir("$dir/$FolderOrFile"))  
                {   
                    $sizeResult += getDirSize("$dir/$FolderOrFile");   
                }  
                else  
                {   
                    $sizeResult += filesize("$dir/$FolderOrFile");   
                }  
            }      
        }  
        closedir($handle);  
        return $sizeResult;  
    }  */
function deldir($time) {
	$dir='../backup/'.$time.'/';
  //先删除目录下的文件：
  $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;
  }
}
?>