<?php
!function_exists('html') && exit('ERR');
@set_time_limit(0);
$db->query("SET SQL_QUOTE_SHOW_CREATE = 1");

/**
*列出數據表
**/
if($job=='out'&&$Apower[mysql_out]){
	$query=$db->query("SHOW TABLE STATUS");
	while( $array=$db->fetch_array($query) ){
		if($choose!='all'){
			if($choose=='out'){
				if(ereg("^($pre)",$array[Name])){
					continue;
				}
			}else{
				if(!ereg("^($pre)",$array[Name])){
					continue;
				}
			}
		}
		$j++;
		$totalsize=$totalsize+$array['Data_length'];
		$array['Data_length']=number_format($array['Data_length']/1024,3);
		$array[j]=$j;
		$listdb2[$array[Name]]=$array;
	}

	@include("tablename.php");$array='';
	foreach($tableName AS $key=>$value){
		$listdb2[$key] && $array[$key]=$listdb2[$key];
	}
	$listdb=$array?$array+$listdb2:$listdb2;

	$totalsize=number_format($totalsize/(1024*1024),3);
	if(file_exists(PHP168_PATH."cache/bak_mysql.txt"))
	{
		$breakbak=read_file(PHP168_PATH."cache/bak_mysql.txt");
	}
	require(dirname(__FILE__)."/"."head.php");
	require(dirname(__FILE__)."/"."template/mysql/menu.htm");
	require(dirname(__FILE__)."/"."template/mysql/out.htm");
	require(dirname(__FILE__)."/"."foot.php");
	
}
//數據庫優化與修復
elseif($job=='do'&&$Apower[mysql_out]){
	if($step=='yh'){
		$db->query("OPTIMIZE TABLE `$table`");
	}elseif($step=='xf'){
		$db->query("REPAIR TABLE `$table`");
	}
	jump("操作succeed，點擊返回",$FROMURL,1);
}

/**
*導出備份數據
**/
elseif($action=='out'&&$Apower[mysql_out]){
	if(!$tabledb&&!$tabledbreto){
		showmsg('請選擇一個數據表');
	}
	if(!$tabledb&&$tabledbreto){
		$detail=explode("|",$tabledbreto);
		$num=count($detail);
		for($i=0;$i<$num-1;$i++){
			$tabledb[]=$detail[$i];
		}
	}
	$rsdb=bak_out($tabledb);
	require(dirname(__FILE__)."/"."head.php");
	require(dirname(__FILE__)."/"."template/mysql/menu.htm");
	require(dirname(__FILE__)."/"."template/mysql/outaction.htm");
	require(dirname(__FILE__)."/"."foot.php");
}

/**
*選擇要導入還原的數據
**/
elseif($job=='into'&&$Apower[mysql_into]){
	$selectname=bak_time();
	if(file_exists(PHP168_PATH."cache/mysql_insert.txt")){
		echo "<CENTER><table><tr bgcolor=#FF0000><td colspan=5 height=30><div align=center><A HREF=".read_file(PHP168_PATH."cache/mysql_insert.txt")."><b><font color=ffffff>上次還原數據被中斷是否繼續,點擊繼續</font></b></A></div></td></tr></table></CENTER>";
	}
	require(dirname(__FILE__)."/"."head.php");
	require(dirname(__FILE__)."/"."template/mysql/menu.htm");
	require(dirname(__FILE__)."/"."template/mysql/into.htm");
	require(dirname(__FILE__)."/"."foot.php");
}

/**
*處理導入還原數據
**/
elseif($action=='into'&&$Apower[mysql_into])
{
	bak_into();
}

/**
*選擇要刪除的備份數據
**/
elseif($job=='del'&&$Apower[mysql_del]){
	$selectname=bak_time();
	require(dirname(__FILE__)."/"."head.php");
	require(dirname(__FILE__)."/"."template/mysql/menu.htm");
	require(dirname(__FILE__)."/"."template/mysql/del.htm");
	require(dirname(__FILE__)."/"."foot.php");
}

/**
*刪除選定的備份數據
**/
elseif($action=='del'&&$Apower[mysql_del]){
	if(!$baktime){
		showmsg('請選擇一個');
	}
	del_file(PHP168_PATH."cache/mysql_bak/$baktime");
	if(!is_dir(PHP168_PATH."cache/mysql_bak/$baktime")){
		jump("數據刪除succeed","index.php?lfj=mysql&job=del",5);
	}else{
		jump("數據刪除失敗,請確認目錄屬性為0777","index.php?lfj=mysql&job=del",5);
	}
}


/**
*從本機上傳SQL文本導入數據
**/
elseif($job=='sql'&&$Apower[mysql_sql]){
	require(dirname(__FILE__)."/"."head.php");
	require(dirname(__FILE__)."/"."template/mysql/menu.htm");
	require(dirname(__FILE__)."/"."template/mysql/sql.htm");
	require(dirname(__FILE__)."/"."foot.php");
}

/**
*處理本機上傳的SQL數據
**/
elseif($action=='sql'&&$Apower[mysql_sql]){
	if($t==2){
		$sqlfile=PHP168_PATH."$webdb[updir]/$upsql";
		$db->insert_file($sqlfile);
		@unlink($sqlfile);
	}elseif($t==1){
		$sql=StripSlashes($sql);
		if($pre!='p8_'){
			$sql=str_replace("p8_",$pre,$sql);
		}		
		write_file(PHP168_PATH."cache/$timestamp.sql",$sql);
		$db->insert_file(PHP168_PATH."cache/$timestamp.sql");
		unlink(PHP168_PATH."cache/$timestamp.sql");
		//$db->query("$sql");
	}
	jump("如果網頁上方沒出現亂碼，則操作succeed","index.php?lfj=mysql&job=sql",10);
	
}

function show_field($table){
	global $db;
	$query=$db->query(" SELECT * FROM $table limit 0,1");
	$num=mysql_num_fields($query);
	for($i=0;$i<$num;$i++){
		$f_db=mysql_fetch_field($query,$i);
		$field=$f_db->name;
		$show.="`$field`,";
	}
	$show.=")";
	$show=str_replace(",)","",$show);
	return $show;
}


function create_table($table){
	global $db,$repair,$mysqlversion,$Charset;
	$show="DROP TABLE IF EXISTS $table;\n";
	if($repair){
		$db->query("OPTIMIZE TABLE `$table`");
	}
	$array=$db->get_one("SHOW CREATE TABLE $table");

	if(!$mysqlversion){
		$show.=$array['Create Table'].";\n\n";
		return $show;
	}

	$array['Create Table']=preg_replace("/DEFAULT CHARSET=([0-9a-z]+)/is","",$array['Create Table']);

	if($mysqlversion=='new'){
		$Charset || $Charset='latin1';
		$array['Create Table'].=" DEFAULT CHARSET=$Charset";
	}
	$show.=$array['Create Table'].";\n\n";
	return $show;
}


function bak_table($table,$start=0,$row=3000){
	global $db;
	$limit=" limit $start,$row ";
	//$field=show_field($table);
	$query=$db->query(" SELECT * FROM $table $limit ");
	$num=mysql_num_fields($query);
	while ($array=mysql_fetch_row($query)){
		$rows='';
		for($i=0;$i<$num;$i++){
			$rows.="'".mysql_escape_string($array[$i])."',";
		}
		$rows.=")";
		$rows=str_replace(",)","",$rows);
		//$show.="INSERT INTO `$table` ($field) VALUES ($rows);\n";
		$show.="INSERT INTO `$table` VALUES ($rows);\n";
	}
	return $show;
}


function create_table_all($tabledb){
	foreach($tabledb as $table){
		$show.=create_table($table)."\n";
	}
	return $show;
}


function bak_out($tabledb){
	global $db,$pre,$rowsnum,$tableid,$page,$timestamp,$step,$rand_dir,$lfj,$baksize;
	//還沒有隨機生成目錄之前
	if(!$rand_dir){
		/*特地處理有些服務器不能創建目錄的情況,此時必須手工創建mysql目錄*/
		if( file_exists(PHP168_PATH."cache/mysql_bak/mysql") )
		{
			if( !is_writable(PHP168_PATH."cache/mysql_bak/mysql") ){
				showmsg(PHP168_PATH."cache/mysql_bak/mysql目錄不可寫,請改屬性為0777");
			}
			$rand_dir="mysql";
			copy("mysql_into.php",PHP168_PATH."cache/mysql_bak/$rand_dir/index.php");
			$show=create_table_all($tabledb);	//備份數據表結構
			//$db->query("TRUNCATE TABLE {$pre}bak");
			//bak_dir('../php168');		//備份緩存
		}else{
			$rand_dir=date("Y-m-d.",time()).strtolower(rands(3));
			$show=create_table_all($tabledb);	//備份數據表結構
			if( !file_exists(PHP168_PATH."cache/mysql_bak") ){
				if( !@mkdir(PHP168_PATH."cache/mysql_bak",0777) ){
					showmsg(PHP168_PATH."cache/mysql_bak目錄不能創建");
				}
			}
			if(	!@mkdir(PHP168_PATH."cache/mysql_bak/$rand_dir",0777)	)
			{
				showmsg(PHP168_PATH."cache/mysql_bak/$rand_dir,目錄不可寫,請改屬性為0777");
			}
			//復制一個自動還原的文件到SQL目錄.方便日後還原
			copy("mysql_into.php",PHP168_PATH."cache/mysql_bak/$rand_dir/index.php");
			//$db->query("TRUNCATE TABLE {$pre}bak");
			//bak_dir('../php168');		//備份緩存
		}
	}
	!$rowsnum && $rowsnum=500;	//每次讀取多少條數據
	//此page指的是每個表大的時候.需要多次跳轉頁面讀取
	if(!$page)
	{
		$page=1;
	}
	$min=($page-1)*$rowsnum;
	$tableid=intval($tableid);

	//$show.=$tablerows=bak_table($tabledb[$tableid],$min,$rowsnum);
	//當前表能取到數據時,繼續此表下一頁取數據,否則從下一個表的0開始

	if( $tablerows=bak_table($tabledb[$tableid],$min,$rowsnum) )
	{
		$show.=$tablerows;
		unset($tablerows);	//釋放內存
		$page++;
	}
	else
	{
		$page=0;
		$tableid++;
	}

	//分卷是從0開始的
	$step=intval($step);
	$filename="$step.sql";
	write_file(PHP168_PATH."cache/mysql_bak/".$rand_dir."/".$filename,$show,'a+');

	//如果不指定每卷大小.將默認為1M
	$baksize=$baksize?$baksize:1024;
	
	//對文件做精確大小分卷處理
	$step=cksize(PHP168_PATH."cache/mysql_bak/".$rand_dir."/".$filename,$step,1024*$baksize);
	
	//如果還存在表時.繼續,否則結束
	if($tabledb[$tableid])
	{
		foreach($tabledb as $value)
		{
			$Table.="$value|";
		}
		//記錄下來.防止中途備份失敗
		write_file(PHP168_PATH."cache/bak_mysql.txt","index.php?lfj=$lfj&action=out&page=$page&rowsnum=$rowsnum&tableid=$tableid&rand_dir=$rand_dir&step=$step&tabledbreto=$Table&baksize=$baksize");

		echo "<CENTER>已備份 <font color=red>$step</font> 卷, 進度條 <font color=blue>{$page}</font> 當前正在備份數據庫 <font color=red>$tabledb[$tableid]</font></CENTER>";

print<<<EOT
<form name="form1" method="post" action="index.php?lfj=$lfj&action=out&page=$page&rowsnum=$rowsnum&tableid=$tableid&rand_dir=$rand_dir&step=$step&baksize=$baksize">
  <input type="hidden" name="tabledbreto" value="$Table">
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
function autosub(){
	document.form1.submit();
}
autosub();
//-->
</SCRIPT>
EOT;
		//echo "<META HTTP-EQUIV=REFRESH CONTENT='0;URL=index.php?lfj=$lfj&action=out&page=$page&rowsnum=$rowsnum&tableid=$tableid&rand_dir=$rand_dir&step=$step&tabledbreto=$Table&baksize=$baksize'>";
		exit;
	}
	else
	{
		$dir=opendir(PHP168_PATH."cache/mysql_bak/$rand_dir");
		while($file=readdir($dir)){
			if($file!='.'&&$file!='..'&&$file!='index.php')
			{
				$totalsize+=$sqlfilesize=@filesize(PHP168_PATH."cache/mysql_bak/$rand_dir/$file");
				$rs[sqlsize][]=number_format($sqlfilesize/1024,3);
			}
			
		}
		$totalsize=number_format($totalsize/1048576,3);
		@unlink(PHP168_PATH."cache/bak_mysql.txt");
		$rs[totalsize]=$totalsize;
		$rs[timedir]=$rand_dir;
		if( !@is_writable(PHP168_PATH."cache/mysql_bak/$rand_dir/0.sql") ){
			showmsg("備份失敗，請在cache/mysql_bak/目錄下創建一個目錄mysql然後改其屬性為0777,如果此目錄已存在，請刪除他，重新創建，並改屬性為0777");
		}
		return $rs;
	}
}

function bak_time(){
	$show="<select  name='baktime'><option value='' selected>請選擇備份文件</option>";
	$dir=opendir(PHP168_PATH."cache/mysql_bak/");
	while( $file=readdir($dir) ){
		if( is_dir(PHP168_PATH."cache/mysql_bak/$file")&&$file!='.'&&$file!='..' ){
			$show.="<option value='$file'>$file</option>";
		}
	}
	$show.="</select>";
	return $show;
}

function bak_into(){
	global $step,$baktime,$db,$pre;
	$step=intval($step);
	$file=PHP168_PATH."cache/mysql_bak/$baktime/{$step}.sql";
	if( file_exists($file) ){
		$db->insert_file($file);
	}
	$step++;
	if( file_exists(PHP168_PATH."cache/mysql_bak/$baktime/{$step}.sql") ){
		write_file(PHP168_PATH."cache/mysql_insert.txt","?lfj=mysql&action=into&baktime=$baktime&step=$step");
		echo "已導入第 {$step} 卷<META HTTP-EQUIV=REFRESH CONTENT='0;URL=index.php?lfj=mysql&action=into&baktime=$baktime&step=$step'>";
		exit;
	}else{
		//$query=$db->query("SELECT * FROM {$pre}bak ");
		//while(@extract($db->fetch_array($query))){
		//	write_file(PHP168_PATH."A/$bak_dir",$bak_txt);
		//}
		@unlink(PHP168_PATH."cache/mysql_insert.txt");
		jump("導入完畢",'index.php?lfj=mysql&job=into','5');
	}
}
/*
function bak_dir($path){
	global $db,$filedb,$pre;
	if (file_exists($path)){
		if(is_file($path)){
			$files=read_file($path);
			$files=mysql_escape_string($files);
			$db->query("INSERT INTO {$pre}bak (bak_dir,bak_txt) VALUES ('$path','$files') ");
		} else{
			$handle = opendir($path);
			while ($file = readdir($handle)) {
				if( ($file!=".") && ($file!="..") && ($file!="") ){
					if (is_dir("$path/$file")){
						bak_dir("$path/$file");
					} else{
						$files=read_file("$path/$file");
						$files=mysql_escape_string($files);
						if("mysql_config.php"!=$file){
							$db->query("INSERT INTO {$pre}bak (bak_dir,bak_txt) VALUES ('$path/$file','$files') ");
						}
					}
				}
			}
			closedir($handle);
		}
	}
}
*/

/*備份的分卷文件按固定大小作處理*/
function cksize($lastSqlFile,$step,$size){
	if( @filesize($lastSqlFile)<($size+10*1024) )
	{
		return $step;
	}
	//復制一份最後生成的大于指定大小的SQL文件做處理
	copy($lastSqlFile,"{$lastSqlFile}.bak");
	$filePre=str_replace(basename($lastSqlFile),"",$lastSqlFile);
	$readfile=read_file("{$lastSqlFile}.bak");
	$detail=explode("\n",$readfile);
	unset($readfile); //釋放內存
	foreach($detail AS $key=>$value){
		$NewSql.="$value\n";
		if(strlen($NewSql)>$size){
			write_file("$filePre/$step.sql",$NewSql);
			$step++;
			$NewSql='';
		}
	}
	//余下的再寫進新文件,此時step已經累加過了
	if($NewSql){
		write_file("$filePre/$step.sql",$NewSql);
	}
	@unlink("{$lastSqlFile}.bak");
	return $step;
}
?>