<?php
/**
 * @version        Somao_Search X1.0 9:23 2012-1-1 Somao $
 * @package        Somao_Search.Site
 * @copyright      Copyright (c) 2009 - 2012, Somao, Inc.
 * @license        http://www.somao123.com/
 * @link           http://www.somao.cc/
 */
require "../global.php";
$backup_path="./sqlbackup/";
$action=$_GET["action"];
switch($action)
{
    case "backup_sql":
	backup_sql();
	break;
	case "restore":
	restore();
	break;
	case "down":
	down();
	break;
	case "del":
	del();
	break;
}
?>
<!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=gbk">
<meta http-equiv="x-ua-compatible" content="ie=7" />
<link href="css/admincp.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
  <div class="floattop">
    <div class="itemtitle"><h3>数据库管理</h3>
      <ul class="tab1">
        <li class="current"><a href="Db_admin.php"><span>管理首页</span></a></li>
        <li><a href="?action=backup_sql"><span>备份数据</span></a></li>
      </ul>
     </div>
   </div>
 <div class="floattopempty"></div>
 <table class="tb tb2 " id="tips">
<tr><th  class="partition">提示</th></tr>
<tr><td class="tipsblock" s="1">
<ul id="tipslis">
 <li>当前数据大小：</li>
  <li>该工具仅用于备份重要数据资料，当数据库大小超过50M建议直接备份MYSQL数据源文件，以保证数据不丢失。</li>
</ul></td></tr>
</table>
<table class="tb tb2 ">
   <tr><th  class="partition"  colspan="5">备份信息</th></tr>
  <tr>
    <th>&nbsp;</th>
    <th>文件名</th>
    <th>备份日期</th>
    <th>文件大小</th>
    <th>操作</th>
  </tr>
  <?php
$i=0;
if ($handle = opendir($backup_path))
{
while (false !== ($file = readdir($handle)))//读取文件夹里的文件
{
   if($file!="."&&$file!="..")
   {
         $file_array[$i]["filename"]=$file;
		 $file_array[$i]["filetime"]=date("Y-m-d H:i:s",filemtime($backup_path.$file));
		 $file_array[$i]["filesize"]=ceil(filesize($backup_path.$file)/1024);
		 $i++;
   }

}
closedir($handle);//关闭文件夹
}
?>
<?php
if($file_array){
foreach($file_array as $key=>$rs)
{
array_multisort($file_array, SORT_DESC);
?>
  <tr>
    <td align="center"><?php echo $key;?></td>
    <td><a href="?action=down&filename=<?php echo $rs["filename"];?>"><?php echo $rs["filename"];?></a></td>
    <td><?php echo $rs["filetime"];?></td>
    <td><?php echo $rs["filesize"];?>K</td>
    
    <td>
	<a href="?action=restore&filename=<?php echo $rs["filename"];?>" onClick="if(!confirm('确定还原吗?')) return false;">还原</a>&nbsp;&nbsp;
	<a href="?action=del&filename=<?php echo $rs["filename"];?>" onClick="if(!confirm('确定删除吗?')) return false;">删除</a></td>
  </tr>
<?php 
}
}
?>
</table>

<?php
/**
* @name GetSql
* @param string , 表名
* @return string , SQl语句
*/
function GetSql($table){
$sql = '';
$sql.= "\r\n\r\n".'--导出表 '.$table.' 的结构：'."\r\n\r\n";
$sql.= 'DROP TABLE IF EXISTS '.$table.";\r\n\r\n";
$result = mysql_query('show create table '.$table);
$row =@mysql_fetch_array($result);
$sql.= $row[1].";\r\n\r\n";
$result=mysql_query('select * from '.$table);
$sql.="--导出表 $table 中的数据：\r\n\r\n";
if(mysql_num_rows($result)==0)
   $sql.='--表'.$table.'中无数据';
else{
$sql.= 'INSERT INTO '.$table;
$c = 1;
$titsql =' (';
$contentsql =" VALUES\r\n(";
while ($row = mysql_fetch_assoc($result)){
   while ($elecment = each($row)){
    if($c==1)
    $titsql.=$elecment['key'].',';
    $contentsql.="'".addslashes($elecment['value'])."',";
   }
   $contentsql = substr($contentsql,0,-1).'),'."\r\n(";
   $c++;
}
$titsql =substr($titsql,0,-1).')';
$contentsql = substr($contentsql,0,-4).';';
   $sql.=$titsql;
   $sql.=$contentsql;
}
return $sql;
}
function backup_sql()
{
/**
* @example 如下：导出某个数据库中的所有表
*/
//header('Content-Disposition: attachment; filename="backup.sql"');
//header("Content-Transfer-Encoding: binary\n");
$result = mysql_query("show tables");
while ($row = mysql_fetch_array($result)){
   $content.= GetSql($row[0])."\r\n";
}
$filename=date(YmdHis).".sql";
 $fp=@fopen("sqlbackup/".$filename,"w") or die("写方式打开文件失败，请检查程序目录是否为可写");//配置conn.php文件
 @fputs($fp,$content) or die("文件写入失败,请检查程序目录是否为可写"); 
 @fclose($fp);
 }
function del()
{
  global $backup_path;
  $filename=$_GET["filename"];
  unlink($backup_path.$filename);
}
function restore()
{
  global $db,$backup_path,$fp;
  set_time_limit(0); //设置超时时间为0，表示一直执行。当php在safe mode模式下无效，此时可能会导致导入超时，此时需要分段导入
  $filename=$_GET["filename"];
  $fullpath=$backup_path.$filename;
  $fp = fopen($fullpath, "r") or die("不能打开SQL文件 $fullpath");//打开文件
  
  while($SQL=GetNextSQL())
  {
       if (mysql_query($SQL)){
       //echo "执行SQL：".mysql_error()."";
      // echo "SQL语句为：".$SQL."<BR>";
	   }
   }
       echo $fullpath."导入完成"; 
       fclose($fp) or die("Can't close file $fullpath");//关闭文件
       mysql_close();

}
function GetNextSQL() {
global $fp;
$sql="";
while ($line = @fgets($fp, 40960)) {
$line = trim($line);
//以下三句在高版本php中不需要
$line = str_replace("\\\\","\\",$line);
$line = str_replace("\'","'",$line);
$line = str_replace("\\r\\n",chr(13).chr(10),$line);
// $line = stripcslashes($line);
if (strlen($line)>1) {
if ($line[0]=="-" && $line[1]=="-") {
continue;
}
}
$sql.=$line.chr(13).chr(10);
if (strlen($line)>0){
if ($line[strlen($line)-1]==";"){
break;
}}
}
return $sql;
}
function down()
{
   global $backup_path;
   $filename=$_GET["filename"];
   file_down($backup_path.$filename);
}
?>
