<?php
# Subroutine: adm_backup_submit.php called by Admin.php
# Xinfeng Chen, 2002.12.19
# Input: $f_scope, $f_bid

require_once('bin/config.php');
require_once('admin/adm.inc');

#--- Validate dministrator ---
include('admin/adm_validate.php');
if(!$adm_validated){jumpTo('admin.php?cmd=logon'); exit;}

#--- Backup specified data ---
require_once('core/class_forum_base.php');
CForumBase::setFileBase("$filepath");

$backfile=CForumBase::getDirPath('BACKUP');
if(!file_exists($backfile)){mkdir($backfile,0700);}
if(!file_exists($backfile)){
 msgBox("备份目录无法建立，中止备份！",mCRITICAL);
 exit;
}
$backfile.="/ZBK$istime";

switch($f_scope){
 case 'ALL': $dirpath=CForumBase::getDirPath('BASE');break; 
 case 'BOARD':
  if(!$f_bid){
   msgBox("指定论坛错误，中止备份！",mCRITICAL);
   exit;
  }
  $dirpath=CForumBase::getDirPath('BOARD',$f_bid);break; 
 case 'USER': $dirpath=CForumBase::getDirPath('USER');break;
 default:
  msgBox("备份策略错误，中止备份！",mCRITICAL);
  exit;
}

if(!file_exists($dirpath) || !is_dir($dirpath)){
 msgBox("源数据文件目录错误，中止备份！",mCRITICAL);
 exit;
}

if(!($fp=fopen($backfile,'wb'))){
 msgBox("备份文件无法建立，中止备份！",mCRITICAL);
 exit;
}

$head='ZBB Backup 2.0'.'|'.$f_scope.'|'.$f_bid.'|'.time().'|'.$ck_admuser.'|';
$head=str_pad($head,64);
fwrite($fp,$head,64);

_backupDir(&$fp, $dirpath);

fclose($fp);

#--- Print result ---
if($f_scope != 'BOARD'){$f_bid='';}
msgBox("论坛数据备份完成！<BR>备份策略：$f_scope, ID=$f_bid 。",mINFORMATION,'操作成功');
exit;

function _backupDir($a_fp, $a_dirpath, $a_relpath='')
{
 if($a_dirpath == CForumBase::getDirPath('BACKUP')){return true;}

 $ddesc='D'.pack('LL',strlen($a_relpath),0);
 $ddesc.=$a_relpath;
 fwrite($a_fp,$ddesc);

 $dir=opendir($a_dirpath);

 while($item=readdir($dir)){
  $itempath="$a_dirpath/$item";
  if($item == '.' || $item == '..'){continue;}
  if(is_file($itempath)){
   $flag=_backupFile(&$a_fp, $itempath, "$a_relpath/$item");
  }elseif(is_dir($itempath)){
   $flag=_backupDir(&$a_fp, $itempath, "$a_relpath/$item");
  }
 }

 closedir($dir);
 return true;
}

function _backupFile($a_fp, $a_fname, $a_relpath)
{
 $fsize=filesize($a_fname);
 $fdesc='F'.pack('LL',strlen($a_relpath),$fsize);
 $fdesc.=$a_relpath;
 fwrite($a_fp,$fdesc);
 $fpos=ftell($a_fp);

 if(!($tmpfp=fopen($a_fname, 'rb'))){return false;}
 while($buf=fread($tmpfp, 4096)){
  fwrite($a_fp, $buf);
 }
 fclose($tmpfp);
 
 fseek($a_fp,$fpos+$fsize);
 return true;
}

?>