<?php
/**
 * @copyright (C)2024-2099 XiaoFeng Provide Technical Support.
 * @author XiaoFeng
 * @website www.ifyzx.com
 * @date 2024年4月21日
 */
// 设置字符集编码、IE文档模式
header('Content-Type:text/html; charset=utf-8');
header('X-UA-Compatible:IE=edge,chrome=1');

// 设置中国时区
date_default_timezone_set('Asia/Shanghai');

// 引入配置文件
$db = require __DIR__ . '/config/database.php';


//执行修改    
if ($_POST) {

    // 数据库配置文件
    $db_path = __DIR__ . @$_POST['config'];

    //纠正路径
    $db = require $db_path;

    // 检查配置文件是否存在
    if (!file_exists($db_path)) {
        die('数据库配置文件不存在，请检查路径是否填写正常！');
    }

    // 要重置的用户名
    $username = @$_POST['username'];

    // 要设置的密码
    $password = @$_POST['password'];

    if (!$username) {
        echo '<script>alert("用户名不能为空！");</script>';
    }

    if (!$password) {
        echo '<script>alert("请输入需要设置的新密码！");</script>';
    }

    if ($username && $password) {
        // 修改密码
        $sql = "UPDATE ay_user SET password='" . md5(md5($password)) . "' where username='$username'";
        if ($db['database']['type'] == 'sqlite' || $db['database']['type'] == 'pdo_sqlite') {
            $conn = get_sqlite(__DIR__ . $db['database']['dbname']);
            $result = $conn->exec($sql) or $conn->lastErrorMsg();
            if ($conn->changes()) {
                echo '<script>alert("恭喜您，重置成功！");</script>';
                echo '<script>alert("请在根目录删除 resetpw.php 文件！");</script>';
            } else {
                echo '<script>alert("重置失败，请核对用户名！(sqlite)");</script>';
            }
        } else {
            $conn = get_mysql($db['database']);
            $result = $conn->query($sql) or mysqli_error($conn);
            if ($conn->affected_rows > 0) {
                echo '<script>alert("恭喜您，重置成功！");</script>';
                echo '<script>alert("请在根目录删除 resetpw.php 文件！");</script>';
            } else {
                echo '<script>alert("重置失败，请核对用户名！(mysql)");</script>';
            }
        }
    }
}

// 连接数据库，接受数据库连接参数，返回数据库连接对象
function get_sqlite($dbfile)
{
    if (extension_loaded('SQLite3')) {
        try {
            $conn = new SQLite3($dbfile);
            $conn->busyTimeout(15 * 1000); // 设置繁忙延迟时间
        } catch (Exception $e) {
            die("读取数据库文件失败：" . iconv('gbk', 'utf-8', $e->getMessage()));
        }
    } else {
        error('未检测到您服务器环境的SQLite3数据库扩展，请检查php.ini中是否已经开启该扩展！');
    }
    return $conn;
}

// 连接数据库，接受数据库连接参数，返回数据库连接对象
function get_mysql($cfg)
{
    if (!extension_loaded('mysqli')) {
        die('未检测到您服务器环境的mysqli数据库扩展，请检查php.ini中是否已经开启该扩展！');
    }
    // 优化>php5.3版本 在win2008以上服务器连接
    if ($cfg['host'] == 'localhost') {
        $cfg['host'] = '127.0.0.1';
    }

    $conn = @new Mysqli($cfg['host'], $cfg['user'], $cfg['passwd'], $cfg['dbname'], $cfg['dbport']);
    if (mysqli_connect_errno()) {
        die("连接数据库服务器失败：" . iconv('gbk', 'utf-8', mysqli_connect_error()));
    }
    $conn->set_charset('utf8'); // 设置编码
    return $conn;
}

// 获取用户名
$sql = 'select username from ay_user';
if ($db['database']['type'] == 'sqlite' || $db['database']['type'] == 'pdo_sqlite') {
    $conn = get_sqlite(__DIR__ . $db['database']['dbname']);
    $result = $conn->query($sql) or $conn->lastErrorMsg();
    $rows = array();
    while (!!$row = $result->fetchArray(1)) {
        if ($row) {
            $out = new \stdClass();
            foreach ($row as $key => $value) {
                $out->$key = $value;
            }
            $row = $out;
        }
        $rows[] = $row;
    }
} else {
    $conn = get_mysql($db['database']);
    $result = $conn->query($sql) or mysqli_error($conn);
    $rows = array();
    if ($conn->affected_rows > 0) {
        while (!!$objects = $result->fetch_object()) {
            $rows[] = $objects;
        }
    }
}
?>

<!doctype html>
<html lang="zh">

<head>
    <meta charset="utf-8">
    <title>PbootCMS - 密码重置</title>
    <style>
        html,
        body {
            height: 80%;
            margin: 0;
            padding: 0;
        }

        h2 {
            margin-bottom: 60px;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            padding-bottom: 50px;
        }

        input {
            width: 180px;
            padding: 10px;
            margin-top: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .form-title {
            text-align: center;
        }

        form {
            background-color: white;
            margin-top: 200px;
            padding: 50px 60px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            width: 320px;
        }

        form p {
            margin-top: 40px;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }

        button {
            background-color: #ff7000;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            width: 150px;
            margin-top: 20px;
            align-self: center;
        }

        button:hover {
            background-color: #e96500;
        }

        footer {
            position: fixed;
            bottom: 0;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 10px 0;
            text-align: center;
        }

        footer a {
            text-decoration: none;
            color: black;
            transition: all 0.3s ease;
        }

        footer a:hover {
            color: #ff7000;
        }
    </style>
</head>

<body>

    <form action="" method="post">
        <div class="form-title">
            <h2>PbootCMS · 密码重置工具</h2>
        </div>
        <p style="display:none;">配置文件：<input type="text" name="config" value="/config/database.php"
                placeholder="请填写数据库配置文件路径"></p>
        <p id="text">本站用户名 ：正在获取...</p>

        <?php foreach ($rows as $k => $v) {} ?>

        <script>
            var username = '<?php echo $v->username;?>';
            var textElement = document.getElementById('text');
            setTimeout(function () {
                textElement.innerHTML = '本站用户名 ：'+username;
            }, 1200);
        </script>

        <p style="display:none;">
            <select style="width: 350px; max-width: 350px;" class="user" name="username">
                <?php
                foreach ($rows as $k => $v) {
                    echo "<option value='" . $v->username . "'>" . $v->username . "</option>";
                }
                ?>
            </select>
        </p>
        <span>设置新密码 ：<input type="text" name="password" placeholder="请输入新密码"></span>
        <p><button type="submit" class="btn btn-info mb-2">修改密码</button></p>
    </form>

    <footer>
        <p style="color: red;">注意：修改密码后请务必在根目录删除 <span style="font-weight: 600;">resetpw.php</span> 文件！</p>
        <a target="_blank" href="https://space.bilibili.com/1100962821">© 2024 小枫社长 Provide Technical Support.</a>
    </footer>

</body>

</html>