<?
$C_126cmsadmin_tname = 'dbsql_config';

include(dirname(__FILE__)."/global.php");



@$job = $submitted_vars["job"];

if($job == "yh"){//优化表
	$table = $_GET['table'];
	mysql_query("OPTIMIZE TABLE `$table`");
	$showmsg = "操作成功！";
	$formurl = "bakup.php";	 
	include('showmsg.php');
	exit();
}elseif($job=='xf'){//修复表
	$table = $_GET['table'];
	mysql_query("REPAIR TABLE `$table`");
	$showmsg = "操作成功！";
	$formurl = "bakup.php";	 
	include('showmsg.php');
	exit();
}

	
if($job == "bakup"){

	$tabledb = $submitted_vars['tabledb'];
	$start = $submitted_vars['start'];
	$tableid = $submitted_vars['tableid'];
	$sizelimit = $submitted_vars['sizelimit'];
	$step = $submitted_vars['step'];
	$tablesel = $submitted_vars['tablesel'];
	$rows = $submitted_vars['rows'];
	$pre = $submitted_vars['pre'];
	
		
	$bakupstr="#\n# 126cms bakfile\n# Version:1.0\n# Time: ".date('Y-m-d H:i:s')."\n# Type: \n# 126cms: http://www.126cms.com\n# --------------------------------------------------------\n\n\n";

	mysql_query("SET SQL_QUOTE_SHOW_CREATE = 1");//SQL_QUOTE_SHOW_CREATE 的值来决定是否要把表名和字段名用引号引用起来 1  引用 0 不引用
		

		$start = intval($start);
		//!$tabledb && !$tablesel && adminmsg('operate_error');
		!$tabledb && $tabledb=explode("|",$tablesel);
		!$step && $sizelimit/=2;//第一次备份时，备份大小值 / 2
		$bakupdata=bakupdata($tabledb,$start);
		if(!$step){
			//!$tabledb && adminmsg('operate_error');
			$tablesel=implode("|",$tabledb);
			$step=1;
			$start=0;
			//$pre='pw_'.get_date($timestamp,'md').'_'.num_rand(10).'_';
			$pre='w6_'.date('YmdHis').'_'.make_3_rand().'_';
			$bakuptable=bakuptable($tabledb);
		}
		$f_num=ceil($step/2);
		
		// f_num 不足位数 补0
		$max_len = 5;
		$len = strlen($f_num);
		$rest = $max_len-$len;
		for ($i=1;$i<=$rest;$i++) {
			$f_num="0".$f_num;               //补足0
		}

		$filename=$pre.$f_num.'.sql';
		$step++;
		$writedata=$bakuptable ? $bakuptable.$bakupdata : $bakupdata;

	
	
	//$bak_table = bakuptable($tabledb);
	//$bak_data  = bakupdata($tabledb);
	$writedata = $bakupstr.$writedata;
	
	//$pre = 'w6_';
	//$f_num=ceil($step/2);
	//$filename=$pre.$f_num.'.sql';


	if($stop==1){//$stop==1 数据备份未完成 文件大于2M
	
		writetofile("../../data/mysql_bak/".$filename,$writedata);

		echo "<p>&nbsp;</p>\n<p>&nbsp;</p>\n<p>&nbsp;</p>\n<p align=\"center\"> 正在备份 ".$tabledb[$tableid]." 表的内容 </p>";

		echo "<meta http-equiv=\"refresh\" content=\"1;URL=?job=$job&start=$startfrom&tableid=$tableid&sizelimit=$sizelimit&step=$step&pre=$pre&tablesel=$tablesel&rows=$rows\">";
		
	}
	else{
	
		writetofile("../../data/mysql_bak/".$filename,$writedata);
		
		$showmsg = "数据库已成功备份！";
		$formurl = "bakup.php";
    	include('showmsg.php');

	}
    exit;
  
}

function bakupdata($tabledb,$start=0){
	global $sizelimit,$tableid,$startfrom,$stop,$rows;
	$tableid=$tableid?$tableid-1:0;
	$stop=0;//$stop 为 0 时表示数据备完成
	$t_count=count($tabledb);
	for($i=$tableid;$i<$t_count;$i++){
	    if(!$rows){
		$ts =& mysql_fetch_array ( mysql_query("SHOW TABLE STATUS LIKE '$tabledb[$i]'") );
		$rows=$ts['Rows'];
        }    
		$limitadd="LIMIT $start,100000";
		$query = mysql_query("SELECT * FROM $tabledb[$i] $limitadd");
		$num_F = mysql_num_fields($query);//返回结果集中字段的数目

		while ($datadb = mysql_fetch_row($query)){
			$start++;
			$bakupdata .= "INSERT INTO $tabledb[$i] VALUES("."'".mysql_escape_string($datadb[0])."'";
			$tempdb='';
			for($j=1;$j<$num_F;$j++){
				$tempdb.=",'".mysql_escape_string($datadb[$j])."'";
			}
			$bakupdata .=$tempdb. ");\n";//取得一条完整的记录
			if($sizelimit && strlen($bakupdata)>$sizelimit*1000){//$sizelimit 单位是 K ，所以 * 1000 = 字节
				break; //大于规定分卷文件长度跳出 while 循环
			}
		}
		mysql_free_result($query);

		if($start>=$rows){
			$start=0;
			$rows=0;
		}

		$bakupdata .="\n";
		if($sizelimit && strlen($bakupdata)>$sizelimit*1000){
			$start==0 && $i++;
			$stop=1;
			break;
		}
		$start=0;
	}
	if($stop==1){
		$i++;
		$tableid=$i;
		$startfrom=$start;
		$start=0;
	}
	return $bakupdata;
}


function bakuptable($tabledb){
	foreach($tabledb as $key=>$table){
		$creattable.= "DROP TABLE IF EXISTS $table;\n";
		//$CreatTable = $db->get_one("SHOW CREATE TABLE $table");
		$query      = "SHOW CREATE TABLE $table";
		$result     =  mysql_query($query);
		$CreatTable =& mysql_fetch_array($result, MYSQL_ASSOC);
		$CreatTable['Create Table']=str_replace($CreatTable['Table'],$table,$CreatTable['Create Table']);
		$creattable.=$CreatTable['Create Table'].";\n\n";
	}
	return $creattable;
}

function bakindata($filename) {
	global $db,$cfg_dbcharset;
	$sql=file($filename);
	$query='';
	$num=0;
	foreach($sql as $key => $value){
		$value=trim($value);
		if(!$value || $value[0]=='#') continue;
		if(eregi("\;$",$value)){
			$query.=$value;
			if(eregi("^CREATE",$query)){
				$extra = substr(strrchr($query,')'),1);
				$query = str_replace($extra,'',$query);
				if($db->server_info() > '4.1'){
					$extra = $cfg_dbcharset ? "ENGINE=MyISAM DEFAULT CHARSET=$cfg_dbcharset;" : "ENGINE=MyISAM;";
				}else{
					$extra = "TYPE=MyISAM;";
				}
				$query .= $extra;
			}elseif(eregi("^INSERT",$query)){
				$query='REPLACE '.substr($query,6);
			}
			$db->query($query);
			$query='';
		} else{
			$query.=$value;
		}

	}
}

function writetofile_w($filename,$book)
{
$fd=fopen("$filename","w");
fwrite($fd,$book);
fclose($fd);
return true;
}
?><!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" />
<title>后台管理</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
a:link {
	text-decoration: none;
	color: #000000;
}
a:visited {
	text-decoration: none;
	color: #000000;
}
a:hover {
	text-decoration: underline;
	color: #FF0000;
}
a:active {
	text-decoration: none;
	color: #000000;
}
-->
</style>
<script language=JavaScript>
function CheckAll(form){
	for (var i=0;i<form.elements.length;i++){
		var e = form.elements[i];
		e.checked == true ? e.checked = false : e.checked = true;
	}
}
</script>
</head>

<body>
<div align="center" class="font12">
  <table width="100%"  border="0" cellpadding="3" cellspacing="1" bgcolor="#A4B6D7">
    <tr>
      <td width="100%" height="22" align="center" background="images/titlebg.jpg">&nbsp;</td>
    </tr>
  </table>
  <br />
  <table width="100%" height="25" border="0" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
    <tr>
      <td align="left" bgcolor="#FFFFFF"> [<a 
      href="bakup.php" class="a_bt">备份数据</a>] 
      [<a 
      href="bakin.php" class="a_bt">还原数据</a>] </td>
    </tr>
  </table>
  <br />
  <table width="100%" border="0" cellpadding="0" cellspacing="0" class="table">
    <tr>
      <td height="22" align="left" class="head">数据库表</td>
    </tr>
    <tr>
      <td height="24" align="left">
	  <br />
      <UL>
      <LI>您可以根据自己的需要选择需要备份的数据库表,导出的数据文件可用&quot;数据恢复&quot;功能。<br />
        <br />
        为了数据安全,备份文件采用时间戳命名保存,如果备份数据超过设定的大小程序会自动采用分卷备份功能，请耐心等待直到程序提示全部备份完成。<br />
        <!---->
      </LI>
      </UL>
</td>
    </tr>
    <tr>
      <td align="center">
	  <FORM name="formlist" action="" method="post">
  <table width="99%" border="0" cellspacing="1" cellpadding="0">
        <tr>
          <td width="4%" height="30" align="center" background="images/titlebg.jpg">ID</td>
          <td width="24%" align="center" background="images/titlebg.jpg">数据库表</td>
          <td width="17%" align="center" background="images/titlebg.jpg">记录数(条)</td>
          <td width="17%" align="center" background="images/titlebg.jpg">占用空间</td>
          <td width="16%" align="center" background="images/titlebg.jpg">选择</td>
          <td width="12%" align="center" background="images/titlebg.jpg">优化</td>
          <td width="10%" align="center" background="images/titlebg.jpg">修复</td>
        </tr>
		<?
$query="SHOW TABLE STATUS";	
$result=mysql_query($query) or die("Could not connect: " . mysql_error());

$i = 1;
while ( $rt = mysql_fetch_array($result) ){
	$value = trim( current($rt) );
	 
		//$othortable[]=$value;
	$table = $value;
	$Rows  = $rt['Rows'];
	
	$totalsize=$totalsize+$rt['Data_length'];//记录数据库总大小
	$Data_length=number_format($rt['Data_length']/1024,3);//每条数据大小

?>
        <tr class=trA onMouseOver="this.className='trB'" 
        onmouseout="this.className='trA'">
          <td align="center" class="td"><?=$i?></td>
          <td align="left" class="td">&nbsp;&nbsp;<?=$table?></td>
          <td align="center" class="td"><?=$Rows?></td>
          <td align="center" class="td"><?=$Data_length?> K</td>
          <td align="center" class="td"><input name="tabledb[]" type="checkbox" value="<?=$table?>" checked="checked"></td>
          <td align="center" class="td"><a href="?job=yh&amp;table=<?=$table?>">优化</a></td>
          <td align="center" class="td"><a href="?job=xf&amp;table=<?=$table?>">修复</a></td>
        </tr>
		<?
		$i++;
		}
		
		
		$totalsize=number_format($totalsize/(1024*1024),3);
		?>
        <tr class=trA onMouseOver="this.className='trB'" 
        onmouseout="this.className='trA'">
          <td colspan="7" align="left" class="td">&nbsp;&nbsp;&nbsp;&nbsp;（总共占用空间 <?=$totalsize?>
             M） 设置每个分卷文件长度为
             <input type=text name="sizelimit" value="2048" size=5> 
            K （数值越大.备份越快,但越占服务器资源,如果你的服务器做了限制备份失败,只能把这个数值改为更小） </td>
          </tr>
        <tr>
          <td height="30" colspan="7" align="center"><input type="button" name="chkall" value="全 选" onClick="CheckAll(this.form)">
<input type=submit value="提 交">
            <input name="job" type="hidden" id="job" value="bakup" /></td>
        </tr>
      </table>
	  </form></td>
    </tr>
  </table>
  </div>
</body>
</html>
