<?php


function writesql( $file, $content )
{
	$fp = fopen( $file, "a+" );
	flock( $fp, 2 );
	fwrite( $fp, $content );
	fclose( $fp );
}

@set_time_limit( 0 );
require_once( "_inc.php" );
$pageSize = 1000;
$dataDir = "../#data/db/";
if ( !empty( $_POST['btnSubmit'] ) )
{
	if ( !count( $_POST['arrTables'] ) )
	{
		$tpl->assign( "msg", "请选择要备份的数据表。" );
		$tpl->assign( "backUrl", "db_export.php" );
		$tpl->display( "_msg.tpl" );
		exit( );
	}
	if ( !file_exists( $dataDir ) )
	{
		$tpl->assign( "msg", "数据备份目录 ".$dataDir." 不存在。" );
		$tpl->assign( "backUrl", "db_export.php" );
		$tpl->display( "_msg.tpl" );
		exit( );
	}
	if ( !is_writeable( $dataDir ) )
	{
		$tpl->assign( "msg", "数据备份目录 ".$dataDir." 不不可写。" );
		$tpl->assign( "backUrl", "db_export.php" );
		$tpl->display( "_msg.tpl" );
		exit( );
	}
	$filename = date( "Ymd-His" ).".sql";
	$file = $dataDir.$filename;
	$i = 0;
	for ( ;	$i < count( $_POST['arrTables'] );	++$i	)
	{
		$table = $_POST['arrTables'][$i];
		$recCount = $db->fetchone( "SELECT COUNT(*) FROM `".$table."`" );
		$pageCount = ceil( $recCount / $pageSize );
		$pageIndex = 1;
		for ( ;	$pageIndex <= $pageCount;	++$pageIndex	)
		{
			$recFrom = ( $pageIndex - 1 ) * $pageSize;
			$arr = $db->fetchrows( "SELECT * FROM `".$table."` LIMIT {$recFrom}, {$pageSize}" );
			$rowsCount = count( $arr );
			if ( !( 0 < $rowsCount ) )
			{
				continue;
			}
			$j = 0;
			for ( ;	$j < $rowsCount;	++$j	)
			{
				$arrValues = array( );
				foreach ( $arr[$j] as $value )
				{
					if ( NULL === $value )
					{
						$arrValues[] = "NULL";
					}
					else
					{
						$value = "'".addslashes( $value )."'";
						$value = str_replace( "\r", "\\r", $value );
						$value = str_replace( "\n", "\\n", $value );
						$arrValues[] = $value;
					}
				}
				writesql( $file, "REPLACE INTO `".$table."` VALUES (".implode( ", ", $arrValues ).");\n" );
			}
		}
		writesql( $file, "\n" );
	}
	$filename = eregi_replace( ".sql\$", ".zip", $filename );
	require_once( $dRootDir."inc/classes/phpzip.php" );
	$zip = new phpzip( );
	$zip->zip( $file, $dataDir.$filename );
	@unlink( $file );
	$tpl->assign( "msg", "数据备份成功！<br/>备份文件为：<a href='download.php?action=db&file=".$filename."'>{$filename}</a>" );
	$tpl->assign( "backUrl", "db_export.php" );
	$tpl->display( "_msg.tpl" );
	exit( );
}
$arr = $db->fetchrows( "SHOW TABLE STATUS" );
$tpl->assign( "arr", $arr );
$tpl->display( );
?>
