SOURCE DOWNLOAD

木漏茶室源码下载中心

整站 PHP 源码:可浏览文件、复制路径、下载单文件或打包 ZIP。

发布版本 v6.25.231 升级后自动生成独立源码包,下载中心只发送这份冻结包 已排除 config.php / 用户数据 / 上传文件 / 升级备份
komorebi-forum 183 个节点 · PHP 8.3.37 · 完整源码 ZIP 1.31 MB
下载完整源码 ZIP 源码包大小:1.31 MB 安装教程 作者主页 免费开源 免费下载 ↓
COMMUNITY DEPLOYMENTS

已经跑起来的木漏茶室

从源码下载中心下载、完成安装并回传验证的站外站点。每个站点只计 1 次部署下载量;已记录站点会实时读取名称、版本、Logo 与在线状态,本机、内网和证书异常站点无法完成回传。

实时检测
2 个站点已部署

已展示全部 2 个站点。

inc/auth.php 20.1 KB · 发布包 v6.25.231
下载
<?php
/**
 * 账号与会话
 */

function user_by_id($id)
{
    static $cache = [];
    $id = (int) $id;
    if ($id <= 0) {
        return null;
    }
    if (!array_key_exists($id, $cache)) {
        $cache[$id] = DB::one('SELECT * FROM ' . DB::table('users') . ' WHERE id = ?', [$id]);
    }
    return $cache[$id];
}

function user_by_username($username)
{
    return DB::one('SELECT * FROM ' . DB::table('users') . ' WHERE username = ?', [$username]);
}

function user_by_login($identifier)
{
    $identifier = trim((string) $identifier);
    if ($identifier === '') { return null; }
    $u = user_by_username($identifier);
    if ($u) { return $u; }
    // 电脑浏览器密码管理器常把邮箱自动填进用户名框,允许邮箱作为登录标识。
    if (strpos($identifier, '@') !== false) {
        return DB::one('SELECT * FROM ' . DB::table('users') . ' WHERE LOWER(email) = LOWER(?) ORDER BY id ASC LIMIT 1', [$identifier]);
    }
    return null;
}

function refresh_user_security($u)
{
    if (!$u) { return $u; }
    $until = trim((string) ($u['ban_until'] ?? ''));
    if ((int) $u['status'] === 0 && $until !== '' && strtotime($until) <= time()) {
        try {
            DB::run('UPDATE ' . DB::table('users') . ' SET status = 1, ban_until = ? WHERE id = ?', ['', $u['id']]);
            $u['status'] = 1;
            $u['ban_until'] = '';
        } catch (Exception $e) {
            // 忽略
        }
    }
    return $u;
}

function current_user()
{
    static $loaded = false;
    static $user = null;
    if ($loaded) {
        return $user;
    }
    $loaded = true;
    $uid = (int) ($_SESSION['imp_uid'] ?? $_SESSION['uid'] ?? 0);
    if ($uid <= 0) {
        return $user = null;
    }
    $u = user_by_id($uid);
    $u = refresh_user_security($u);
    if (!$u || (int) $u['status'] !== 1) {
        if (empty($_SESSION['imp_uid'])) {
            unset($_SESSION['uid']);
        }
        return $user = null;
    }
    // 官方固定账号禁止登录;即使存在历史会话也立即失效。
    if (function_exists('is_official_account') && is_official_account($u)) {
        unset($_SESSION['uid'], $_SESSION['imp_uid']);
        return $user = null;
    }
    // 记录在线状态(真实登录账号;代登录也记录管理员本人)
    if (function_exists('online_touch')) {
        online_touch((int) ($_SESSION['uid'] ?? $u['id']));
    }
    // 记录最后访问 IP(代登录不覆盖对方记录)
    if (empty($_SESSION['imp_uid']) && function_exists('client_ip')) {
        $ip = client_ip();
        $lastAt = (string) ($u['last_ip_at'] ?? '');
        if ($ip !== '' && ((string) ($u['last_ip'] ?? '') !== $ip || strtotime($lastAt) < time() - 300)) {
            try {
                DB::run('UPDATE ' . DB::table('users') . ' SET last_ip = ?, last_ip_at = ? WHERE id = ?', [$ip, now(), $u['id']]);
            } catch (Exception $e) {
                // 忽略记录失败
            }
        }
    }
    return $user = $u;
}

/**
 * 真实登录账号(代登录时返回管理员本人)
 */
function real_user()
{
    $uid = (int) ($_SESSION['uid'] ?? 0);
    if ($uid <= 0) {
        return null;
    }
    $u = refresh_user_security(user_by_id($uid));
    return ($u && (int) $u['status'] === 1) ? $u : null;
}

function impersonating()
{
    return !empty($_SESSION['imp_uid']) && real_user();
}

function permanent_login_seconds()
{
    // 约 10 年:只要用户不主动退出登录,回到本站仍然保持登录。
    return 10 * 365 * 86400;
}

function login_session($user, $remember = false)
{
    // 共享主机上 session_regenerate_id(true) 可能产生新的不可写会话文件,表现就是“登录成功跳首页但还是游客”。
    // 登录直接沿用当前已通过 CSRF 校验的会话 ID,随后刷新 Cookie 有效期,保证登录态一定落盘。
    // 安全上仍由 HttpOnly + SameSite=Lax + 登录 CSRF 令牌保护;如需防会话固定可后续单独加二次校验。
    $_SESSION['uid'] = (int) $user['id'];
    // 标记本次会话已通过登录验证(邮箱验证与 TOTP 的持久登录令牌恢复都依赖这些标记)。
    $_SESSION['login_email_verified_at'] = time();
    $_SESSION['login_totp_verified_at'] = time();
    unset($_SESSION['imp_uid']);
    if ($remember) {
        $_SESSION['remember_until'] = time() + permanent_login_seconds();
        refresh_session_cookie(permanent_login_seconds());
    } else {
        unset($_SESSION['remember_until']);
        // 未勾选永久免登录时也保留 30 天,避免 iPhone Safari 切后台/刷新后掉登录。
        refresh_session_cookie(30 * 86400);
    }
    auth_token_issue($user, $remember ? permanent_login_seconds() : 30 * 86400);
}

function refresh_session_cookie($lifetime = 0)
{
    if (headers_sent() || session_status() !== PHP_SESSION_ACTIVE) { return; }
    $p = session_get_cookie_params();
    $options = [
        'expires'  => $lifetime > 0 ? time() + $lifetime : 0,
        'path'     => $p['path'] ?: '/',
        'httponly' => true,
    ];
    if (!empty($p['domain'])) { $options['domain'] = $p['domain']; }
    if (!empty($p['secure'])) { $options['secure'] = true; }
    if (!empty($p['samesite'])) { $options['samesite'] = $p['samesite']; }
    setcookie(session_name(), session_id(), $options);
}

function auth_token_cookie_name()
{
    return 'km_auth';
}

function auth_cookie_options($expires = 0)
{
    $https = (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
        || ((int) ($_SERVER['SERVER_PORT'] ?? 0) === 443);
    return [
        'expires'  => (int) $expires,
        'path'     => '/',
        'secure'   => $https,
        'httponly' => true,
        'samesite' => 'Lax',
    ];
}

function auth_device_cookie_name()
{
    return 'km_auth_device';
}

/** 取得(必要时创建)当前设备的持久登录绑定串。 */
function auth_device_token($lifetime = 0)
{
    $raw = (string) ($_COOKIE[auth_device_cookie_name()] ?? '');
    if (!preg_match('/^[a-f0-9]{64}$/', $raw)) {
        $raw = bin2hex(random_bytes(32));
    }
    if (!headers_sent()) {
        setcookie(auth_device_cookie_name(), $raw, auth_cookie_options(time() + ($lifetime > 0 ? (int) $lifetime : permanent_login_seconds())));
    }
    return $raw;
}

function auth_device_hash($raw)
{
    return hash('sha256', (string) $raw);
}

/**
 * 额外签发一个持久登录 Cookie。
 * 不依赖 PHP 会话 Cookie:苹果 Safari / PWA 把会话 Cookie 回收后,
 * 仍可用这个长期令牌恢复登录,避免“点任何功能都跳登录页”。
 */
function auth_token_issue($user, $lifetime = 0)
{
    $uid = (int) ($user['id'] ?? 0);
    if ($uid <= 0) { return ''; }
    $token = bin2hex(random_bytes(32));
    $hash = hash('sha256', $token);
    $device = auth_device_token($lifetime > 0 ? (int) $lifetime : permanent_login_seconds());
    $deviceHash = $device !== '' ? auth_device_hash($device) : '';
    try {
        DB::run('UPDATE ' . DB::table('users') . ' SET auth_token = ?, auth_token_device = ? WHERE id = ?', [$hash, $deviceHash, $uid]);
    } catch (Throwable $e) {
        return '';
    }
    // 第 3 段标记“签发时已完成当时启用的全部登录校验”,用于区分升级前的旧令牌。
    setcookie(auth_token_cookie_name(), $uid . ':' . $token . ':2', auth_cookie_options(time() + ($lifetime > 0 ? (int) $lifetime : permanent_login_seconds())));
    return $token;
}

function auth_token_try()
{
    if (!empty($_SESSION['uid'])) { return true; }
    // 持久登录令牌只在完整登录(含已启用的邮箱验证 / TOTP)成功后才签发,
    // 因此它本身就是“已完成登录验证”的凭证。PHP 会话 Cookie 被系统回收时,
    // 必须允许它恢复会话,否则会出现点任何页面都重新登录的问题。
    $raw = (string) ($_COOKIE[auth_token_cookie_name()] ?? '');
    if (!preg_match('/^(\d{1,10}):([a-f0-9]{64})(?::([a-z0-9]+))?$/', $raw, $m)) { return false; }
    $uid = (int) $m[1];
    $token = $m[2];
    $assurance = (string) ($m[3] ?? '');
    $deviceRaw = (string) ($_COOKIE[auth_device_cookie_name()] ?? '');
    $user = user_by_id($uid);
    if (!$user || (int) ($user['status'] ?? 0) !== 1 || empty($user['auth_token'])) { return false; }
    if (!hash_equals((string) $user['auth_token'], hash('sha256', $token))) { return false; }
    // 设备 Cookie 被浏览器清理或跨设备时重新绑定,避免“登录成功却每次回到登录页”。
    if (!preg_match('/^[a-f0-9]{64}$/', $deviceRaw)) {
        $deviceRaw = auth_device_token(permanent_login_seconds());
    }
    if (empty($user['auth_token_device']) || !hash_equals((string) $user['auth_token_device'], auth_device_hash($deviceRaw))) {
        try {
            DB::run('UPDATE ' . DB::table('users') . ' SET auth_token_device = ? WHERE id = ?', [auth_device_hash($deviceRaw), $uid]);
        } catch (Throwable $e) {
            // 绑定失败不阻塞本次登录恢复
        }
    }
    // 旧格式令牌没有完整登录标记;只有确实需要邮箱验证(用户已开启个人开关)
    // 或启用 TOTP 的账号才必须重新登录,避免全局开关误伤普通账号。
    if ((login_email_verify_required_for($user) || totp_login_required_for($user)) && $assurance !== '2') { return false; }
    // 官方固定账号只用于系统发布,禁止通过任何持久登录令牌恢复登录。
    if (function_exists('is_official_account') && is_official_account($user)) { return false; }
    $_SESSION['uid'] = $uid;
    // 令牌签发时已完成当时的全部登录校验;恢复会话后同步标记,避免后续逻辑误判。
    $_SESSION['login_email_verified_at'] = time();
    $_SESSION['login_totp_verified_at'] = time();
    unset($_SESSION['imp_uid']);
    refresh_session_cookie(30 * 86400);
    return true;
}

function auth_token_clear()
{
    $uid = (int) ($_SESSION['uid'] ?? 0);
    if ($uid > 0) {
        try {
            DB::run('UPDATE ' . DB::table('users') . ' SET auth_token = \'\', auth_token_device = \'\' WHERE id = ?', [$uid]);
        } catch (Throwable $e) {
            // 忽略:退出登录仍应清掉本地 Cookie
        }
    }
    setcookie(auth_token_cookie_name(), '', auth_cookie_options(time() - 42000));
    setcookie(auth_device_cookie_name(), '', auth_cookie_options(time() - 42000));
}

function logout_session()
{
    if (function_exists('online_forget') && !empty($_SESSION['uid'])) {
        online_forget((int) $_SESSION['uid']);
    }
    auth_token_clear();
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
    }
    session_destroy();
}

function require_login()
{
    if (!current_user()) {
        $next = $_SERVER['REQUEST_URI'] ?? '';
        redirect(page_url('login', ['next' => $next]));
    }
}

function require_admin()
{
    $admin = current_user();
    if (!$admin) {
        flash('需要管理员权限才能访问该页面', 'err');
        redirect(page_url('login', ['next' => $_SERVER['REQUEST_URI'] ?? '']));
    }
    if (!in_array($admin['role'], ['admin', 'superadmin'], true)) {
        flash('当前身份没有后台权限,代登录普通用户时请先退出代登录', 'err');
        redirect(page_url('home'));
    }
}

function verify_password($plain, $hash)
{
    return password_verify($plain, $hash);
}


/** 登录保护:连续密码错误达到上限后临时锁定账号。 */
function login_lockout_enabled()
{
    return setting('login_lockout_enabled', '1') === '1';
}

function login_lockout_threshold()
{
    return max(1, min(50, (int) setting('login_lockout_threshold', '5')));
}

function login_lockout_minutes()
{
    return max(1, min(1440, (int) setting('login_lockout_minutes', '30')));
}

/** 返回账号剩余锁定秒数;已到期则自动清零失败计数。 */
function login_lockout_remaining(&$user)
{
    if (!is_array($user) || !login_lockout_enabled()) {
        return 0;
    }
    $until = trim((string) ($user['login_locked_until'] ?? ''));
    if ($until === '') {
        return 0;
    }
    $ts = strtotime($until);
    if ($ts === false) {
        return 0;
    }
    $remaining = $ts - time();
    if ($remaining > 0) {
        return $remaining;
    }
    // 锁定期已结束,下一次登录从零开始计数。
    $user['login_fail_count'] = 0;
    $user['login_locked_until'] = '';
    try {
        DB::run('UPDATE ' . DB::table('users') . ' SET login_fail_count = 0, login_locked_until = ? WHERE id = ?', ['', (int) $user['id']]);
    } catch (Exception $e) {
    }
    return 0;
}

/** 记录一次密码错误;返回本次触发后的剩余锁定秒数,0 表示尚未锁定。 */
function login_lockout_register_failure($user)
{
    if (!is_array($user) || !login_lockout_enabled()) {
        return 0;
    }
    $count = (int) ($user['login_fail_count'] ?? 0) + 1;
    $threshold = login_lockout_threshold();
    if ($count >= $threshold) {
        $seconds = login_lockout_minutes() * 60;
        $until = date('Y-m-d H:i:s', time() + $seconds);
        try {
            DB::run('UPDATE ' . DB::table('users') . ' SET login_fail_count = ?, login_locked_until = ? WHERE id = ?', [$threshold, $until, (int) $user['id']]);
        } catch (Exception $e) {
        }
        return $seconds;
    }
    try {
        DB::run('UPDATE ' . DB::table('users') . ' SET login_fail_count = ? WHERE id = ?', [$count, (int) $user['id']]);
    } catch (Exception $e) {
    }
    return 0;
}

/** 密码正确后清除失败计数与锁定。 */
function login_lockout_clear($user)
{
    if (!is_array($user)) {
        return;
    }
    try {
        DB::run('UPDATE ' . DB::table('users') . ' SET login_fail_count = 0, login_locked_until = ? WHERE id = ?', ['', (int) $user['id']]);
    } catch (Exception $e) {
    }
}

/** 给用户看的剩余锁定时长。 */
function login_lockout_text($seconds)
{
    $minutes = max(1, (int) ceil(((int) $seconds) / 60));
    if ($minutes >= 60) {
        $hours = intdiv($minutes, 60);
        $mins = $minutes % 60;
        return $hours . ' 小时' . ($mins > 0 ? ' ' . $mins . ' 分钟' : '');
    }
    return $minutes . ' 分钟';
}

/** 登录方式:password=用户名密码,email_code=邮箱验证码。 */
function login_mode()
{
    return setting('login_mode', 'password') === 'email_code' ? 'email_code' : 'password';
}

/** 登录邮箱验证开关(后台「账号安全」)。 */
function login_email_verify_enabled()
{
    return setting('login_email_verify', '0') === '1';
}

/** 用户自己是否在个人中心开启了「邮箱验证登录」。 */
function login_email_verify_user_enabled($user)
{
    return is_array($user) && (int) ($user['email_login_verify'] ?? 0) === 1;
}

/**
 * 登录邮箱验证:后台全局开关只是开放功能,
 * 还需要用户自己开启个人开关、且邮箱已验证,才会在密码登录后要求邮箱验证码。
 */
function login_email_verify_required_for($user)
{
    // 用户自己在「登录验证」里开启后即生效,不再依赖后台全局开关。
    // 超级管理员同样按本人选择生效,避免出现“已开启但登录不验证”的错觉。
    if (!is_array($user) || !login_email_verify_user_enabled($user)) {
        return false;
    }
    $email = trim((string) ($user['email'] ?? ''));
    return $email !== ''
        && filter_var($email, FILTER_VALIDATE_EMAIL)
        && (int) ($user['email_verified'] ?? 0) === 1;
}

/** 登录验证码展示用邮箱掩码。 */
function login_email_mask($email)
{
    $email = trim((string) $email);
    $at = strpos($email, '@');
    if ($at === false || $at < 1) {
        return $email;
    }
    $name = substr($email, 0, $at);
    $domain = substr($email, $at + 1);
    $visible = mb_substr($name, 0, 2);
    return $visible . str_repeat('*', max(2, mb_strlen($name) - 2)) . '@' . $domain;
}

/**
 * 注册校验,返回错误信息数组
 */
function validate_register($username, $password, $password2, $nickname, $email)
{
    $errors = [];
    if (!preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]{2,20}$/u', $username)) {
        $errors[] = '用户名需为 2-20 位中文、字母、数字或下划线';
    }
    if (strlen($password) < 6) {
        $errors[] = '密码至少 6 位';
    }
    if ($password !== $password2) {
        $errors[] = '两次输入的密码不一致';
    }
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = '邮箱格式不正确';
    }
    if (user_by_username($username)) {
        $errors[] = '该用户名已被占用';
    }
    list($nickOk, $nickReason) = nickname_check($username);
    if (!$nickOk) {
        $errors[] = $nickReason;
    }
    if ($nickname !== '') {
        list($nickOk, $nickReason) = nickname_check($nickname);
        if (!$nickOk) {
            $errors[] = $nickReason;
        }
    }
    return $errors;
}

function create_user($username, $password, $nickname, $gender, $email, $role = 'user')
{
    $genders = ['male', 'female', 'secret'];
    $user = DB::one('SELECT * FROM ' . DB::table('users') . ' WHERE username = ?', [$username]);
    if ($user) {
        throw new Exception('该用户名已被占用');
    }
    return DB::insert('users', [
        'username'   => $username,
        'password'   => password_hash($password, PASSWORD_DEFAULT),
        'nickname'   => $nickname !== '' ? $nickname : $username,
        'avatar'     => '',
        'gender'     => in_array($gender, $genders, true) ? $gender : 'secret',
        'email'      => $email,
        'role'       => $role,
        'status'     => 1,
        'points'     => 0,
        'streak'     => 0,
        'profile_visitor_count' => 0,
        'initial_profile' => json_encode([
            'username' => $username,
            'nickname' => $nickname !== '' ? $nickname : $username,
            'gender' => in_array($gender, $genders, true) ? $gender : 'secret',
            'email' => $email,
            'email_verified' => 0,
            'avatar' => '',
            'bio' => '',
            'province' => '',
            'city' => '',
            'district' => '',
            'town' => '',
            'village' => '',
            'show_location' => 1,
            'show_ip' => 1,
            'role' => $role,
            'created_at' => now(),
        ], JSON_UNESCAPED_UNICODE),
        'created_at' => now(),
    ]);
}

/**
 * 安装完成后的一次性管理员登录凭据。
 * 安装向导生成随机令牌,前台入口只消费一次;文件位于受保护的 data 目录。
 */
function install_login_file($kind = 'home')
{
    return APP_ROOT . '/data/install-login-' . ($kind === 'admin' ? 'admin' : 'home') . '.json';
}

function install_login_issue($uid, $kind = 'home', $ttl = 1800)
{
    $token = bin2hex(random_bytes(32));
    $data = [
        'token'      => $token,
        'uid'        => (int) $uid,
        'created_at' => time(),
        'expires'    => time() + max(60, (int) $ttl),
    ];
    $file = install_login_file($kind);
    if (!is_dir(dirname($file))) {
        @mkdir(dirname($file), 0775, true);
    }
    if (@file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE), LOCK_EX) === false) {
        return '';
    }
    @chmod($file, 0600);
    return $token;
}

function install_login_consume($token, $kind = 'home')
{
    $token = (string) $token;
    $kind = $kind === 'admin' ? 'admin' : 'home';
    if ($token === '' || !preg_match('/^[a-f0-9]{64}$/', $token)) {
        return false;
    }
    $file = install_login_file($kind);
    if (!is_file($file)) {
        return false;
    }
    $raw = @file_get_contents($file);
    $data = json_decode((string) $raw, true);
    if (!is_array($data) || empty($data['token']) || empty($data['uid'])) {
        @unlink($file);
        return false;
    }
    if ((int) ($data['expires'] ?? 0) < time() || !hash_equals((string) $data['token'], $token)) {
        return false;
    }
    $u = user_by_id((int) $data['uid']);
    if (!$u || (int) $u['status'] !== 1 || !is_superadmin($u)) {
        @unlink($file);
        return false;
    }
    if (session_status() !== PHP_SESSION_ACTIVE) {
        @session_start();
    }
    session_regenerate_id(true);
    $_SESSION['uid'] = (int) $u['id'];
    unset($_SESSION['imp_uid']);
    auth_token_issue($u);
    @unlink($file);
    return true;
}
主题