<?php

/**
 * install
 * @package EMLOG
 * @link https://www.emlog.net
 */

const EMLOG_ROOT = __DIR__;

require_once EMLOG_ROOT . '/include/lib/common.php';
header('Content-Type: text/html; charset=UTF-8');
spl_autoload_register("emAutoload");

if (PHP_VERSION < '5.6') {
    emMsg('PHP版本太低，推荐使用PHP7.4及以上版本');
}

$act = Input::getStrVar('action');

$bt_db_host = 'localhost';
$bt_db_username = 'BT_DB_USERNAME';
$bt_db_password = 'BT_DB_PASSWORD';
$bt_db_name = 'BT_DB_NAME';

$env_emlog_env = getenv('EMLOG_ENV');
$env_db_host = getenv('EMLOG_DB_HOST');
$env_db_name = getenv('EMLOG_DB_NAME');
$env_db_user = getenv('EMLOG_DB_USER');
$env_db_password = getenv('EMLOG_DB_PASSWORD');

if (!$act) {
?>
    <!doctype html>
    <html lang="zh-cn">

    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <meta name="renderer" content="webkit">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <meta name="applicable-device" content="pc,mobile">
        <link rel="stylesheet" href="/res/layui/css/layui.css" />
        <title>emlog</title>
        <style>
            .main {
                background-color: #FFFFFF;
                font-size: 12px;
                color: #666666;
                width: 750px;
                margin: 30px auto;
                padding: 50px;
                list-style: none;
            }

            .logo {
                background: url(admin/views/images/logo.png) no-repeat center;
                padding: 50px 0 50px 0;
                margin: 0 0;
            }

            .title {
                text-align: center;
                font-size: 14px;
            }
        </style>
    </head>

    <body>
        <div class="layui-container">
            <div class="layui-row main">
                <p class="logo"></p>
                <p class="title mb20">emlog <?= Option::EMLOG_VERSION ?></p>
            </div>
            <form class="layui-form layui-form-pane" action="" name="form1" method="post"
                action="install.php?action=install">
                <?php if ($env_db_user): ?>
                    <div class="b">
                        <input name="hostname" type="hidden" value="<?= $env_db_host ?>">
                        <input name="dbuser" type="hidden" value="<?= $env_db_user ?>">
                        <input name="dbpasswd" type="hidden" value="<?= $env_db_password ?>">
                        <input name="dbname" type="hidden" value="<?= $env_db_name ?>">
                        <input name="dbprefix" type="hidden" value="emlog_">
                    </div>
                <?php elseif (strpos($bt_db_username, 'BT_DB_') === false): ?>
                    <div class="b">
                        <input name="hostname" type="hidden" value="<?= $bt_db_host ?>">
                        <input name="dbuser" type="hidden" value="<?= $bt_db_username ?>">
                        <input name="dbpasswd" type="hidden" value="<?= $bt_db_password ?>">
                        <input name="dbname" type="hidden" value="<?= $bt_db_name ?>">
                        <input name="dbprefix" type="hidden" value="emlog_">
                    </div>
                <?php else: ?>
                    <div class="layui-card">
                        <div class="layui-card-header">数据库设置</div>
                        <div class="layui-card-body">
                            <div class="layui-form-item">
                                <label class="layui-form-label">数据库类型</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="dbtype" value="mysql" title="Mysql" lay-filter="radio_dbtype">
                                    <input type="radio" name="dbtype" value="sqlite" title="Sqlite" lay-filter="radio_dbtype" checked>
                                </div>
                            </div>
                            <div class="layui-row" id="form_mysql">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">地址</label>
                                    <div class="layui-input-inline">
                                        <input class="layui-input" name="hostname" type="text" class="form-control"
                                            value="localhost" required>
                                    </div>
                                    <div class="layui-form-mid layui-text-em">通常为 localhost 或者指定端口 localhost:3306</div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">用户名</label>
                                    <div class="layui-input-inline">
                                        <input class="layui-input" name="dbuser" type="text" class="form-control" value=""
                                            required>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">密码</label>
                                    <div class="layui-input-inline">
                                        <input class="layui-input" name="dbpasswd" type="password" class="form-control" value=""
                                            required>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">数据库名</label>
                                    <div class="layui-input-inline">
                                        <input class="layui-input" name="dbname" type="text" class="form-control" value=""
                                            required>
                                    </div>
                                    <div class="layui-form-mid layui-text-em">程序不会自动创建数据库，请提前创建一个空数据库或使用已有数据库</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">表前缀</label>
                                    <div class="layui-input-inline">
                                        <input class="layui-input" name="dbprefix" type="text" class="form-control" value="emlog_"
                                            required>
                                    </div>
                                    <div class="layui-form-mid layui-text-em">通常默认即可，不必修改。由英文字母、数字、下划线组成，且必须以下划线结束</div>
                                </div>

                            </div>
                            <div id="form_sqlite" class="">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">数据库名</label>
                                    <div class="layui-input-inline">
                                        <input class="layui-input" name="dbname" type="text" class="form-control" value="myemlog"
                                            required>
                                    </div>
                                    <div class="layui-form-mid layui-text-em">程序不会自动创建数据库，请提前创建一个空数据库或使用已有数据库</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">表前缀</label>
                                    <div class="layui-input-inline">
                                        <input class="layui-input" name="dbprefix" type="text" class="form-control" value="emlog_"
                                            required>
                                    </div>
                                    <div class="layui-form-mid layui-text-em">通常默认即可，不必修改。由英文字母、数字、下划线组成，且必须以下划线结束</div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                <div class="layui-card">
                    <div class="layui-card-header">管理员设置</div>
                    <div class="layui-card-body">
                        <div class="layui-form-item">
                            <label class="layui-form-label">登录名</label>
                            <div class="layui-input-inline">
                                <input class="layui-input" name="username" type="text" class="form-control" value="admin"
                                    required>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">密码</label>
                            <div class="layui-input-inline">
                                <input class="layui-input" name="password" type="text" class="form-control" value="123456"
                                    required>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">重复密码</label>
                            <div class="layui-input-inline">
                                <input class="layui-input" name="repassword" type="text" class="form-control" value="123456"
                                    required>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">邮箱</label>
                            <div class="layui-input-inline">
                                <input class="layui-input" name="email" type="text" class="form-control" value="demo@emlog.my" required>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="submit" class="layui-btn layui-bg-blue" lay-submit
                            lay-filter="install_submit">开始安装</button>
                    </div>
                </div>

            </form>
        </div>
        <div class="footer">Powered by <a href="http://www.emlog.net">emlog</a></div>
        <script src="/res/layui/layui.js"></script>
        <script src="/res/binder.js"></script>
        <script>
            layui.use(['form', 'jquery'], function(form, $) {
                form.render();
                var db_type = 'sqlite';
                $('#form_mysql').hide();
                form.on('radio(radio_dbtype)', function(data) {
                    db_type = data.value;
                    if (db_type == 'mysql') {
                        $('#form_mysql').show();
                        $('#form_sqlite').hide();
                    } else if (db_type == 'sqlite') {
                        $('#form_mysql').hide();
                        $('#form_sqlite').show();
                    }
                    console.log(data.elem); //得到radio原始DOM对象
                    console.log(data.value); //被点击的radio的value值
                });

                function isEmpty(obj) {
                    if (typeof obj == "undefined" || obj == null || obj == "") {
                        return true;
                    } else {
                        return false;
                    }
                }
                // 提交事件
                form.on('submit(install_submit)', function(data) {
                    var field = data.field; // 获取表单字段值
                    var params = {};
                    if (db_type == 'mysql') {
                        params.dbtype = field.dbtype;
                        params.hostname = field.hostname;
                        params.dbname = field.dbname;
                        params.dbuser = field.dbuser;
                        params.dbpasswd = field.dbpasswd;
                        params.dbprefix = field.dbprefix;
                        // layui.each(params, function(index, item) {
                        //     if (isEmpty(item)) {
                        //         layer.msg('【' + index + '】字段为空，请检查！');
                        //     }
                        //     return;
                        // })
                    } else if (db_type == 'sqlite') {
                        params.dbtype = field.dbtype;
                        params.dbname = field.dbname;
                        params.dbprefix = field.dbprefix;
                        // layui.each(params, function(index, item) {
                        //     if (isEmpty(item)) {
                        //         layer.msg('【' + index + '】字段为空，请检查！');
                        //     }
                        //     return;
                        // })
                    }
                    params.username = field.username;
                    params.password = field.password;
                    params.repassword = field.repassword;
                    params.email = field.email;
                    // 此处可执行 Ajax 等操作
                    console.log(params)
                    $.ajax({
                        url: "install.php?action=install",
                        dataType: "json",
                        type: "post",
                        async: "false",
                        //异步方式true：ajax执行后，会直接执行ajax后面的脚本，直到服务器端返回数据后，触发ajax里的success方法，这时候执行的是两个线程。
                        //同步方式false：在没有返回值之前，同步请求将锁住浏览器，用户其它操作必须等待请求完成才可以执行。
                        data: params,
                        success: function(res) {
                            //请求成功时执行
                            console.log(res);
                            if (res.status == 'reinstall') {
                                layui.layer.confirm('已经安装，确定重装？', {
                                    btn: ['确定', '关闭'] //按钮
                                }, function() {
                                    //执行重装程序
                                    reinstall(params);
                                }, function() {
                                    layer.alert('取消安装');
                                });
                            }

                        },
                        error: function(res) {
                            //请求失败时执行
                        }
                    });
                    return false; // 阻止默认 form 跳转
                });

                function reinstall(params) {
                    $.ajax({
                        url: "install.php?action=reinstall",
                        dataType: "json",
                        type: "post",
                        async: "false",
                        //异步方式true：ajax执行后，会直接执行ajax后面的脚本，直到服务器端返回数据后，触发ajax里的success方法，这时候执行的是两个线程。
                        //同步方式false：在没有返回值之前，同步请求将锁住浏览器，用户其它操作必须等待请求完成才可以执行。
                        data: params,
                        success: function(res) {
                            if (res.status == 'ok') {
                                layer.open({
                                    type: 1,
                                    area: ['420px', '240px'], // 宽高
                                    content: res.data
                                });
                            } else {
                                layer.alert('安装失败')
                            }

                        },
                        error: function(res) {
                            //请求失败时执行
                        }
                    });
                }
            });
        </script>
    </body>

    </html>
<?php
}
if ($act == 'install' || $act == 'reinstall') {
    $db_type = $res['db_type'] = Input::postStrVar('dbtype');

    if ($res['db_type'] == 'mysql') {
        $db_host = $res['db_host'] = Input::postStrVar('hostname');
        $db_user = $res['db_user'] = Input::postStrVar('dbuser');
        $db_pw = $res['db_pw'] = Input::postStrVar('dbpasswd');
        $db_name = $res['db_name'] = Input::postStrVar('dbname');
        $db_prefix = $res['db_prefix'] = Input::postStrVar('dbprefix');
        $username = $res['username'] = Input::postStrVar('username');
        $password = $res['password'] = Input::postStrVar('password');
        $repassword = $res['repassword'] = Input::postStrVar('repassword');
        $email = $res['email'] = Input::postStrVar('email');
    } elseif ($res['db_type'] == 'sqlite') {
        $db_name = $res['db_name'] = Input::postStrVar('dbname');
        $db_prefix = $res['db_prefix'] = Input::postStrVar('dbprefix');
        $username = $res['username'] = Input::postStrVar('username');
        $password = $res['password'] = Input::postStrVar('password');
        $repassword = $res['repassword'] = Input::postStrVar('repassword');
        $email = $res['email'] = Input::postStrVar('email');
    }

    if ($db_prefix === '') {
        emMsg('数据库表前缀不能为空!');
    } elseif (!preg_match("/^[\w_]+_$/", $db_prefix)) {
        emMsg('数据库表前缀格式错误!');
    } elseif (!$username || !$password) {
        emMsg('登录名和密码不能为空!');
    } elseif (strlen($password) < 6) {
        emMsg('登录密码不得小于6位');
    } elseif ($password != $repassword) {
        emMsg('两次输入的密码不一致');
    }
    define('DB_TYPE', $db_type);
    if ($res['db_type'] == 'mysql') {
        define('DB_HOST', $db_host);
        define('DB_USER', $db_user);
        define('DB_PASSWD', $db_pw);
        define('DB_NAME', $db_name);
        define('DB_PREFIX', $db_prefix);
    } elseif ($res['db_type'] == 'sqlite') {
        define('DB_NAME', $db_name);
        define('DB_PREFIX', $db_prefix);
        define('DB_HOST', '');
        define('DB_USER', '');
        define('DB_PASSWD', '');
    }

    $DB = Database::getInstance($db_type);
    $CACHE = Cache::getInstance();
    if ($res['db_type'] == 'mysql') {
        $find_blog = "SHOW TABLES LIKE '{$db_prefix}blog'";
    } elseif ($res['db_type'] == 'sqlite') {
        $find_blog = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name = '{$db_prefix}blog'";
    }
    //检测是否为reinstall操作，并检测数据库中是否存在数据表
    if ($act != 'reinstall' && $DB->num_rows($DB->query($find_blog)) == 1) {
        exit(json_encode(['code' => 0, 'status' => 'reinstall', 'data' => '已经安装过了，是否要重装？']));
    }

    if (!is_writable('config.php')) {
        emMsg('配置文件(config.php)不可写，请调整文件读写权限。');
    }
    if (!is_writable(EMLOG_ROOT . '/content/cache')) {
        emMsg('缓存目录（content/cache）不可写。请检查目录读写权限。');
    }

    $PHPASS = new PasswordHash(8, true);

    $config = "<?php\n"
        . "//database type\n"
        . "const DB_TYPE = '$db_type';\n"
        . "//MySQL database host\n"
        . "const DB_HOST = '$db_host';"
        . "\n//Database username\n"
        . "const DB_USER = '$db_user';"
        . "\n//Database user password\n"
        . "const DB_PASSWD = '$db_pw';"
        . "\n//Database name\n"
        . "const DB_NAME = '$db_name';"
        . "\n//Database Table Prefix\n"
        . "const DB_PREFIX = '$db_prefix';"
        . "\n//Auth key\n"
        . "const AUTH_KEY = '" . $PHPASS->HashPassword(getRandStr(32) . md5(getIp()) . getUA() . microtime()) . "';"
        . "\n//Cookie name\n"
        . "const AUTH_COOKIE_NAME = 'EM_AUTHCOOKIE_" . sha1(getRandStr(32, false) . md5(getIp()) . getUA() . microtime()) . "';";

    if (!file_put_contents('config.php', $config)) {
        emMsg('配置文件(config.php)不可写，请调整文件读写权限。');
    }

    $password = $PHPASS->HashPassword($password);

    //$table_charset_sql = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;';
    $table_charset_sql = ';';
    $DB->query("ALTER DATABASE `{$db_name}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;", true);

    $widget_title = serialize(Option::getWidgetTitle());
    $def_widgets = serialize(Option::getDefWidget());
    $def_plugin = serialize(Option::getDefPlugin());

    $apikey = md5(getRandStr(32));

    define('BLOG_URL', realUrl());
    $sql = "
PRAGMA foreign_keys = false;

DROP TABLE IF EXISTS '{$db_prefix}attachment';
CREATE TABLE '{$db_prefix}attachment' (
  'aid' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'alias' text(64) NOT NULL default '',
  'author' integer(11) NOT NULL default '1',
  'sortid' integer(11) NOT NULL default '0',
  'blogid' integer(11) NOT NULL default '0',
  'filename' text(255) NOT NULL default '',
  'filesize' integer(11) NOT NULL default '0',
  'filepath' text(255) NOT NULL default '',
  'addtime' integer(20) NOT NULL default '0',
  'width' integer(11) NOT NULL default '0',
  'height' integer(11) NOT NULL default '0',
  'mimetype' text(40) NOT NULL default '',
  'thumfor' integer(11) NOT NULL default 0,
  'download_count' integer(20) NOT NULL default 0
);

DROP TABLE IF EXISTS '{$db_prefix}blog';
CREATE TABLE '{$db_prefix}blog' (
  'gid' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'title' text(512) NOT NULL default '',
  'date' integer(20) NOT NULL,
  'content' text NOT NULL,
  'excerpt' text NOT NULL,
  'cover' text(2048) NOT NULL default '',
  'alias' text(255) NOT NULL default '',
  'author' integer(11) NOT NULL default '1',
  'sortid' integer(11) NOT NULL default '-1',
  'type' text(20) NOT NULL default 'blog',
  'views' integer(11) NOT NULL default '0',
  'comnum' integer(11) NOT NULL default '0',
  'like_count' integer(11) NOT NULL default '0',
  'attnum' integer(11) NOT NULL default '0',
  'top' text(255) NOT NULL default 'n',
  'sortop' text(255) NOT NULL default 'n',
  'hide' text(255) NOT NULL default 'n',
  'checked' text(255) NOT NULL default 'y',
  'allow_remark' text(255) NOT NULL default 'y',
  'password' text(255) NOT NULL default '',
  'template' text(255) NOT NULL default '',
  'tags' text,
  'link' text(2048) NOT NULL DEFAULT '',
  'feedback' text(2048) NOT NULL DEFAULT '',
  'parent_id' integer(20) NOT NULL DEFAULT '0'
);

INSERT INTO '{$db_prefix}blog' VALUES (1, '欢迎使用emlog', '" . time() . "', '这是系统生成的演示文章。编辑或者删除它，然后开始您的创作吧！', '', '', '', 1, -1, 'blog', 0, 1, 0, 0, 'n', 'n', 'n', 'y', 'y', '', '', NULL, '', '', 0);

DROP TABLE IF EXISTS '{$db_prefix}blog_fields';
CREATE TABLE '{$db_prefix}blog_fields' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'gid' integer(20) NOT NULL DEFAULT '0',
  'field_key' text(255) DEFAULT '',
  'field_value' text
);

DROP TABLE IF EXISTS '{$db_prefix}comment';
CREATE TABLE '{$db_prefix}comment' (
  'cid' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'gid' integer(11) NOT NULL default '0',
  'pid' integer(11) NOT NULL default '0',
  'top' text(255) NOT NULL default 'n',
  'poster' text(20) NOT NULL default '',
  'avatar' text(512) NOT NULL default '',
  'uid' integer(11) NOT NULL default '0',
  'comment' text NOT NULL,
  'mail' text(60) NOT NULL default '',
  'url' text(75) NOT NULL default '',
  'ip' text(128) NOT NULL default '',
  'agent' text(512) NOT NULL default '',
  'hide' text(255) NOT NULL default 'n',
  'like_count' integer(11) NOT NULL default '0',
  'date' integer(20) NOT NULL
);

INSERT INTO '{$db_prefix}comment' VALUES (1, 1, 0, 'n', 'emlog', '', 0, '这是系统生成的演示评论', '', '', '', '', 'n', 0, '" . time() . "');

DROP TABLE IF EXISTS '{$db_prefix}like';
CREATE TABLE '{$db_prefix}like' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'gid' integer(11) NOT NULL default '0',
  'poster' text(20) NOT NULL default '',
  'avatar' text(512) NOT NULL default '',
  'uid' integer(11) NOT NULL default '0',
  'ip' text(128) NOT NULL default '',
  'agent' text(512) NOT NULL default '',
  'date' integer(20) NOT NULL
);

DROP TABLE IF EXISTS '{$db_prefix}link';
CREATE TABLE '{$db_prefix}link' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'sitename' text(255) NOT NULL default '',
  'siteurl' text(255) NOT NULL default '',
  'icon' text(512) NOT NULL default '',
  'description' text(512) NOT NULL default '',
  'hide' text(255) NOT NULL default 'n',
  'taxis' integer(11) NOT NULL default '0'
);

INSERT INTO '{$db_prefix}link' VALUES (1, 'EMLOG', 'https://www.emlog.net', '', 'emlog官方主页', 'n', 0);

DROP TABLE IF EXISTS '{$db_prefix}media_sort';
CREATE TABLE '{$db_prefix}media_sort' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'sortname' text(255) NOT NULL default ''
);

DROP TABLE IF EXISTS '{$db_prefix}navi';
CREATE TABLE '{$db_prefix}navi' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'naviname' text(30) NOT NULL default '',
  'url' text(512) NOT NULL default '',
  'newtab' text(255) NOT NULL default 'n',
  'hide' text(255) NOT NULL default 'n',
  'taxis' integer(11) NOT NULL default '0',
  'pid' integer(11) NOT NULL default '0',
  'isdefault' text(255) NOT NULL default 'n',
  'type' integer(3) NOT NULL default '0',
  'type_id' integer(11) NOT NULL default '0'
);

INSERT INTO '{$db_prefix}navi' VALUES (1, '首页', '', 'n', 'n', 1, 0, 'y', 1, 0);
INSERT INTO '{$db_prefix}navi' VALUES (3, '登录', 'admin', 'n', 'n', 3, 0, 'y', 3, 0);

DROP TABLE IF EXISTS '{$db_prefix}options';
CREATE TABLE '{$db_prefix}options' (
  'option_id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'option_name' text(75) NOT NULL,
  'option_value' text NOT NULL
);

INSERT INTO '{$db_prefix}options' VALUES (1, 'blogname', 'EMLOG');
INSERT INTO '{$db_prefix}options' VALUES (2, 'bloginfo', '使用emlog搭建的站点');
INSERT INTO '{$db_prefix}options' VALUES (3, 'site_title', '');
INSERT INTO '{$db_prefix}options' VALUES (4, 'site_description', '');
INSERT INTO '{$db_prefix}options' VALUES (5, 'site_key', 'emlog');
INSERT INTO '{$db_prefix}options' VALUES (6, 'log_title_style', '0');
INSERT INTO '{$db_prefix}options' VALUES (7, 'blogurl', '" . BLOG_URL . "');
INSERT INTO '{$db_prefix}options' VALUES (8, 'icp', '');
INSERT INTO '{$db_prefix}options' VALUES (10, 'rss_output_num', '10');
INSERT INTO '{$db_prefix}options' VALUES (11, 'rss_output_fulltext', 'y');
INSERT INTO '{$db_prefix}options' VALUES (12, 'index_lognum', '10');
INSERT INTO '{$db_prefix}options' VALUES (13, 'isfullsearch', 'n');
INSERT INTO '{$db_prefix}options' VALUES (14, 'index_comnum', '10');
INSERT INTO '{$db_prefix}options' VALUES (15, 'index_newlognum', '5');
INSERT INTO '{$db_prefix}options' VALUES (16, 'index_hotlognum', '5');
INSERT INTO '{$db_prefix}options' VALUES (17, 'comment_subnum', '20');
INSERT INTO '{$db_prefix}options' VALUES (18, 'nonce_templet', 'default');
INSERT INTO '{$db_prefix}options' VALUES (19, 'admin_style', 'default');
INSERT INTO '{$db_prefix}options' VALUES (20, 'tpl_sidenum', '1');
INSERT INTO '{$db_prefix}options' VALUES (21, 'comment_code', 'n');
INSERT INTO '{$db_prefix}options' VALUES (22, 'comment_needchinese', 'n');
INSERT INTO '{$db_prefix}options' VALUES (23, 'comment_interval', '60');
INSERT INTO '{$db_prefix}options' VALUES (24, 'isgravatar', 'y');
INSERT INTO '{$db_prefix}options' VALUES (25, 'isthumbnail', 'n');
INSERT INTO '{$db_prefix}options' VALUES (26, 'att_maxsize', '2048');
INSERT INTO '{$db_prefix}options' VALUES (27, 'att_type', 'jpg,jpeg,png,gif,zip,rar');
INSERT INTO '{$db_prefix}options' VALUES (28, 'att_imgmaxw', '600');
INSERT INTO '{$db_prefix}options' VALUES (29, 'att_imgmaxh', '370');
INSERT INTO '{$db_prefix}options' VALUES (30, 'comment_paging', 'y');
INSERT INTO '{$db_prefix}options' VALUES (31, 'comment_pnum', '10');
INSERT INTO '{$db_prefix}options' VALUES (32, 'comment_order', 'newer');
INSERT INTO '{$db_prefix}options' VALUES (33, 'iscomment', 'y');
INSERT INTO '{$db_prefix}options' VALUES (34, 'login_comment', 'n');
INSERT INTO '{$db_prefix}options' VALUES (35, 'ischkcomment', 'y');
INSERT INTO '{$db_prefix}options' VALUES (36, 'isurlrewrite', '0');
INSERT INTO '{$db_prefix}options' VALUES (37, 'isalias', 'n');
INSERT INTO '{$db_prefix}options' VALUES (38, 'isalias_html', 'n');
INSERT INTO '{$db_prefix}options' VALUES (39, 'timezone', 'Asia/Shanghai');
INSERT INTO '{$db_prefix}options' VALUES (42, 'custom_widget', 'a:0:{}');
INSERT INTO '{$db_prefix}options' VALUES (44, 'detect_url', 'y');
INSERT INTO '{$db_prefix}options' VALUES (45, 'emkey', '');
INSERT INTO '{$db_prefix}options' VALUES (46, 'login_code', 'n');
INSERT INTO '{$db_prefix}options' VALUES (47, 'email_code', 'n');
INSERT INTO '{$db_prefix}options' VALUES (48, 'is_signup', 'y');
INSERT INTO '{$db_prefix}options' VALUES (49, 'ischkarticle', 'y');
INSERT INTO '{$db_prefix}options' VALUES (50, 'article_uneditable', 'n');
INSERT INTO '{$db_prefix}options' VALUES (51, 'forbid_user_upload', 'n');
INSERT INTO '{$db_prefix}options' VALUES (52, 'posts_per_day', '10');
INSERT INTO '{$db_prefix}options' VALUES (53, 'smtp_mail', '');
INSERT INTO '{$db_prefix}options' VALUES (54, 'smtp_pw', '');
INSERT INTO '{$db_prefix}options' VALUES (55, 'smtp_server', '');
INSERT INTO '{$db_prefix}options' VALUES (56, 'smtp_port', '');
INSERT INTO '{$db_prefix}options' VALUES (57, 'is_openapi', 'n');
INSERT INTO '{$db_prefix}options' VALUES (58, 'apikey', '" . $apikey . "');
INSERT INTO '{$db_prefix}options' VALUES (59, 'panel_menu_title', '');
INSERT INTO '{$db_prefix}options' VALUES (60, 'admin_article_perpage_num', '20');
INSERT INTO '{$db_prefix}options' VALUES (61, 'admin_user_perpage_num', '20');
INSERT INTO '{$db_prefix}options' VALUES (62, 'admin_comment_perpage_num', '20');

DROP TABLE IF EXISTS '{$db_prefix}order';
CREATE TABLE '{$db_prefix}order' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'app_name' text(32) NOT NULL,
  'order_id' text(64) NOT NULL DEFAULT '',
  'order_uid' integer(10) NOT NULL,
  'out_trade_no' text(255) DEFAULT '',
  'pay_type' text(64) NOT NULL DEFAULT '',
  'sku_name' text(64) NOT NULL DEFAULT '',
  'sku_id' integer(11) NOT NULL,
  'price' real(10,2) NOT NULL,
  'pay_price' real(10,2) DEFAULT '0.00',
  'refund_amount' real(10,2) NOT NULL DEFAULT '0.00',
  'update_time' integer(10) NOT NULL,
  'create_time' integer(10) NOT NULL
);

DROP TABLE IF EXISTS '{$db_prefix}sort';
CREATE TABLE '{$db_prefix}sort' (
  'sid' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'sortname' text(255) NOT NULL default '',
  'alias' text(255) NOT NULL default '',
  'taxis' integer(11) NOT NULL default '0',
  'pid' integer(11) NOT NULL default '0',
  'description' text NOT NULL,
  'kw' text(2048) NOT NULL default '',
  'title' text(2048) NOT NULL default '',
  'template' text(255) NOT NULL default '',
  'sortimg' text(512) NOT NULL default '',
  'page_count' integer(11) NOT NULL default '0'
);

DROP TABLE IF EXISTS '{$db_prefix}storage';
CREATE TABLE '{$db_prefix}storage' (
  'sid' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'plugin' text(32) NOT NULL,
  'name' text(32) NOT NULL,
  'type' text(8) NOT NULL,
  'value' text NOT NULL,
  'createdate' integer(11) NOT NULL,
  'lastupdate' integer(11) NOT NULL
);

DROP TABLE IF EXISTS '{$db_prefix}tag';
CREATE TABLE '{$db_prefix}tag' (
  'tid' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'tagname' text(60) NOT NULL default '',
  'description' text(2048) NOT NULL default '',
  'title' text(2048) NOT NULL default '',
  'kw' text(2048) NOT NULL default '',
  'gid' text NOT NULL
);

DROP TABLE IF EXISTS '{$db_prefix}tpl_options_data';
CREATE TABLE '{$db_prefix}tpl_options_data' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'template' text(64) NOT NULL,
  'name' text(64) NOT NULL,
  'depend' text(64) NOT NULL DEFAULT '',
  'data' text NOT NULL
);

DROP TABLE IF EXISTS '{$db_prefix}twitter';
CREATE TABLE '{$db_prefix}twitter' (
  'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'content' text NOT NULL,
  'img' text(255),
  'author' integer(11) NOT NULL default '1',
  'date' integer(20) NOT NULL,
  'replynum' integer(11) NOT NULL default '0',
  'private' text(255) NOT NULL default 'n'
);

DROP TABLE IF EXISTS '{$db_prefix}user';
CREATE TABLE '{$db_prefix}user' (
  'uid' integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  'username' text(32) NOT NULL default '',
  'password' text(64) NOT NULL default '',
  'nickname' text(20) NOT NULL default '',
  'role' text(60) NOT NULL default '',
  'ischeck' text(255) NOT NULL default 'n',
  'photo' text(255) NOT NULL default '',
  'email' text(60) NOT NULL default '',
  'description' text(255) NOT NULL default '',
  'ip' text(128) NOT NULL default '',
  'state' integer(4) NOT NULL default '0',
  'credits' integer(11) NOT NULL default '0',
  'create_time' integer(11) NOT NULL,
  'update_time' integer(11) NOT NULL
);

INSERT INTO '{$db_prefix}user' VALUES (1,'{$username}','{$password}','admin', 'admin','n','','{$email}','','127.0.0.1',0,0, " . time() . ", " . time() . ");
PRAGMA foreign_keys = true;";

    $array_sql = preg_split("/;[\r\n]/", $sql);
    foreach ($array_sql as $sql) {
        $sql = trim($sql);
        if ($sql) {
            $DB->query($sql);
            //echo $sql . '</br>';
        }
    }
    $CACHE->updateCache();
    $result = '';
    $result .= "
        <p style=\"font-size:24px; border-bottom:1px solid #E6E6E6; padding:10px 0px;\">安装成功了🎉</p>
        <p><b>用户名</b>：{$username}</p>
        <p><b>密 码</b>：{$repassword}</p>";
    // if ($env_emlog_env === 'develop' || ($env_emlog_env !== 'develop' && !@unlink('./install.php'))) {
    //     $result .= '<p style="color:#ff0000;margin:10px 20px;">警告：请手动删除根目录下安装文件：install.php</p> ';
    // }
    $result .= "<p style=\"text-align:right;\"><a href=\"./\">访问首页</a> | <a href=\"./admin/\">登录后台</a></p>";
    exit(json_encode(['code' => 0, 'status' => 'ok', 'data' => $result]));
}
?>