<?php
//程序安装文件
error_reporting(0);
date_default_timezone_set("PRC");
$databaseFile = '../config.php';//数据库配额文件

@header('Content-Type: text/html; charset=UTF-8');
$step = isset($_GET['step']) ? $_GET['step'] : 1;
if (file_exists('install.lock')) {
    exit('你已经成功安装，如需重新安装，请手动删除install目录下install.lock文件！');
}

function clearpack()
{
    $array = glob('../spdns_release*');
    foreach ($array as $dir) {
        unlink($dir);
    }
    $array = glob('../spdns_update*');
    foreach ($array as $dir) {
        unlink($dir);
    }
}

function random($length, $numeric = 0)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed[mt_rand(0, $max)];
    }
    return $hash;
}

if ($step == 3) {
    if ($_GET['jump'] == 1) {
        include '../config.php';
        if (!$dbconfig['user'] || !$dbconfig['pwd'] || !$dbconfig['dbname']) {
            $errorMsg = '请先填写好数据库并保存后再安装！';
        }
    } else {
        $host = isset($_POST['host']) ? $_POST['host'] : null;
        $port = isset($_POST['port']) ? $_POST['port'] : null;
        $user = isset($_POST['user']) ? $_POST['user'] : null;
        $pwd = isset($_POST['pwd']) ? $_POST['pwd'] : null;
        $database = isset($_POST['database']) ? $_POST['database'] : null;
        $dbqz = isset($_POST['dbqz']) ? $_POST['dbqz'] : null;
        if (empty($host) || empty($port) || empty($user) || empty($pwd) || empty($database) || empty($dbqz)) {
            $errorMsg = '请填写完整所有数据库信息！';
        }
        $dbconfig = array(
            'host' => $host,
            'port' => $port,
            'user' => $user,
            'pwd' => $pwd,
            'dbname' => $database,
            'dbqz' => $dbqz
        );
        $config = "<?php
    /*数据库配置*/
    \$dbconfig=array(
        'host' => '{$host}', //数据库服务器
        'port' => {$port}, //数据库端口
        'user' => '{$user}', //数据库用户名
        'pwd' => '{$pwd}', //数据库密码
        'dbname' => '{$database}', //数据库名
        'charset' => 'utf8mb4', // 字符集
        'dbqz' => '{$dbqz}' //数据表前缀
    );
    ";
    }
    if (empty($errorMsg)) {
        try {
            $DB = new PDO("mysql:host=" . $dbconfig['host'] . ";dbname=" . $dbconfig['dbname'] . ";port=" . $dbconfig['port'], $dbconfig['user'], $dbconfig['pwd']);
        } catch (Exception $e) {
            if ($e->getCode() == 2002) {
                $errorMsg = '连接数据库失败：数据库地址填写错误！';
            } elseif ($e->getCode() == 1045) {
                $errorMsg = '连接数据库失败：数据库用户名或密码填写错误！';
            } elseif ($e->getCode() == 1049) {
                $errorMsg = '连接数据库失败：数据库名不存在！';
            } else {
                $errorMsg = '连接数据库失败：' . $e->getMessage();
            }
        }
        if (empty($errorMsg)) {
            $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
            $DB->exec("set sql_mode = ''");
            $DB->exec("set names utf8");
            $mysqlversion = $DB->query("select version()")->fetchColumn();
            if (version_compare($mysqlversion, '5.5.3', '<')) {
                $errorMsg = 'MySQL数据库版本太低，需要MySQL 5.6或以上版本！';
            }
            if (!$_GET['jump'] && !file_put_contents($databaseFile, $config)) {
                $errorMsg = '保存失败，请确保网站根目录有写入权限';
            }
        }
    }
} elseif ($step == 4) {
    include '../config.php';
    if (!$dbconfig['user'] || !$dbconfig['pwd'] || !$dbconfig['dbname']) {
        $errorMsg = '请先填写好数据库并保存后再安装！';
    } else {
        try {
            $DB = new PDO("mysql:host=" . $dbconfig['host'] . ";dbname=" . $dbconfig['dbname'] . ";port=" . $dbconfig['port'], $dbconfig['user'], $dbconfig['pwd']);
        } catch (Exception $e) {
            $errorMsg = '连接数据库失败：' . $e->getMessage();
        }
        if (empty($errorMsg) && !$_GET['jump']) {
            $dbqz = $dbconfig['dbqz'];
            $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
            $DB->exec("set sql_mode = ''");
            $DB->exec("set names utf8");
            $sqls = file_get_contents('install.sql');
            $sqls = explode(';', $sqls);
            $sqls[] = "INSERT INTO `" . $dbqz . "_api_manager` (`a_id`, `a_key`) VALUES ('web_apikey', '" . random(32) . "')";
            $success = 0;
            $error = 0;
            $errorMsg = null;

            foreach ($sqls as $value) {
                $value = trim($value);
                if (empty($value))
                    continue;
                $value = str_replace('sp', $dbqz, $value);
                if ($DB->exec($value) === false) {
                    $error++;
                    $dberror = $DB->errorInfo();
                    $errorMsg .= $dberror[2] . "<br>";
                } else {
                    $success++;
                }
            }
        }
        if (empty($errorMsg)) {
            $lock_status = file_put_contents("install.lock", '安装锁');
            clearpack();
            $step = 5;
        }
    }
}

?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title>迅风DNS - 安装程序</title>
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <script src="../assets/js/bootstrap.bundle.min.js"></script>
    <style>
        .wizard-step {
            display: none;
        }

        .wizard-step.active {
            display: block;
        }

        .wizard-footer {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title mb-0">迅风DNS - 安装程序</h4>
                    </div>
                    <div class="card-body">

                        <div id="progrss-wizard" class="twitter-bs-wizard">
                            <ul class="twitter-bs-wizard-nav nav nav-pills nav-justified" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <a href="#step1" class="nav-link" data-bs-toggle="tab"
                                        aria-selected="<?php echo $step == 1 ? 'true' : 'false'; ?>" role="tab"
                                        tabindex="<?php echo $step == 1 ? '0' : '-1'; ?>">
                                        <div class="step-icon" data-bs-toggle="tooltip" data-bs-placement="top"
                                            aria-label="安装环境检测" data-bs-original-title="安装环境检测">
                                            <i class="bx bx-list-ul"></i>
                                        </div>
                                    </a>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <a href="#step2" class="nav-link" data-bs-toggle="tab"
                                        aria-selected="<?php echo $step == 2 ? 'true' : 'false'; ?>" role="tab"
                                        tabindex="<?php echo $step == 2 ? '0' : '-1'; ?>">
                                        <div class="step-icon" data-bs-toggle="tooltip" data-bs-placement="top"
                                            aria-label="MYSQL数据库信息配置" data-bs-original-title="MYSQL数据库信息配置">
                                            <i class="bx bx-book-bookmark"></i>
                                        </div>
                                    </a>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <a href="#step3" class="nav-link" data-bs-toggle="tab"
                                        aria-selected="<?php echo $step == 3 ? 'true' : 'false'; ?>" role="tab"
                                        tabindex="<?php echo $step == 3 ? '0' : '-1'; ?>">
                                        <div class="step-icon" data-bs-toggle="tooltip" data-bs-placement="top"
                                            aria-label="保存数据库配置" data-bs-original-title="保存数据库配置">
                                            <i class="bx bxs-file"></i>
                                        </div>
                                    </a>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <a href="#step4" class="nav-link" data-bs-toggle="tab"
                                        aria-selected="<?php echo $step == 4 ? 'true' : 'false'; ?>" role="tab"
                                        tabindex="<?php echo $step == 4 ? '0' : '-1'; ?>">
                                        <div class="step-icon" data-bs-toggle="tooltip" data-bs-placement="top"
                                            aria-label="安装数据表" data-bs-original-title="安装数据表">
                                            <i class="bx bxs-bank"></i>
                                        </div>
                                    </a>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <a href="#step5" class="nav-link" data-bs-toggle="tab"
                                        aria-selected="<?php echo $step == 5 ? 'true' : 'false'; ?>" role="tab"
                                        tabindex="<?php echo $step == 5 ? '0' : '-1'; ?>">
                                        <div class="step-icon" data-bs-toggle="tooltip" data-bs-placement="top"
                                            aria-label="安装完成" data-bs-original-title="安装完成">
                                            <i class="bx bx-check-circle"></i>
                                        </div>
                                    </a>
                                </li>
                            </ul>
                            <!-- wizard-nav -->

                            <div id="bar" class="progress mt-4">
                                <div class="progress-bar bg-success progress-bar-striped progress-bar-animated"
                                    style="width: <?php echo ($step - 1) * 20 ?>%;"></div>
                            </div>
                            <div class="tab-content twitter-bs-wizard-tab-content">
                                <?php if ($step == 1) { ?>
                                    <div class="tab-pane fade show <?php echo $step == 1 ? 'active' : ''; ?>" id="step1"
                                        role="tabpanel">
                                        <div class="text-center mb-4">
                                            <h5>安装环境检测</h5>
                                            <p class="card-title-desc">请确保您的服务器环境符合以下要求</p>
                                        </div>
                                        <ul class="list-group">
                                            <li class="list-group-item">PHP版本>=7.1
                                                <?php echo $check[3] ?? '<span class="pull-right label label-success">支持</span>'; ?>
                                            </li>
                                            <li class="list-group-item">PDO_MYSQL组件
                                                <?php echo $check[0] ?? '<span class="pull-right label label-success">支持</span>'; ?>
                                            </li>
                                            <li class="list-group-item">CURL组件
                                                <?php echo $check[2] ?? '<span class="pull-right label label-success">支持</span>'; ?>
                                            </li>
                                            <li class="list-group-item">主目录写入权限
                                                <?php echo $check[1] ?? '<span class="pull-right label label-success">支持</span>'; ?>
                                            </li>
                                            <li class="list-group-item">
                                                成功安装后安装文件就会锁定，如需重新安装，请手动删除install目录下install.lock配置文件！</li>
                                            <?php if ($install ?? true)
                                                echo '<li class="list-group-item"><a href="?step=2" class="btn btn-primary">检测通过，下一步</a></li>'; ?>
                                        </ul>
                                    </div>
                                <?php } elseif ($step == 2) { ?>
                                    <div class="tab-pane fade show <?php echo $step == 2 ? 'active' : ''; ?>" id="step2"
                                        role="tabpanel">
                                        <div class="text-center mb-4">
                                            <h5>MYSQ数据库信息配置</h5>
                                            <p class="card-title-desc">请填写您的数据库信息</p>
                                        </div>
                                        <form class="form-horizontal" action="?step=3" method="post">
                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <div class="mb-3">
                                                        <label for="host" class="form-label">数据库地址</label>
                                                        <input type="text" name="host" class="form-control"
                                                            value="localhost" required>
                                                    </div>
                                                </div>
                                                <div class="col-lg-6">
                                                    <div class="mb-3">
                                                        <label for="port" class="form-label">数据库端口</label>
                                                        <input type="text" name="port" class="form-control" value="3306"
                                                            required>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <div class="mb-3">
                                                        <label for="user" class="form-label">数据库用户名</label>
                                                        <input type="text" name="user" class="form-control" required>
                                                    </div>
                                                </div>
                                                <div class="col-lg-6">
                                                    <div class="mb-3">
                                                        <label for="pwd" class="form-label">数据库密码</label>
                                                        <input type="text" name="pwd" class="form-control" required>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <div class="mb-3">
                                                        <label for="database" class="form-label">数据库名称</label>
                                                        <input type="text" name="database" class="form-control" required>
                                                    </div>
                                                </div>
                                                <div class="col-lg-6">
                                                    <div class="mb-3">
                                                        <label for="dbqz" class="form-label">数据表前缀</label>
                                                        <input type="text" name="dbqz" class="form-control" value="sp"
                                                            required>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="mb-3">
                                                        <button type="submit" class="btn btn-primary">确认无误，下一步</button>
                                                    </div>
                                                    <div class="mb-3">
                                                        （如果已事先填写好config.php相关数据库配置，请 <a href="?step=3&jump=1">点击此处</a>
                                                        跳过这一步！）
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                <?php } elseif ($step == 3) { ?>
                                    <div class="tab-pane fade show <?php echo $step == 3 ? 'active' : ''; ?>" id="step3"
                                        role="tabpanel">
                                        <div class="alert alert-danger" role="alert">
                                            <?php echo !empty($errorMsg) ? $errorMsg : '数据库配置文件保存成功！'; ?>
                                        </div>
                                        <?php if (!empty($errorMsg)) { ?>
                                            <div class="mt-3"><a href="javascript:history.back(-1)" class="btn btn-primary"><i
                                                        class="bx bx-chevron-left me-1"></i> 返回上一页</a></div>
                                        <?php } else { ?>
                                            <?php if ($DB->query("select * from " . $dbconfig['dbqz'] . "_config")) { ?>
                                                <div class="mt-3 alert alert-info" role="alert">系统检测到你已安装过迅风DNS</div>
                                                <div class="mt-3"><a href="?step=4&jump=1" class="btn btn-primary">跳过安装数据表</a></div>
                                                <div class="mt-3"><a href="?step=4"
                                                        onclick="if(!confirm('全新安装将会清空所有数据，是否继续？')){return false;}"
                                                        class="btn btn-warning">强制全新安装</a></div>
                                            <?php } else { ?>
                                                <div class="mt-3"><a href="?step=4" class="btn btn-success">立即安装数据表 >></a></div>
                                            <?php } ?>
                                        <?php } ?>
                                    </div>
                                <?php } elseif ($step == 4) { ?>
                                    <div class="tab-pane fade show <?php echo $step == 4 ? 'active' : ''; ?>" id="step4"
                                        role="tabpanel">
                                        <div class="text-center mb-4">
                                            <h5>安装数据表</h5>
                                            <p class="card-title-desc">正在安装数据表...</p>
                                        </div>
                                        <div class="alert alert-danger" role="alert"><?php echo $errorMsg ?? ''; ?></div>
                                        <ul class="pager wizard twitter-bs-wizard-pager-link">
                                            <li class="previous"><a href="javascript:history.back(-1)"
                                                    class="btn btn-primary"><i class="bx bx-chevron-left me-1"></i>
                                                    返回上一页</a></li>
                                            <li class="next"><a href="?step=4" class="btn btn-primary">重试 <i
                                                        class="bx bx-chevron-right ms-1"></i></a></li>
                                        </ul>
                                    </div>
                                <?php } elseif ($step == 5) { ?>
                                    <div class="tab-pane fade show <?php echo $step == 5 ? 'active' : ''; ?>" id="step5"
                                        role="tabpanel">
                                        <div class="text-center mb-4">
                                            <h5>安装完成</h5>
                                            <p class="card-title-desc">成功安装迅风DNS</p>
                                        </div>
                                        <?php if ($success > 0) { ?>
                                            <div class="alert alert-success" role="alert">
                                                成功执行SQL语句<?php echo $success; ?>条，失败<?php echo $error; ?>条！</div><?php } ?>
                                        <ul class="list-group mt-3">
                                            <li class="list-group-item">1、系统已成功安装完毕！</li>
                                            <li class="list-group-item">2、后台地址：<a href="/admin/" target="_blank">/admin/</a>
                                                密码:123456</li>
                                            <li class="list-group-item">3、请及时修改后台管理员密码！</li>
                                            <?php if (!$lock_status) { ?>
                                                <li class="list-group-item">4、<font color="#FF0033">你的空间不支持本地文件读写，请自行在 /install/
                                                        目录建立 install.lock 文件！</font>
                                                </li><?php } ?>
                                            <li class="list-group-item"><a href="/" class="btn btn-primary">进入网站首页</a></li>
                                        </ul>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                    <!-- end card body -->
                </div>
                <!-- end card -->
            </div>
            <!-- end col -->
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const steps = document.querySelectorAll('.twitter-bs-wizard-nav a');
            const step = parseInt(new URLSearchParams(window.location.search).get('step')) || 1;

            steps.forEach((s, index) => {
                if (index + 1 === step) {
                    s.classList.add('active');
                    s.setAttribute('aria-selected', 'true');
                    s.setAttribute('tabindex', '0');
                } else {
                    s.classList.remove('active');
                    s.setAttribute('aria-selected', 'false');
                    s.setAttribute('tabindex', '-1');
                }
            });

            const progressBar = document.querySelector('.progress-bar');
            progressBar.style.width = ((step - 1) * 20) + '%';
        });
    </script>
</body>

</html>