<?php

$size = abs(intval($_GET['size']));
$c_tabid = $_GET['c_tabid'];
$tabs = $_GET['tabs'];
$dir = $_GET['dir'];
$rid = $_GET['rid'];
$sumfile = $_GET['sumfile'];
$bakdir = ABSPATH . 'backup/' . $dir . '/';
is_array($tabs) or yun_error('至少选择一个表');
$size < 100 && yun_error('不能少于100K');
if (!mkdirs($bakdir))
    yun_error('无法创建存储目录!');
write_file($bakdir . 'index.html', '0');
$filesize = $size * 1024;
/**
 * 初始化
 */
$bak = '';
if ($c_tabid == 0 && $sumfile == 1)
{
    $bak = '-- ' . htmlspecialchars($conf['sys_webname'][LANG]) . ' 系统数据备份 ' . "\n";
    $bak .= '-- 生成日期:' . date('y/m/d H:i', TIME) . "\n";
    $bak .= '-- ----------------------------------------' . "\n";
    $bak .= '-- 警告!修改本文件的任何部分,将有可能导致恢复失败!' . "\n";
    $bak .= '-- ----------------------------------------' . "\n\n";
    $bak .= "DROP TABLE IF EXISTS `" . $tabs[$c_tabid] . "`;\n\n";
    $result = $db->query("SHOW CREATE TABLE " . $tabs[$c_tabid]);
    $row = $db->fetch_row($result);
    $bak .= $row[1] . ";\n\n";
}
do
{
    $result = $db->query("select * from " . $tabs[$c_tabid]);
    $listnum = $db->num_fields($result);
    $rownum = $db->num_rows($result);
    while ($rid < $rownum)
    {
        $db->data_seek($result, $rid);
        $row = $db->fetch_row($result);
        $bak .= 'INSERT INTO ' . $tabs[$c_tabid] . ' VALUES(';
        $arr = array();
        for ($i = 0; $i < $listnum; $i++)
        {
            $arr[] = "'" . mysql_escape_string($row[$i]) . "'";
        }
        $bak .= implode(',', $arr) . ");\n\n";
        $rid++;
        if (strlen($bak) >= $filesize)
        {
            /**
             * 写入备份
             */
            write_file($bakdir . $sumfile++ . '.php', $bak);
            /**
             * 进行下一个备份URL
             */
            $arr = array();
            foreach ($tabs as $v)
            {
                $arr[] = 'tabs[]=' . urlencode($v);
            }
            $url = RPM . 'sqlbackup.html?' . implode('&', $arr) . '&sumfile=' . $sumfile .
                '&rid=' . $rid . '&c_tabid=' . $c_tabid . '&dir=' . urlencode($dir) . '&size=' .
                $size;

            echo 'yun_send("' . $url . '");';
            exit;
        }
    }
    if (!isset($tabs[++$c_tabid]))
    {
        /**
         * 备份结束
         */
        write_file($bakdir . $sumfile . '.php', $bak);
        yun_succeed('成功备份', url(RPGM . 'sql/'));
    }
    $bak .= "DROP TABLE IF EXISTS `" . $tabs[$c_tabid] . "`;\n\n";
    $result = $db->query("SHOW CREATE TABLE " . $tabs[$c_tabid]);
    $row = $db->fetch_row($result);
    $bak .= $row[1] . ";\n\n";
    $rid = 0;
} while (true);

?>