<?php
/**
 * Copyright (C) 2009  Honghao Geng (genghonghao@gmail.com)
 * $Id: data.php 196 2009-10-07 16:08:47Z genghonghao $
 */

define('IN_ADMIN', TRUE);

require_once dirname(__FILE__) . '/includes/init.php';
require_once GEN_ROOT . '/languages/' . $_CONF['lang'] . '/admin/content.lang.php';
$image = new image();

// 验证用户是否登录
if (false === verify_user()) {;
    header("Location: ../login.php");
}

$tpl->assign('lang', $lang);

$action = isset($_REQUEST['act']) ? $_REQUEST['act'] : 'data_backup';

// 获得当前页面的完整URL
$current_page_url = $base_url . '/' . $current_file . '?' . get_uri_param_string();

$tpl->assign('current_page_url', $current_page_url);
$tpl->assign('base_root_url', $base_root_url);

// 数据备份
if ($action == 'data_backup') {
    @set_time_limit($_CONF['memory_limit']);
    if (!empty($_CONF['memory_limit'])) {
        @ini_set('memory_limit', $_CONF['memory_limit']);
    }
    // 备份数据
    if (isset($_REQUEST['sub_db_backup']) && !empty($_REQUEST['sub_db_backup'])) {

        $export_data = get_export_header();

        if (isset($_REQUEST['text_data_type'])) {
            $what = 'sql';
        } else {
            $what = 'sql';
        }
        if (isset($_REQUEST['table_select']) && is_array($_REQUEST['table_select'])) {
            $tabs = $_REQUEST['table_select'];
            foreach ($tabs AS $item) {
                $export_data .= get_table_structure($item);
                $export_data .= get_table_data($item);
            }
        } else {

        }

        $file_name =  'smartgoon_data_' . date("Ymdhis") . '.' . $what;
        // 强制下载
        header("Content-Type: application/force-download");
        // 下载保存的文件名
        header("Content-Disposition: attachment; filename=$file_name");
        echo $export_data;
        exit;
    }
    // 所在位置
    $location_link = array("<a href='data.php'>" . $lang['5_data_setup']['name'] . "</a>",
        "<a href='data.php?act=$action'>" . $lang['5_data_setup']['data_backup'] . "</a>"
    );
    // 相关操作
    $location_other = array("<a class='realbutton' href='data.php?act=database_sql'>" . $lang['5_data_setup']['database_sql'] . "</a>",
        "<a class='realbutton' href='data.php?act=database_optimize'>" . $lang['5_data_setup']['database_optimize'] . "</a>",
        "<a class='realbutton' href='data.php?act=data_import'>" . $lang['5_data_setup']['data_import'] . "</a>"
    );

    // 取出所有的数据表
    $tas = $db->result("SHOW TABLES");
    $tables = array();
    foreach($tas as $val) {
        if (is_array($val)) {
            foreach($val as $item) {
                if ($item != strtolower($db->get_table('TB_SESSIONS'))) {
                    $tables[] = $item;
                }
            }
        }
    }

    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->assign('tabs', $tables);
    $tpl->display('database_backup.html');
}

// 数据导入
if ($action == 'data_import') {

// 恢复备份的数据
    if (isset($_REQUEST['sub_db_import']) && !empty($_REQUEST['sub_db_import'])) {

    // 如果是安全模式，检查目录是否存在
        if (ini_get('safe_mode') == 1 && (!file_exists('../' . BACKUP_DIR . '/'.date('Ym')) || !is_dir('../' . BACKUP_DIR . '/'.date('Ym')))) {
            if (@!mkdir('../' . BACKUP_DIR . '/'.date('Ym'), 0777)) {
                $warning = sprintf($_LANG['safe_mode_warning'], '../' . BACKUP_DIR . '/'.date('Ym'));
                $tpl->assign('warning', $warning);
            }
        }

        // 如果目录存在但不可写，提示用户
        elseif (file_exists('../' . BACKUP_DIR . '/'.date('Ym')) && file_mode_info('../' . BACKUP_DIR . '/'.date('Ym')) < 2) {
            $warning = sprintf($_LANG['not_writable_warning'], '../' . BACKUP_DIR . '/'.date('Ym'));
            $tpl->assign('warning', $warning);
        }

        /* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
        if (isset($_FILES['upfile']['error'])) {
        // 最大上传文件大小
            $php_maxsize = ini_get('upload_max_filesize');
            $htm_maxsize = '2M';

            // 上传的文件错误检查
            if ($_FILES['upfile']['error'] == 0) {

                if ('text/plain' != $_FILES['upfile']['type'] && 'application/octet-stream' != $_FILES['upfile']['type']) {
                    sys_msg('ERROR: Upload file not legal', 1, array(), false);
                }
            }
            else {
                sys_msg(sprintf($lang['upfile_img_too_big'], $php_maxsize), 1, array(), false);
            }

            // 检查文件是否是合法的SQL文件
            if (substr($_FILES['upfile']['name'], -3) != 'sql') {
                sys_msg(sprintf($lang['notice_upload_file_type']), 1, array(), false);
            }
            // 处理上传的文件
            $file = '../' . BACKUP_DIR . '/'.date('Ym') . $_FILES['upfile']['name'];
            if ($_FILES['upfile']['tmp_name'] != '' && $_FILES['upfile']['tmp_name'] != 'none') {
                $move_file   = @move_uploaded_file ($_FILES['upfile']['tmp_name'], $file);
                if ($move_file === false) {
                    sys_msg('ERROR: File upload failure', 1, array(), false);
                }
            }
            $exec_sql = file($file);
            $new_sql = '';
            foreach ($exec_sql AS $item) {
                if (trim($item) != '' && substr($item, 0, 1) != '-') {
                    $new_sql .= $item;
                }
            }
            $last_sql = explode(';', $new_sql);
            $result['success'] = 0;
            $result['failure'] = 0;
            foreach($last_sql AS $sql) {
                $query = $db->query($sql, '', 1);
                if ($query !== false) {
                    $result['success']++;
                } else {
                    $result['failure']++;
                }
            }
            $tpl->assign('notice_import_data', $lang['notice_import_data']);
        }
    }

    // 所在位置
    $location_link = array("<a href='data.php'>" . $lang['5_data_setup']['name'] . "</a>",
        "<a href='data.php?act=$action'>" . $lang['5_data_setup']['data_backup'] . "</a>"
    );
    // 相关操作
    $location_other = array("<a class='realbutton' href='data.php?act=database_sql'>" . $lang['5_data_setup']['database_sql'] . "</a>",
        "<a class='realbutton' href='data.php?act=database_optimize'>" . $lang['5_data_setup']['database_optimize'] . "</a>",
        "<a class='realbutton' href='data.php?act=data_backup'>" . $lang['5_data_setup']['data_backup'] . "</a>"
    );

    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->display('database_import.html');
}

// 数据表状态
if ($action == 'database_status') {
// 数据库状态
    if (isset($_REQUEST['type']) && $_REQUEST['type'] == 'db') {
        $query_sql_result = $db->result("SHOW variables");

        // 分页数据
        $total = count($query_sql_result);
        $perpage = 15;
        if (!isset($_REQUEST['page']) || is_int($_REQUEST['page'])) {
            $p = 0;
        }
        else {
            $p = ((int)$_REQUEST['page'] - 1) * $perpage;
            if ($p >= $total) {
                $p = 0;
            }
        }


        // 读表头数据
        if (isset($query_sql_result[0])) {
            $tpl->assign('table_header', (array_keys($query_sql_result[0])));
        }

        // 分页
        require GEN_ROOT . 'includes/page.class.php';
        $page = new page(array('total'=>$total,'perpage'=>$perpage));
        $tpl->assign('page', $page->show(4));
        $tpl->assign('query_result', array_slice($query_sql_result, $p, $perpage));
    }
    // 数据表状态
    if (isset($_REQUEST['type']) && $_REQUEST['type'] == 'tb') {
        $tabname = trim($_REQUEST['val']);
        $tpl->assign('tabname', $tabname);

        // 表单数据
        $query_sql_result = $db->result("SHOW FULL COLUMNS FROM $tabname");
        // 读表头数据
        if (isset($query_sql_result[0])) {
            $tpl->assign('table_header', (array_keys($query_sql_result[0])));
        }

        // 索引数据
        $index_sql_result = $db->result("SHOW INDEX FROM $tabname");
        if (isset($index_sql_result[0])) {
            $tpl->assign('index_header', (array_keys($index_sql_result[0])));
        }

        $tpl->assign('index_result', $index_sql_result);
        $tpl->assign('query_result', $query_sql_result);
    }

    // 所在位置
    $location_link = array("<a href='data.php'>" . $lang['5_data_setup']['name'] . "</a>",
        "<a href='data.php?act=$action'>" . $lang['5_data_setup']['database_status'] . "</a>"
    );
    // 相关操作
    $location_other = array("<a class='realbutton' href='data.php?act=data_backup'>" . $lang['5_data_setup']['data_backup'] . "</a>",
        "<a class='realbutton' href='data.php?act=data_import'>" . $lang['5_data_setup']['data_import'] . "</a>"
    );

    // 取出所有的数据表
    $tas = $db->result("SHOW TABLES");
    $tables = array();
    foreach($tas as $val) {
        if (is_array($val)) {
            foreach($val as $item) {
                $tables[] = $item;
            }
        }
    }
    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->assign('tabs', $tables);
    $tpl->display('database_status.html');
}

// 数据表优化
if ($action == 'database_optimize') {
// 所在位置
    $location_link = array("<a href='data.php'>" . $lang['5_data_setup']['name'] . "</a>",
        "<a href='data.php?act=$action'>" . $lang['5_data_setup']['database_optimize'] . "</a>"
    );
    // 相关操作
    $location_other = array("<a class='realbutton' href='data.php?act=data_backup'>" . $lang['5_data_setup']['data_backup'] . "</a>",
        "<a class='realbutton' href='data.php?act=data_import'>" . $lang['5_data_setup']['data_import'] . "</a>"
    );

    // 取出所有的数据表
    $tas = $db->result("SHOW TABLES");
    $tables = array();
    foreach($tas as $val) {
        if (is_array($val)) {
            foreach($val as $item) {
                $tables[] = $item;
            }
        }
    }

    $tpl->assign('table_header', array('Table', 'Op', 'Msg_type', 'Msg_text'));
    $check_list = array();
    $list       = array();

    // 检查表
    if (isset($_REQUEST['sub_check'])) {
        foreach($tables as $item) {
            $list = $db->result("CHECK TABLE `$item`");
            $check_list[] = $list[0];
        }

        $tpl->assign('data_list', $check_list);
    }

    // 分析表
    if (isset($_REQUEST['sub_analyze'])) {
        foreach($tables as $item) {
            $list = $db->result("ANALYZE TABLE `$item`");
            $check_list[] = $list[0];
        }

        $tpl->assign('data_list', $check_list);
    }

    // 修复表
    if (isset($_REQUEST['sub_repair'])) {
        foreach($tables as $item) {
            $list = $db->result("REPAIR TABLE `$item`");
            $check_list[] = $list[0];
        }

        $tpl->assign('data_list', $check_list);
    }

    // 优化表
    if (isset($_REQUEST['sub_optimize'])) {
        foreach($tables as $item) {
            $list = $db->result("OPTIMIZE TABLE `$item`");
            $check_list[] = $list[0];
        }

        $tpl->assign('data_list', $check_list);
    }

    // 强制更新资料表
    if (isset($_REQUEST['sub_flush'])) {
        $i = 0;
        foreach($tables as $item) {
            $query = $db->query("FLUSH TABLE `$item`", '', 1);
            if (false !== $query) {
                $check_list[$i][] = $item;
                $check_list[$i][] = 'OK';
            } else {
                $check_list[$i] = $item;
                $check_list[$i] = 'Failure';
            }
            $i++;
        }
        $tpl->assign('data_status', '1');
        $tpl->assign('data_list', $check_list);
    }

    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->display('database_optimize.html');
}

// 执行SQL语句
elseif ($action == 'database_sql') {
// 所在位置
    $location_link = array("<a href='data.php'>" . $lang['5_data_setup']['name'] . "</a>",
        "<a href='data.php?act=$action'>" . $lang['5_data_setup']['database_sql'] . "</a>"
    );
    // 相关操作
    $location_other = array("<a class='realbutton' href='data.php?act=database_optimize'>" . $lang['5_data_setup']['database_optimize'] . "</a>",
        "<a class='realbutton' href='data.php?act=data_backup'>" . $lang['5_data_setup']['data_backup'] . "</a>",
        "<a class='realbutton' href='data.php?act=data_import'>" . $lang['5_data_setup']['data_import'] . "</a>"
    );

    // 执行SQL查询动作
    if (isset($_REQUEST['sql_code']) && !empty($_REQUEST['sql_code'])) {

        $sql_code = stripslashes(urldecode(trim($_REQUEST['sql_code'])));
        $tpl->assign('sql_code', $sql_code);
        $sql_code_upper = strtoupper($sql_code);

        // 数据插入操作
        if (false !== strpos($sql_code_upper, 'INSERT')) {
            $query = $db->query($sql_code, '', 1);
            if (false === $query) {
                $tpl->assign('notice_data', sprintf($lang['notice_sql_failter'], $sql_code));
            } else {
                $tpl->assign('notice_data', sprintf($lang['notice_sql_success'], $sql_code));
            }
        }
        // 数据更新操作
        elseif (false !== strpos($sql_code_upper, 'UPDATE')) {
            $query = $db->query($sql_code, '', 1);
            if (false === $query) {
                $tpl->assign('notice_data', sprintf($lang['notice_sql_failter'], $sql_code));
            } else {
                $tpl->assign('notice_data', sprintf($lang['notice_sql_success'], $sql_code));
            }
        }
        // 删除操作
        elseif (false !== strpos($sql_code_upper, 'DELETE')) {
            $query = $db->query($sql_code, '', 1);
            if (false === $query) {
                $tpl->assign('notice_data', sprintf($lang['notice_sql_failter'], $sql_code));
            } else {
                $tpl->assign('notice_data', sprintf($lang['notice_sql_success'], $sql_code));
            }
        }
        // 数据查询操作
        elseif (false !== strpos($sql_code_upper, 'SELECT')) {
            $query = $db->query($sql_code, '', 1);
            if (false === $query) {
                $query_sql_result = array();
                $tpl->assign('notice_data', sprintf($lang['notice_data'], 'SELECT'));
            } else {
                $query_sql_result = $db->fetch_array($query);
            }

            // 分页数据
            $total = count($query_sql_result);
            $perpage = 15;
            if (!isset($_REQUEST['page']) || is_int($_REQUEST['page'])) {
                $p = 0;
            }
            else {
                $p = ((int)$_REQUEST['page'] - 1) * $perpage;
                if ($p >= $total) {
                    $p = 0;
                }
            }

            // 读表头数据
            if (isset($query_sql_result[0])) {
                $tpl->assign('table_header', (array_keys($query_sql_result[0])));
            }

            // 分页
            require GEN_ROOT . 'includes/page.class.php';
            $page = new page(array('total'=>$total,'perpage'=>$perpage));
            $tpl->assign('page', $page->show(4));
            $tpl->assign('query_result', array_slice($query_sql_result, $p, $perpage));
        }
        // SHOW操作
        elseif (false !== strpos($sql_code_upper, 'SHOW')) {
            $query = $db->query($sql_code, '', 1);
            if (false === $query) {
                $query_sql_result = array();
                $tpl->assign('notice_data', sprintf($lang['notice_data'], 'SHOW'));
            } else {
                $query_sql_result = $db->fetch_array($query);
            }

            // 分页数据
            $total = count($query_sql_result);
            $perpage = 15;
            if (!isset($_REQUEST['page']) || is_int($_REQUEST['page'])) {
                $p = 0;
            }
            else {
                $p = ((int)$_REQUEST['page'] - 1) * $perpage;
                if ($p >= $total) {
                    $p = 0;
                }
            }


            // 读表头数据
            if (isset($query_sql_result[0])) {
                $tpl->assign('table_header', (array_keys($query_sql_result[0])));
            }

            // 分页
            require GEN_ROOT . 'includes/page.class.php';
            $page = new page(array('total'=>$total,'perpage'=>$perpage));
            $tpl->assign('page', $page->show(4));
            $tpl->assign('query_result', array_slice($query_sql_result, $p, $perpage));
        }

        // describe
        elseif (false !== strpos($sql_code_upper, 'DESCRIBE')) {
            $query = $db->query($sql_code, '', 1);
            if (false === $query) {
                $query_sql_result = array();
                $tpl->assign('notice_data', sprintf($lang['notice_data'], 'DESCRIBE'));
            } else {
                $query_sql_result = $db->fetch_array($query);
            }

            // 分页数据
            $total = count($query_sql_result);
            $perpage = 15;
            if (!isset($_REQUEST['page']) || is_int($_REQUEST['page'])) {
                $p = 0;
            }
            else {
                $p = ((int)$_REQUEST['page'] - 1) * $perpage;
                if ($p >= $total) {
                    $p = 0;
                }
            }

            // 读表头数据
            if (isset($query_sql_result[0])) {
                $tpl->assign('table_header', (array_keys($query_sql_result[0])));
            }

            // 分页
            require GEN_ROOT . 'includes/page.class.php';
            $page = new page(array('total'=>$total,'perpage'=>$perpage));
            $tpl->assign('page', $page->show(4));
            $tpl->assign('query_result', array_slice($query_sql_result, $p, $perpage));
        }

        // 其它操作都为不合法的操作
        else {
            $tpl->assign('notice_data', sprintf($lang['notice_data'], 'SQL'));
        }

    }

    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->display('database_sql.html');
}
?>