<?php
/**
 * 通用函数库
 */

function e($value)
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

function cfg($key, $default = '')
{
    global $CONFIG;
    return $CONFIG[$key] ?? $default;
}

function base_url($path = '')
{
    $base = BASE_PATH;
    if ($path === '') {
        return $base === '' ? '/' : $base . '/';
    }
    return $base . '/' . ltrim($path, '/');
}

function page_url($page = 'home', array $params = [])
{
    $params = array_merge(['page' => $page], $params);
    return base_url('index.php') . '?' . http_build_query($params);
}

/**
 * 绝对地址（生成外链、分享链接用）
 */
function full_url($path = '')
{
    $https = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    return $scheme . '://' . $host . base_url($path);
}

function redirect($url)
{
    if (!headers_sent()) {
        header('Location: ' . $url);
    } else {
        // 后台页面在输出页头后才处理 POST 时，用 JS + meta 双保险立即跳转，避免停留在半截页面。
        $jsonUrl = json_encode((string) $url, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
        echo '<meta http-equiv="refresh" content="0;url=' . e($url) . '">';
        echo '<script>location.replace(' . $jsonUrl . ');</script>';
    }
    exit;
}

function redirect_page($page = 'home', array $params = [])
{
    redirect(page_url($page, $params));
}

function client_device_type()
{
    $ua = strtolower((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
    $mobileHint = strtolower((string) ($_SERVER['HTTP_SEC_CH_UA_MOBILE'] ?? ''));
    if ($ua === '') {
        return 'desktop';
    }
    // 平板优先判断：iPad 的 UA 也包含 Mobile；Android 平板通常不含 Mobile。
    if (preg_match('/ipad|tablet|kindle|silk|playbook|nexus 7|nexus 9|sm-t|lenovo tab|matepad/', $ua)) {
        return 'tablet';
    }
    if (strpos($ua, 'android') !== false && strpos($ua, 'mobile') === false) {
        return 'tablet';
    }
    if ($mobileHint === '?1' || preg_match('/mobile|iphone|ipod|android|blackberry|opera mini|iemobile|windows phone|crios|fxios|edgios/', $ua)) {
        return 'mobile';
    }
    return 'desktop';
}

/** 木卫守护设备分类：手机端 / 苹果端 / 电脑端 / 平板端 */
function client_device_category($ua = null)
{
    $ua = $ua === null
        ? strtolower((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''))
        : strtolower((string) $ua);
    if ($ua === '') { return 'desktop'; }
    if (preg_match('/ipad|tablet|kindle|silk|playbook|nexus 7|nexus 9|sm-t|lenovo tab|matepad/', $ua)) {
        return 'tablet';
    }
    if (strpos($ua, 'android') !== false && strpos($ua, 'mobile') === false) {
        return 'tablet';
    }
    if (preg_match('/iphone|ipod|ios/', $ua)) { return 'apple'; }
    if (preg_match('/mobile|android|blackberry|opera mini|iemobile|windows phone/', $ua)) { return 'mobile'; }
    return 'desktop';
}

function client_device_category_label($ua = null)
{
    return ['mobile' => '手机端', 'apple' => '苹果端', 'desktop' => '电脑端', 'tablet' => '平板端'][client_device_category($ua)] ?? '电脑端';
}

function device_view_modes()
{
    return ['mobile', 'tablet', 'desktop'];
}

function device_view_mode()
{
    static $mode = null;
    if ($mode !== null) {
        return $mode;
    }
    $allowed = device_view_modes();
    $requested = strtolower(trim((string) ($_GET['device'] ?? '')));
    if (in_array($requested, $allowed, true)) {
        $mode = $requested;
        if (!headers_sent()) {
            $path = BASE_PATH !== '' ? BASE_PATH . '/' : '/';
            setcookie('km_device_view', $mode, [
                'expires' => time() + 365 * 86400,
                'path' => $path,
                'samesite' => 'Lax',
            ]);
        }
        return $mode;
    }
    $cookie = strtolower(trim((string) ($_COOKIE['km_device_view'] ?? '')));
    if (in_array($cookie, $allowed, true)) {
        return $mode = $cookie;
    }
    return $mode = client_device_type();
}

function device_view_url($mode)
{
    $mode = in_array($mode, device_view_modes(), true) ? $mode : 'mobile';
    $path = strtok((string) ($_SERVER['REQUEST_URI'] ?? '/'), '?');
    if ($path === false || $path === '') {
        $path = '/';
    }
    $query = [];
    parse_str((string) ($_SERVER['QUERY_STRING'] ?? ''), $query);
    $query['device'] = $mode;
    return $path . '?' . http_build_query($query);
}

function asset($path)
{
    $rel = 'assets/' . ltrim($path, '/');
    $file = dirname(__DIR__) . '/' . $rel;
    $ver = is_file($file) ? filemtime($file) : APP_VERSION;
    return base_url($rel) . '?v=' . $ver;
}

function upload_url($relPath)
{
    if (!$relPath) {
        return asset('img/avatar-default.svg');
    }
    if (preg_match('#^(http|https)://#i', $relPath)) {
        return $relPath;
    }
    return base_url($relPath);
}

function settings_all($reload = false)
{
    static $cache = null;
    if ($cache === null || $reload) {
        $cache = [];
        try {
            foreach (DB::all('SELECT skey, svalue FROM ' . DB::table('settings')) as $row) {
                $cache[$row['skey']] = $row['svalue'];
            }
        } catch (Exception $e) {
            $cache = [];
        }
    }
    return $cache;
}

function setting($key, $default = '')
{
    $all = settings_all();
    return isset($all[$key]) && $all[$key] !== '' ? $all[$key] : $default;
}

function set_setting($key, $value)
{
    $exists = DB::val('SELECT COUNT(*) FROM ' . DB::table('settings') . ' WHERE skey = ?', [$key]);
    if ($exists) {
        DB::run('UPDATE ' . DB::table('settings') . ' SET svalue = ? WHERE skey = ?', [(string) $value, $key]);
    } else {
        DB::run('INSERT INTO ' . DB::table('settings') . ' (skey, svalue) VALUES (?, ?)', [$key, (string) $value]);
    }
    settings_all(true);
}

/**
 * 木卫守护的守护起始时间。
 * 优先使用首次记录的时间；旧站没有记录时，回退到最早账号或最早设备记录。
 */
function muwei_guard_since()
{
    static $since = null;
    if ($since !== null) {
        return $since;
    }
    $stored = trim((string) setting('muwei_guard_since', ''));
    if ($stored !== '' && strtotime($stored) !== false) {
        $since = date('Y-m-d H:i:s', strtotime($stored));
        return $since;
    }
    $candidates = [];
    try {
        $firstUser = (string) DB::val('SELECT MIN(created_at) FROM ' . DB::table('users') . ' WHERE created_at <> ?', [''], '');
        if ($firstUser !== '' && strtotime($firstUser) !== false) {
            $candidates[] = strtotime($firstUser);
        }
    } catch (Exception $e) {
    }
    try {
        $firstDevice = (string) DB::val('SELECT MIN(first_at) FROM ' . DB::table('guard_devices') . ' WHERE first_at <> ?', [''], '');
        if ($firstDevice !== '' && strtotime($firstDevice) !== false) {
            $candidates[] = strtotime($firstDevice);
        }
    } catch (Exception $e) {
    }
    $sinceTs = $candidates ? min($candidates) : time();
    $since = date('Y-m-d H:i:s', $sinceTs);
    try {
        set_setting('muwei_guard_since', $since);
    } catch (Exception $e) {
    }
    return $since;
}

/** 木卫守护已守护的天数，按自然日计算并包含当天。 */
function muwei_guard_days()
{
    $start = strtotime(date('Y-m-d', strtotime(muwei_guard_since())));
    $today = strtotime(date('Y-m-d'));
    if ($start === false || $today === false) {
        return 1;
    }
    return max(1, (int) floor(($today - $start) / 86400) + 1);
}

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

function csrf_token()
{
    if (empty($_SESSION['csrf'])) {
        $cookieToken = (string) ($_COOKIE['km_csrf'] ?? '');
        if (preg_match('/^[a-f0-9]{48}$/', $cookieToken)) {
            $_SESSION['csrf'] = $cookieToken;
        } else {
            $_SESSION['csrf'] = bin2hex(random_bytes(24));
        }
    }
    $token = (string) $_SESSION['csrf'];
    // 同步一份持久 Cookie。iPhone Safari 把 PHP 会话 Cookie 回收后，
    // POST 仍能用这个 Cookie 校验表单令牌，不会误报“页面已过期”。
    if ((string) ($_COOKIE['km_csrf'] ?? '') !== $token && !headers_sent()) {
        setcookie('km_csrf', $token, csrf_cookie_options(time() + 30 * 86400));
    }
    return $token;
}

function csrf_field()
{
    return '<input type="hidden" name="_token" value="' . e(csrf_token()) . '">';
}

function check_csrf()
{
    $token = $_POST['_token'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
    $sessionToken = (string) ($_SESSION['csrf'] ?? '');
    $cookieToken = (string) ($_COOKIE['km_csrf'] ?? '');
    $valid = false;
    if (is_string($token) && $token !== '') {
        if ($sessionToken !== '' && hash_equals($sessionToken, $token)) {
            $valid = true;
        } elseif ($cookieToken !== '' && hash_equals($cookieToken, $token)) {
            // 双提交校验：会话 Cookie 丢失但持久 CSRF Cookie 仍在时继续有效。
            $valid = true;
        }
    }
    if (!$valid) {
        http_response_code(419);
        if (is_ajax_request()) {
            json_out(['ok' => false, 'msg' => '页面已过期，请刷新后重试'], 419);
        }
        app_fatal_page('页面已过期', '令牌校验失败，请刷新页面后重新提交。');
    }
    return true;
}

function is_ajax_request()
{
    return strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'xmlhttprequest'
        || strpos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') !== false;
}

// ---------- 闪存消息 ----------
function flash($message, $type = 'ok')
{
    $_SESSION['flash'][] = ['msg' => $message, 'type' => $type];
}

function take_flashes()
{
    $list = $_SESSION['flash'] ?? [];
    unset($_SESSION['flash']);
    return $list;
}

// ---------- 输入 ----------
function input($key, $default = '')
{
    if (isset($_POST[$key])) {
        return is_string($_POST[$key]) ? trim($_POST[$key]) : $_POST[$key];
    }
    if (isset($_GET[$key])) {
        return is_string($_GET[$key]) ? trim($_GET[$key]) : $_GET[$key];
    }
    return $default;
}

function now()
{
    return date('Y-m-d H:i:s');
}

function exact_time($datetime)
{
    $datetime = trim((string) $datetime);
    if ($datetime === '') { return ''; }
    $ts = strtotime($datetime);
    return $ts ? date('Y-m-d H:i:s', $ts) : $datetime;
}

function time_ago($datetime)
{
    if (!$datetime) {
        return '';
    }
    $ts = strtotime($datetime);
    if (!$ts) {
        return $datetime;
    }
    $diff = time() - $ts;
    if ($diff < 60) {
        return '刚刚';
    }
    if ($diff < 3600) {
        return floor($diff / 60) . ' 分钟前';
    }
    if ($diff < 86400) {
        return floor($diff / 3600) . ' 小时前';
    }
    if ($diff < 86400 * 30) {
        return floor($diff / 86400) . ' 天前';
    }
    return date('Y-m-d', $ts);
}

function format_size($bytes)
{
    $bytes = (int) $bytes;
    if ($bytes >= 1073741824) {
        return round($bytes / 1073741824, 2) . ' GB';
    }
    if ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . ' MB';
    }
    if ($bytes >= 1024) {
        return round($bytes / 1024, 1) . ' KB';
    }
    return $bytes . ' B';
}

// ---------- 用户展示 ----------

/**
 * 认证款式与 V 徽章
 */
function verify_styles()
{
    return [
        'red'    => ['红V', '#ef4444'],
        'blue'   => ['蓝V', '#4f8ef7'],
        'gold'   => ['金V', '#e0a93b'],
        'purple' => ['紫V', '#9b6cf0'],
        'green'  => ['绿V', '#2fb67c'],
        'pink'   => ['粉V', '#f26fa7'],
        'huangxiaoyun' => ['黄霄雲粉V', '#ff5c9d'],
        'huangxiaoyun_loop' => ['黄霄雲循环动态粉V', '#ff5c9d'],
        'cyan'   => ['青V', '#20b8cc'],
        'orange' => ['橙V', '#f58533'],
        'admin'  => ['管理V', '#6b5424', true],
        'rainbow'=> ['闪彩V', '#ff5fa2'],
    ];
}

function comment_bubble_styles()
{
    return [
        'tea'     => ['name' => '清茶', 'desc' => '米白暖调，安静耐看'],
        'cloud'   => ['name' => '云朵', 'desc' => '雾蓝轻盈，像一小片云'],
        'sakura'  => ['name' => '樱花', 'desc' => '淡粉柔软，春日茶话'],
        'celadon' => ['name' => '青瓷', 'desc' => '青绿温润，茶器釉色'],
        'ink'     => ['name' => '夜墨', 'desc' => '深色留白，夜里也清楚'],
    ];
}

function comment_bubble_of($user)
{
    $style = (string) ($user['comment_bubble'] ?? 'tea');
    $styles = comment_bubble_styles();
    return isset($styles[$style]) ? $style : 'tea';
}

function verify_style_of($user)
{
    $style = (string) ($user['verify_style'] ?? '');
    return isset(verify_styles()[$style]) ? $style : 'blue';
}

function verify_title_of($user)
{
    $title = trim((string) ($user['verify_title'] ?? ''));
    if ($title !== '') {
        return $title;
    }
    return ($user['verify_type'] ?? '') === 'professional' ? '职业认证' : '官方认证';
}

function verify_badge($user, $withText = false)
{
    if (empty($user['verified']) && trim((string) ($user['verify_style'] ?? '')) === '' && trim((string) ($user['verify_title'] ?? '')) === '') {
        return '';
    }
    $style = verify_style_of($user);
    $label = verify_styles()[$style][0];
    $html = '<span class="v-badge v-' . $style . '" title="' . e(verify_title_of($user)) . '">V<span class="v-txt">' . e($label) . '</span></span>';
    if ($withText) {
        $html .= '<span class="v-title">' . e(verify_title_of($user)) . '</span>';
    }
    return $html;
}

function extension_icon_src($icon)
{
    $icon = trim((string) $icon);
    if ($icon === '') {
        return '';
    }
    if (preg_match('#^https?://#i', $icon)) {
        return $icon;
    }
    return base_url($icon);
}

/** 当前用户可见的扩展：系统扩展 + 本人添加的网站扩展，按个人布局排序 */
function extension_list_for_user($user = null)
{
    $user = $user ?: current_user();
    $uid = (int) ($user['id'] ?? 0);
    $where = "status = 1 AND slug <> 'collect' AND slug <> 'fishing'";
    if ($uid > 0) {
        $where .= ' AND (owner_id = 0 OR owner_id = ' . $uid . ')';
    } else {
        $where .= ' AND owner_id = 0';
    }
    $rows = DB::all('SELECT * FROM ' . DB::table('extensions') . ' WHERE ' . $where . ' ORDER BY sort ASC, id ASC');
    $prefs = [];
    if ($uid > 0) {
        foreach (DB::all('SELECT * FROM ' . DB::table('user_ext_prefs') . ' WHERE user_id = ?', [$uid]) as $p) {
            $prefs[(int) $p['extension_id']] = $p;
        }
    }
    foreach ($rows as &$row) {
        $id = (int) $row['id'];
        $row['_sort'] = isset($prefs[$id]) ? (int) $prefs[$id]['sort'] : (int) $row['sort'];
        $row['_hidden'] = isset($prefs[$id]) ? (int) $prefs[$id]['hidden'] : 0;
    }
    unset($row);
    usort($rows, function ($a, $b) {
        if ((int) $a['_sort'] === (int) $b['_sort']) { return (int) $a['id'] <=> (int) $b['id']; }
        return (int) $a['_sort'] <=> (int) $b['_sort'];
    });
    return $rows;
}

function avatar_video_extensions()
{
    // 只接受主流浏览器可直接播放的视频容器，避免上传后头像变成空白。
    return ['mp4', 'm4v', 'webm', 'ogv', 'mov'];
}

function avatar_media_kind($user)
{
    if (is_numeric($user)) {
        $user = user_by_id((int) $user);
    }
    $avatar = is_array($user) ? trim((string) ($user['avatar'] ?? '')) : '';
    $path = (string) parse_url($avatar, PHP_URL_PATH);
    $ext = strtolower(pathinfo($path !== '' ? $path : $avatar, PATHINFO_EXTENSION));
    return in_array($ext, avatar_video_extensions(), true) ? 'video' : 'image';
}

function avatar_is_video($user)
{
    return avatar_media_kind($user) === 'video';
}

function avatar_of($user)
{
    if (is_numeric($user)) {
        $user = user_by_id((int) $user);
    }
    $avatar = is_array($user) ? trim((string) ($user['avatar'] ?? '')) : '';
    if ($avatar === '') {
        return asset('img/avatar-default.svg');
    }
    return upload_url($avatar);
}

/**
 * 统一输出头像。图片/GIF/动态 WebP 用 img 原样展示，视频头像用 video + 懒加载播放。
 * $attrs 只由服务端模板拼接，调用方需自行对动态值做 e() 转义。
 */
function avatar_html($user, $class = '', $attrs = '')
{
    $url = avatar_of($user);
    $isVideo = avatar_is_video($user);
    $classes = trim('avatar-media ' . ($isVideo ? 'avatar-video ' : '') . $class);
    $extra = trim((string) $attrs) !== '' ? ' ' . trim((string) $attrs) : '';
    if ($isVideo) {
        return '<video class="' . e($classes) . '" data-avatar-video data-src="' . e($url) . '"'
            . ' muted loop playsinline preload="none" aria-label="用户视频头像"' . $extra . '></video>';
    }
    return '<img class="' . e($classes) . '" src="' . e($url) . '" alt="" loading="lazy" decoding="async"' . $extra . '>';
}

/** 认证头像右下角的彩色小 V；未认证用户返回空字符串。 */
function verify_dot_html($user)
{
    if (empty($user['verified']) && trim((string) ($user['verify_style'] ?? '')) === '' && trim((string) ($user['verify_title'] ?? '')) === '') {
        return '';
    }
    $style = verify_style_of($user);
    return '<span class="avatar-v v-' . e($style) . '" title="' . e(verify_title_of($user)) . '">V</span>';
}

/** 输出头像并在右下角叠加认证小 V（有认证才叠加），父级使用相对定位。 */
function verified_avatar_html($user, $class = '', $wrapClass = '', $attrs = '')
{
    $avatar = avatar_html($user, $class, $attrs);
    $badge = verify_dot_html($user);
    if ($badge === '') {
        return $avatar;
    }
    $wrap = trim('avatar-v-wrap ' . $wrapClass);
    return '<span class="' . e($wrap) . '">' . $avatar . $badge . '</span>';
}

/** 按头像路径直接渲染（审核预览用，支持图片与视频） */
function avatar_path_media_html($path, $class = '')
{
    $path = (string) $path;
    if ($path === '') {
        return '<span class="' . e(trim('avatar-media avatar-empty ' . $class)) . '"></span>';
    }
    $url = strpos($path, 'http://') === 0 || strpos($path, 'https://') === 0 ? $path : upload_url($path);
    $ext = strtolower(pathinfo((string) parse_url($path, PHP_URL_PATH), PATHINFO_EXTENSION));
    $isVideo = in_array($ext, avatar_video_extensions(), true);
    $classes = trim('avatar-media ' . ($isVideo ? 'avatar-video ' : '') . $class);
    if ($isVideo) {
        return '<video class="' . e($classes) . '" data-avatar-video data-src="' . e($url) . '" autoplay muted loop playsinline preload="metadata"></video>';
    }
    return '<img class="' . e($classes) . '" src="' . e($url) . '" alt="" loading="lazy" decoding="async">';
}

/**
 * 头像文件大小上限（MB）：由后台「头像文件大小」设置，默认图片 200MB、视频 500MB。
 */
function avatar_max_mb($kind = 'image')
{
    $key = $kind === 'video' ? 'avatar_video_max_mb' : 'avatar_image_max_mb';
    $default = $kind === 'video' ? 500 : 200;
    return max(1, min(10000, (int) setting($key, (string) $default)));
}

function avatar_max_bytes($kind = 'image')
{
    return avatar_max_mb($kind) * 1024 * 1024;
}

/**
 * 头像上传入口：图片与视频大小上限读取后台设置。
 * 图片不做 GD 缩放或重编码，保留原始画质与动画帧。
 */
function avatar_store_upload($field)
{
    if (empty($_FILES[$field]['name'])) {
        throw new Exception('没有选择头像文件');
    }
    $original = basename((string) $_FILES[$field]['name']);
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
    if (in_array($ext, avatar_video_extensions(), true)) {
        return upload_store($field, 'avatars', [
            'allow' => avatar_video_extensions(),
            'video' => true,
            'max' => avatar_max_bytes('video'),
        ]);
    }
    $stored = upload_store($field, 'avatars', [
        'image' => true,
        'max' => avatar_max_bytes('image'),
    ]);
    if (!empty($stored['path'])) {
        media_normalize_gif_loop($stored['path']);
    }
    return $stored;
}

/**
 * 站点 Logo 与头像共用同一套媒体规则：图片 200MB 原质保存，视频 500MB。
 */
function site_logo_is_video($logo)
{
    $path = (string) parse_url((string) $logo, PHP_URL_PATH);
    $ext = strtolower(pathinfo($path !== '' ? $path : (string) $logo, PATHINFO_EXTENSION));
    return in_array($ext, avatar_video_extensions(), true);
}

function site_logo_favicon($logo)
{
    // 浏览器 favicon 不能播放视频，视频 Logo 时回退到内置站点图标。
    return site_logo_is_video($logo) ? asset('img/logo.svg') : upload_url($logo);
}

/** 标签页图标：优先使用站点信息里单独设置的 favicon，未设置时跟随 Logo。 */
function site_favicon_url($logo = null)
{
    $custom = trim((string) setting('site_favicon', ''));
    if ($custom !== '') {
        return upload_url($custom);
    }
    return site_logo_favicon($logo !== null ? $logo : setting('site_logo', 'assets/img/logo.svg'));
}

function site_logo_html($logo, $class = '')
{
    $url = upload_url($logo);
    $classes = trim('site-logo-media ' . $class);
    if (site_logo_is_video($logo)) {
        // 视频 Logo 使用 video 输出，保留用户上传的动态效果；首帧未加载时由背景色兜底，不再直接替换成内置 Logo。
        $mime = 'video/mp4';
        $ext = strtolower(pathinfo((string) parse_url((string) $logo, PHP_URL_PATH), PATHINFO_EXTENSION));
        if ($ext === 'webm') { $mime = 'video/webm'; }
        elseif (in_array($ext, ['ogv', 'ogg'], true)) { $mime = 'video/ogg'; }
        return '<video class="' . e($classes) . ' site-logo-video" autoplay muted loop playsinline preload="auto" aria-label="logo"><source src="' . e($url) . '" type="' . e($mime) . '"></video>';
    }
    return '<img class="' . e($classes) . '" src="' . e($url) . '" alt="logo" decoding="async">';
}

function site_logo_store_upload($field)
{
    if (empty($_FILES[$field]['name'])) {
        throw new Exception('没有选择 Logo 文件');
    }
    $original = basename((string) $_FILES[$field]['name']);
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
    if (in_array($ext, avatar_video_extensions(), true)) {
        return upload_store($field, 'site', [
            'allow' => avatar_video_extensions(),
            'video' => true,
            'max' => 500 * 1024 * 1024,
        ]);
    }
    $stored = upload_store($field, 'site', [
        'image' => true,
        'max' => 200 * 1024 * 1024,
    ]);
    if (!empty($stored['path'])) {
        media_normalize_gif_loop($stored['path']);
    }
    return $stored;
}

/** GIF 头像 / Logo：统一改写为无限循环（ImageMagick 可用时） */
function media_normalize_gif_loop($path)
{
    $path = (string) $path;
    if (strtolower(pathinfo((string) parse_url($path, PHP_URL_PATH), PATHINFO_EXTENSION)) !== 'gif') {
        return;
    }
    $full = strpos($path, 'uploads/') === 0 ? APP_ROOT . '/' . $path : (strpos($path, '/') === 0 ? $path : APP_ROOT . '/' . $path);
    if (!is_file($full)) {
        return;
    }
    $bin = '';
    foreach (['/usr/bin/convert', '/usr/local/bin/convert', '/opt/local/bin/convert'] as $candidate) {
        if (is_executable($candidate)) { $bin = $candidate; break; }
    }
    if ($bin === '' || !function_exists('exec')) {
        return;
    }
    $tmp = $full . '.loop.gif';
    $out = [];
    $code = 1;
    @exec($bin . ' ' . escapeshellarg($full) . ' -loop 0 ' . escapeshellarg($tmp) . ' 2>&1', $out, $code);
    if ($code === 0 && is_file($tmp) && filesize($tmp) > 0) {
        @rename($tmp, $full);
    } else {
        @unlink($tmp);
    }
}

/** 头像即时检测的临时暂存：按 register / profile 分开，只允许 uploads/avatars 下的文件 */
function avatar_stage_key($scope)
{
    return $scope === 'profile' ? 'profile' : 'register';
}

function avatar_stage_path($scope)
{
    $slot = avatar_stage_key($scope);
    $entry = $_SESSION['avatar_stages'][$slot] ?? null;
    $path = is_array($entry) ? (string) ($entry['path'] ?? '') : '';
    if (!preg_match('#^uploads/avatars/[A-Za-z0-9._-]+$#', $path) || !is_file(APP_ROOT . '/' . $path)) {
        unset($_SESSION['avatar_stages'][$slot]);
        return '';
    }
    return $path;
}

function avatar_stage_set($scope, $path)
{
    $path = (string) $path;
    if (!preg_match('#^uploads/avatars/[A-Za-z0-9._-]+$#', $path) || !is_file(APP_ROOT . '/' . $path)) {
        throw new Exception('头像暂存文件无效');
    }
    $slot = avatar_stage_key($scope);
    $old = avatar_stage_path($slot);
    if ($old !== '' && $old !== $path) {
        delete_upload($old);
    }
    $_SESSION['avatar_stages'][$slot] = ['path' => $path, 'at' => now()];
    return $path;
}

/** 最终保存时取走暂存路径，但不删除文件（它将成为正式头像） */
function avatar_stage_forget($scope)
{
    unset($_SESSION['avatar_stages'][avatar_stage_key($scope)]);
}

/** 用户取消选择时清空暂存并删除临时文件 */
function avatar_stage_clear($scope)
{
    $slot = avatar_stage_key($scope);
    $path = avatar_stage_path($slot);
    unset($_SESSION['avatar_stages'][$slot]);
    if ($path !== '') {
        delete_upload($path);
    }
}

/** 头像审核总开关 */
function avatar_review_enabled()
{
    return setting('avatar_review_enabled', '0') === '1';
}

/** 当前用户更换头像是否需要审核：管理员与超级管理员始终免审 */
function avatar_review_required_for($user)
{
    return avatar_review_enabled() && $user && !is_admin($user);
}

/** 待审核头像数量 */
function avatar_review_pending_count($userId = 0)
{
    if ($userId > 0) {
        return DB::count('avatar_reviews', 'status = 0 AND user_id = ?', [(int) $userId]);
    }
    return DB::count('avatar_reviews', 'status = 0');
}

/** 清理某用户此前仍在待审核的头像，避免堆积 */
function avatar_review_clear_pending($userId)
{
    $userId = (int) $userId;
    $rows = DB::all('SELECT * FROM ' . DB::table('avatar_reviews') . ' WHERE user_id = ? AND status = 0', [$userId]);
    foreach ($rows as $row) {
        $pendingPath = (string) ($row['new_avatar'] ?? '');
        if (strpos($pendingPath, 'uploads/') === 0) {
            delete_upload($pendingPath);
        }
        $refund = (int) ($row['cost'] ?? 0);
        if ($refund > 0) {
            add_points($userId, $refund);
            DB::insert('point_logs', [
                'user_id' => $userId,
                'action' => 'profile_avatar_refund',
                'delta' => $refund,
                'note' => '重新提交换头像，退回首笔审核费用',
                'created_at' => now(),
            ]);
        }
        DB::delete('avatar_reviews', 'id = ?', [(int) $row['id']]);
    }
}

/** 新头像进入待审核后，通知全部管理员与超级管理员 */
function avatar_review_notify_admins($reviewId, $user)
{
    $reviewId = (int) $reviewId;
    $userId = (int) ($user['id'] ?? 0);
    $name = display_name($user);
    $content = $name . ' 更换了头像，等待审核通过后展示';
    $admins = DB::all('SELECT id FROM ' . DB::table('users') . " WHERE role IN ('admin','superadmin') AND status = 1");
    foreach ($admins as $row) {
        notify((int) $row['id'], $userId, 'avatar_review', $reviewId, $content, page_url('notifications'));
    }
    return count($admins);
}

/** 头像审核通过：替换用户头像并回信 */
function avatar_review_approve($reviewId, $actor)
{
    $reviewId = (int) $reviewId;
    $review = DB::one('SELECT * FROM ' . DB::table('avatar_reviews') . ' WHERE id = ?', [$reviewId]);
    if (!$review || (int) $review['status'] !== 0) {
        return false;
    }
    $user = user_by_id((int) $review['user_id']);
    if (!$user) {
        return false;
    }
    $newAvatar = (string) $review['new_avatar'];
    $oldAvatar = (string) ($user['avatar'] ?? '');
    DB::run('UPDATE ' . DB::table('users') . ' SET avatar = ? WHERE id = ?', [$newAvatar, (int) $user['id']]);
    if ($oldAvatar !== '' && $oldAvatar !== $newAvatar && strpos($oldAvatar, 'uploads/') === 0) {
        delete_upload($oldAvatar);
    }
    DB::run('UPDATE ' . DB::table('avatar_reviews') . ' SET status = 1, reason = ?, reviewer_id = ?, reviewed_at = ? WHERE id = ?', [
        '', (int) ($actor['id'] ?? 0), now(), $reviewId,
    ]);
    profile_change_log((int) $user['id'], 'avatar');
    notify((int) $user['id'], (int) ($actor['id'] ?? 0), 'avatar_approved', $reviewId,
        '你更换的头像已审核通过，现在已正常展示。');
    return true;
}

/** 头像审核驳回：删除待用文件并回信说明理由 */
function avatar_review_reject($reviewId, $reason, $actor)
{
    $reviewId = (int) $reviewId;
    $reason = trim((string) $reason);
    $review = DB::one('SELECT * FROM ' . DB::table('avatar_reviews') . ' WHERE id = ?', [$reviewId]);
    if (!$review || (int) $review['status'] !== 0) {
        return false;
    }
    $newAvatar = (string) $review['new_avatar'];
    if (strpos($newAvatar, 'uploads/') === 0) {
        delete_upload($newAvatar);
    }
    DB::run('UPDATE ' . DB::table('avatar_reviews') . ' SET status = 2, reason = ?, reviewer_id = ?, reviewed_at = ? WHERE id = ?', [
        mb_substr($reason !== '' ? $reason : '头像不符合站点规范', 0, 200), (int) ($actor['id'] ?? 0), now(), $reviewId,
    ]);
    $refund = (int) ($review['cost'] ?? 0);
    if ($refund > 0) {
        add_points((int) $review['user_id'], $refund);
        DB::insert('point_logs', [
            'user_id' => (int) $review['user_id'],
            'action' => 'profile_avatar_refund',
            'delta' => $refund,
            'note' => '头像审核未通过，退回本次费用',
            'created_at' => now(),
        ]);
    }
    notify((int) $review['user_id'], (int) ($actor['id'] ?? 0), 'avatar_rejected', $reviewId,
        '你更换的头像审核未通过' . ($reason !== '' ? '，原因：' . mb_substr($reason, 0, 120) : '') . '。原头像继续保留。');
    return true;
}

/** 个人卡背景审核总开关 */
function profile_bg_review_enabled()
{
    return setting('profile_bg_review_enabled', '0') === '1';
}

/** 当前用户更换个人卡背景是否需要审核：管理员与超级管理员免审 */
function profile_bg_review_required_for($user)
{
    return profile_bg_review_enabled() && $user && !is_admin($user);
}

/** 待审核个人卡背景数量 */
function profile_bg_review_pending_count($userId = 0)
{
    if ($userId > 0) {
        return DB::count('card_bg_reviews', 'status = 0 AND user_id = ?', [(int) $userId]);
    }
    return DB::count('card_bg_reviews', 'status = 0');
}

/** 清理某用户此前仍在待审核的个人卡背景 */
function profile_bg_review_clear_pending($userId)
{
    $rows = DB::all('SELECT * FROM ' . DB::table('card_bg_reviews') . ' WHERE user_id = ? AND status = 0', [(int) $userId]);
    foreach ($rows as $row) {
        foreach (['new_bg', 'new_bg_video'] as $field) {
            $path = (string) ($row[$field] ?? '');
            if ($path !== '' && strpos($path, 'uploads/') === 0) {
                delete_upload($path);
            }
        }
        DB::delete('card_bg_reviews', 'id = ?', [(int) $row['id']]);
    }
}

/** 个人卡边框样式（空字符串表示无边框） */
function profile_frame_options()
{
    return [
        '' => '默认无边框',
        'vine' => '青藤缠绕',
        'ivy' => '常春藤',
        'wisteria' => '紫藤花',
        'sakura' => '樱花枝',
        'fern' => '蕨叶',
        'eucalyptus' => '尤加利',
        'gold' => '金藤蔓',
        'wedding_white' => '白纱 · 珍珠结',
        'wedding_red' => '红纱 · 同心结',
    ];
}

/** 归一化用户个人卡边框 */
function profile_frame_of($user)
{
    $key = trim((string) ($user['profile_frame'] ?? ''));
    return array_key_exists($key, profile_frame_options()) ? $key : '';
}

/** 个人卡边框装饰 HTML */
function profile_frame_html($key)
{
    $key = trim((string) $key);
    if ($key === '' || !array_key_exists($key, profile_frame_options())) {
        return '';
    }
    $class = 'pc-frame frame-' . e($key);
    return '<div class="' . $class . '" aria-hidden="true">'
        . '<span class="pf-edge pf-edge-t"></span><span class="pf-edge pf-edge-b"></span>'
        . '<span class="pf-edge pf-edge-l"></span><span class="pf-edge pf-edge-r"></span>'
        . '<span class="pf-c pf-tl"></span><span class="pf-c pf-tr"></span>'
        . '<span class="pf-c pf-br"></span><span class="pf-c pf-bl"></span>'
        . '</div>';
}

/** 个人卡背景预览 HTML */
function profile_bg_media_html($image, $video = '', $class = '')
{
    $video = trim((string) $video);
    if ($video !== '') {
        $url = preg_match('#^https?://#i', $video) ? $video : upload_url($video);
        return '<video class="' . e(trim($class . ' card-bg-review-media')) . '" src="' . e($url) . '" muted loop playsinline preload="metadata"></video>';
    }
    $image = trim((string) $image);
    if ($image !== '') {
        $url = preg_match('#^https?://#i', $image) ? $image : upload_url($image);
        return '<img class="' . e(trim($class . ' card-bg-review-media')) . '" src="' . e($url) . '" alt="" loading="lazy" decoding="async">';
    }
    return '<span class="' . e(trim($class . ' card-bg-review-empty')) . '">未设置</span>';
}

/** 后台官方通知号专用：保存并压缩个人卡背景图片（最长边 1440px）。 */
function profile_bg_store_admin_image($field, $userId)
{
    if (empty($_FILES[$field]['name'])) {
        return '';
    }
    if (!function_exists('imagecreatefromstring')) {
        throw new Exception('服务器缺少 GD 图像库，无法处理背景图片');
    }
    $stored = upload_store($field, 'profile-bg', [
        'image' => true,
        'allow' => ['jpg', 'jpeg', 'png', 'webp'],
        'max' => 20 * 1024 * 1024,
    ]);
    $src = APP_ROOT . '/' . $stored['path'];
    $raw = @file_get_contents($src);
    if ($raw === false) {
        @unlink($src);
        throw new Exception('无法读取上传的图片');
    }
    $img = @imagecreatefromstring($raw);
    if (!$img) {
        @unlink($src);
        throw new Exception('无法解析这张图片，请换 JPG / PNG / WebP');
    }
    $w = imagesx($img);
    $h = imagesy($img);
    $maxSide = 1440;
    $scale = min(1, $maxSide / max(1, max($w, $h)));
    $tw = max(1, (int) round($w * $scale));
    $th = max(1, (int) round($h * $scale));
    $out = imagecreatetruecolor($tw, $th);
    $white = imagecolorallocate($out, 255, 255, 255);
    imagefill($out, 0, 0, $white);
    imagealphablending($out, true);
    imagecopyresampled($out, $img, 0, 0, 0, 0, $tw, $th, $w, $h);
    $dir = APP_ROOT . '/uploads/profile-bg';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    $hasJpeg = function_exists('imagejpeg') && (imagetypes() & IMG_JPG);
    $file = 'bg_' . (int) $userId . '_' . bin2hex(random_bytes(6)) . ($hasJpeg ? '.jpg' : '.png');
    $full = $dir . '/' . $file;
    $ok = $hasJpeg ? @imagejpeg($out, $full, 90) : @imagepng($out, $full, 6);
    imagedestroy($out);
    imagedestroy($img);
    if (is_file($src) && $src !== $full) {
        @unlink($src);
    }
    if (!$ok || !is_file($full)) {
        throw new Exception('背景图片保存失败，请检查 uploads/profile-bg 目录权限');
    }
    return 'uploads/profile-bg/' . $file;
}

/** 后台官方通知号专用：保存裁剪后的个人卡背景图片（base64）。 */
function profile_bg_store_data_image($dataUrl, $userId)
{
    $dataUrl = (string) $dataUrl;
    if (!preg_match('#^data:image/(jpeg|jpg|png|webp);base64,#i', $dataUrl, $m)) {
        throw new Exception('背景图片格式无效，请重新选择');
    }
    if (!function_exists('imagecreatefromstring')) {
        throw new Exception('服务器缺少 GD 图像库，无法处理背景图片');
    }
    $raw = base64_decode(substr($dataUrl, strpos($dataUrl, ',') + 1), true);
    if ($raw === false || strlen($raw) > 6 * 1024 * 1024) {
        throw new Exception('背景图片过大或数据损坏，请换一张图片');
    }
    $img = @imagecreatefromstring($raw);
    if (!$img) {
        throw new Exception('无法读取这张图片，请换 JPG / PNG / WebP');
    }
    $w = imagesx($img);
    $h = imagesy($img);
    $maxSide = 1440;
    $scale = min(1, $maxSide / max(1, max($w, $h)));
    $tw = max(1, (int) round($w * $scale));
    $th = max(1, (int) round($h * $scale));
    $out = imagecreatetruecolor($tw, $th);
    $white = imagecolorallocate($out, 255, 255, 255);
    imagefill($out, 0, 0, $white);
    imagealphablending($out, true);
    imagecopyresampled($out, $img, 0, 0, 0, 0, $tw, $th, $w, $h);
    $dir = APP_ROOT . '/uploads/profile-bg';
    if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
    $hasJpeg = function_exists('imagejpeg') && (imagetypes() & IMG_JPG);
    $file = 'bg_' . (int) $userId . '_' . bin2hex(random_bytes(6)) . ($hasJpeg ? '.jpg' : '.png');
    $full = $dir . '/' . $file;
    $ok = $hasJpeg ? @imagejpeg($out, $full, 90) : @imagepng($out, $full, 6);
    imagedestroy($out);
    imagedestroy($img);
    if (!$ok || !is_file($full)) {
        throw new Exception('背景图片保存失败，请检查 uploads/profile-bg 目录权限');
    }
    return 'uploads/profile-bg/' . $file;
}

/** 后台官方通知号专用：保存个人卡背景视频。 */
function profile_bg_store_admin_video($field)
{
    if (empty($_FILES[$field]['name'])) {
        return '';
    }
    $stored = upload_store($field, 'profile-bg', [
        'video' => true,
        'allow' => avatar_video_extensions(),
        'max' => 200 * 1024 * 1024,
    ]);
    return (string) $stored['path'];
}

/** 删除官方通知号个人卡背景旧文件（仅限 uploads/profile-bg/）。 */
function profile_bg_delete_media_file($path)
{
    $path = trim((string) $path);
    if ($path !== '' && strpos($path, 'uploads/profile-bg/') === 0 && is_file(APP_ROOT . '/' . $path)) {
        @unlink(APP_ROOT . '/' . $path);
    }
}

/** 新个人卡背景进入待审核后，通知全部管理员与超级管理员 */
function profile_bg_review_notify_admins($reviewId, $user)
{
    $reviewId = (int) $reviewId;
    $userId = (int) ($user['id'] ?? 0);
    $content = display_name($user) . ' 更换了个人卡背景，等待审核通过后展示';
    $admins = DB::all('SELECT id FROM ' . DB::table('users') . " WHERE role IN ('admin','superadmin') AND status = 1");
    foreach ($admins as $row) {
        notify((int) $row['id'], $userId, 'card_bg_review', $reviewId, $content, page_url('notifications'));
    }
    return count($admins);
}

/** 个人卡背景审核通过：替换用户背景并回信 */
function profile_bg_review_approve($reviewId, $actor)
{
    $review = DB::one('SELECT * FROM ' . DB::table('card_bg_reviews') . ' WHERE id = ?', [(int) $reviewId]);
    if (!$review || (int) $review['status'] !== 0) {
        return false;
    }
    $user = user_by_id((int) $review['user_id']);
    if (!$user) {
        return false;
    }
    $newBg = (string) ($review['new_bg'] ?? '');
    $newVideo = (string) ($review['new_bg_video'] ?? '');
    $oldBg = (string) ($user['profile_bg'] ?? '');
    $oldVideo = (string) ($user['profile_bg_video'] ?? '');
    DB::run('UPDATE ' . DB::table('users') . ' SET profile_bg = ?, profile_bg_video = ?, profile_bg_blur = ? WHERE id = ?', [
        $newBg, $newVideo, max(0, min(20, (int) ($review['new_blur'] ?? 0))), (int) $user['id'],
    ]);
    foreach ([[$oldBg, $newBg], [$oldVideo, $newVideo]] as $pair) {
        $old = (string) $pair[0];
        if ($old !== '' && $old !== (string) $pair[1] && strpos($old, 'uploads/') === 0) {
            delete_upload($old);
        }
    }
    DB::run('UPDATE ' . DB::table('card_bg_reviews') . ' SET status = 1, reason = ?, reviewer_id = ?, reviewed_at = ? WHERE id = ?', [
        '', (int) ($actor['id'] ?? 0), now(), (int) $reviewId,
    ]);
    notify((int) $user['id'], (int) ($actor['id'] ?? 0), 'card_bg_approved', (int) $reviewId,
        '你更换的个人卡背景已审核通过，现在已显示在个人主页。');
    return true;
}

/** 个人卡背景驳回：删除待用文件并回信说明理由 */
function profile_bg_review_reject($reviewId, $reason, $actor)
{
    $reason = trim((string) $reason);
    $review = DB::one('SELECT * FROM ' . DB::table('card_bg_reviews') . ' WHERE id = ?', [(int) $reviewId]);
    if (!$review || (int) $review['status'] !== 0) {
        return false;
    }
    foreach (['new_bg', 'new_bg_video'] as $field) {
        $path = (string) ($review[$field] ?? '');
        if ($path !== '' && strpos($path, 'uploads/') === 0) {
            delete_upload($path);
        }
    }
    $reason = mb_substr($reason !== '' ? $reason : '个人卡背景不符合站点规范', 0, 200);
    DB::run('UPDATE ' . DB::table('card_bg_reviews') . ' SET status = 2, reason = ?, reviewer_id = ?, reviewed_at = ? WHERE id = ?', [
        $reason, (int) ($actor['id'] ?? 0), now(), (int) $reviewId,
    ]);
    notify((int) $review['user_id'], (int) ($actor['id'] ?? 0), 'card_bg_rejected', (int) $reviewId,
        '你更换的个人卡背景审核未通过' . ($reason !== '' ? '，原因：' . mb_substr($reason, 0, 120) : '') . '。原背景继续保留。');
    return true;
}

/** 头像自动检测开关 */
function avatar_auto_check_enabled()
{
    // 默认开启；管理员在后台明确关闭后才停止检测。
    return setting('avatar_auto_check', '1') === '1';
}

/**
 * 扫描一张 GD 图像：返回整体肤色比例、中心区域比例、下半身区域比例与分数。
 * 用抽样后的 96×96 图像计算，避免大图逐像素扫描拖慢上传。
 */
function avatar_skin_scan_gd($src)
{
    $w = imagesx($src);
    $h = imagesy($src);
    $sample = 96;
    $dst = imagecreatetruecolor($sample, $sample);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $sample, $sample, $w, $h);
    $skin = $total = $centerSkin = $centerTotal = $lowerSkin = $lowerTotal = 0;
    for ($y = 2; $y < $sample; $y += 2) {
        for ($x = 2; $x < $sample; $x += 2) {
            $rgb = imagecolorat($dst, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $total++;
            $isSkin = ($r > 70 && $g > 35 && $b > 20 && $r > $g + 8 && $g >= $b - 12 && $r - $b > 18 && ($r + $g + $b) > 140);
            if ($isSkin) $skin++;
            if ($x > 22 && $x < 74 && $y > 22 && $y < 74) {
                $centerTotal++;
                if ($isSkin) $centerSkin++;
            }
            if ($y > 53) {
                $lowerTotal++;
                if ($isSkin) $lowerSkin++;
            }
        }
    }
    imagedestroy($dst);
    return [
        'ratio' => $total > 0 ? $skin / $total : 0,
        'center' => $centerTotal > 0 ? $centerSkin / $centerTotal : 0,
        'lower' => $lowerTotal > 0 ? $lowerSkin / $lowerTotal : 0,
        'score' => (int) round(($total > 0 ? $skin / $total : 0) * 100),
    ];
}

/** 打开一帧图片并返回肤色扫描结果；无法识别时返回 null。 */
function avatar_skin_scan_file($path, $ext = '')
{
    if (!function_exists('imagecreatefromstring')) return null;
    $im = @imagecreatefromstring((string) @file_get_contents($path));
    if (!$im) return null;
    $result = avatar_skin_scan_gd($im);
    imagedestroy($im);
    return $result;
}

/**
 * 用 ffmpeg 从 GIF/视频里抽取最多 8 帧（每秒 1 帧，最多前 8 秒）。
 * 返回临时帧文件路径数组；没有 ffmpeg 时返回空数组。
 */
function avatar_extract_frames($full, $ext)
{
    static $ffmpeg = null;
    if ($ffmpeg === null) {
        $ffmpeg = '';
        $out = [];
        $code = 1;
        @exec('command -v ffmpeg 2>/dev/null', $out, $code);
        if ($code === 0 && !empty($out[0])) $ffmpeg = trim((string) $out[0]);
    }
    if ($ffmpeg === '' || !function_exists('exec')) return [];
    $dir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'km_avatar_frames_' . bin2hex(random_bytes(6));
    if (!@mkdir($dir, 0700, true)) return [];
    $pattern = $dir . DIRECTORY_SEPARATOR . 'f%02d.png';
    $cmd = escapeshellarg($ffmpeg) . ' -nostdin -v error -i ' . escapeshellarg($full)
        . ' -t 8 -vf ' . escapeshellarg('fps=1,scale=96:96:force_original_aspect_ratio=decrease,pad=96:96:(ow-iw)/2:(oh-ih)/2:color=black')
        . ' -frames:v 8 -pix_fmt rgb24 ' . escapeshellarg($pattern) . ' 2>/dev/null';
    @exec($cmd, $out, $code);
    $frames = glob($dir . DIRECTORY_SEPARATOR . 'f*.png') ?: [];
    sort($frames);
    if (count($frames) > 6) $frames = array_slice($frames, 0, 6);
    return [$dir, $frames];
}

function avatar_cleanup_frames($dir, $frames)
{
    foreach ($frames as $frame) { @unlink($frame); }
    if ($dir !== '' && is_dir($dir)) { @rmdir($dir); }
}

/**
 * 头像违规自动初筛（本地算法，不依赖外部接口）
 * 支持静态图片、GIF 多帧、视频抽帧；返回 [是否违规, 理由, 分数]。
 */
function avatar_auto_check($avatarPath)
{
    if (!avatar_auto_check_enabled()) {
        return [false, '', 0];
    }
    $avatarPath = (string) $avatarPath;
    if (!preg_match('#^uploads/#', $avatarPath)) {
        return [false, '', 0];
    }
    $ext = strtolower(pathinfo((string) parse_url($avatarPath, PHP_URL_PATH), PATHINFO_EXTENSION));
    $imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    $videoExts = avatar_video_extensions();
    if (!in_array($ext, array_merge($imageExts, $videoExts), true)) {
        return [false, '', 0];
    }
    $full = APP_ROOT . '/' . $avatarPath;
    if (!is_file($full)) {
        return [false, '', 0];
    }
    if (!function_exists('imagecreatetruecolor') || !function_exists('imagecreatefromstring')) {
        return [false, '', 0];
    }

    $isVideo = in_array($ext, $videoExts, true);
    $isAnimated = $ext === 'gif' || $isVideo;
    $frames = [];
    $frameDir = '';
    $scores = [];

    if ($isAnimated) {
        $extracted = avatar_extract_frames($full, $ext);
        if ($extracted) { $frameDir = $extracted[0]; $frames = $extracted[1]; }
        if ($isVideo && !$frames) {
            // 视频无法抽帧时不冒充已检测；保留上传，由后台人工复核。
            return [false, '', 0];
        }
        foreach ($frames as $frame) {
            $scan = avatar_skin_scan_file($frame, 'png');
            if ($scan) $scores[] = $scan;
        }
    } else {
        $scan = avatar_skin_scan_file($full, $ext);
        if (!$scan) return [false, '', 0];
        $scores[] = $scan;
    }

    if (!$scores) {
        if ($isAnimated) avatar_cleanup_frames($frameDir, $frames);
        return [false, '', 0];
    }

    $maxScore = 0;
    $bad = false;
    $badRatio = 0;
    foreach ($scores as $scan) {
        $maxScore = max($maxScore, (int) $scan['score']);
        // 大面积裸露肤色：整体占比很高，或躯干下半部分与中心同时高。
        if ($scan['ratio'] >= 0.66
            || ($scan['center'] >= 0.66 && $scan['lower'] >= 0.60 && $scan['ratio'] >= 0.55)) {
            $bad = true;
            $badRatio = max($badRatio, (float) $scan['ratio']);
        }
    }
    if ($isAnimated) avatar_cleanup_frames($frameDir, $frames);

    if ($bad) {
        $type = $isVideo ? '视频头像' : ($ext === 'gif' ? 'GIF 头像' : '头像');
        return [true, '自动检测发现' . $type . '中有大面积肤色，可能包含不适宜内容，请更换为风景、角色或物件头像', $maxScore];
    }
    return [false, '', $maxScore];
}

/** 昵称违禁词（手动词库 + 站点敏感词） */
function nickname_banned_words()
{
    $raw = (string) setting('nickname_banned_words', '');
    $raw .= "\n" . (string) setting('sensitive_words', '');
    $lines = preg_split('/[\x{FF0C}\x{3000}\r\n,，]+/u', $raw) ?: [];
    $words = [];
    foreach ($lines as $line) {
        $word = trim($line);
        if ($word !== '') {
            $words[mb_strtolower($word)] = $word;
        }
    }
    return array_values($words);
}

/** 昵称违规检测：管理员与超级管理员免检 */
function nickname_check($nickname, $user = null)
{
    if (is_admin($user)) {
        return [true, ''];
    }
    if (setting('nickname_auto_check', '0') !== '1' && trim((string) setting('nickname_banned_words', '')) === '') {
        return [true, ''];
    }
    $name = mb_strtolower(trim((string) $nickname));
    if ($name === '') {
        return [true, ''];
    }
    $words = nickname_banned_words();
    foreach ($words as $word) {
        if (mb_strpos($name, mb_strtolower($word)) !== false) {
            return [false, '昵称包含违禁词「' . $word . '」，请修改后重试'];
        }
    }
    return [true, ''];
}

/** 保存注册时前端裁剪好的头像 DataURL，返回 uploads/avatars 下的相对路径 */
function save_avatar_data_url($dataUrl)
{
    $dataUrl = trim((string) $dataUrl);
    if ($dataUrl === '') {
        return '';
    }
    if (!preg_match('#^data:image/(png|jpeg|jpg|webp);base64,#i', $dataUrl, $m)) {
        throw new Exception('头像裁剪数据格式不正确');
    }
    $payload = substr($dataUrl, strlen($m[0]));
    // iOS Safari 的 canvas.toDataURL 偶尔会把 base64 里的“+”变成空格，或在
    // 长字符串中插入换行；先做归一化再解码，避免误报“裁剪数据损坏”。
    $payload = str_replace(' ', '+', $payload);
    $payload = preg_replace('/\s+/', '', $payload);
    $payload = strtr($payload, '-_', '+/');
    $mod = strlen($payload) % 4;
    if ($mod) {
        $payload .= str_repeat('=', 4 - $mod);
    }
    $raw = base64_decode($payload, true);
    if ($raw === false) {
        // 极少数 WebView 会夹带非法字符；交给 imagecreatefromstring 做最终校验。
        $raw = base64_decode(preg_replace('/[^A-Za-z0-9+\/=]/', '', $payload), false);
    }
    if ($raw === false || $raw === '') {
        throw new Exception('头像裁剪数据损坏，请重新选择图片');
    }
    if (strlen($raw) > 8 * 1024 * 1024) {
        throw new Exception('裁剪后的头像过大，请压缩后重试');
    }
    if (!function_exists('imagecreatefromstring')) {
        throw new Exception('服务器缺少 GD 图像扩展，暂时无法处理裁剪头像');
    }
    $img = @imagecreatefromstring($raw);
    if (!$img) {
        throw new Exception('头像图片无法识别');
    }
    $w = imagesx($img);
    $h = imagesy($img);
    $size = 512;
    $out = imagecreatetruecolor($size, $size);
    imagealphablending($out, false);
    imagesavealpha($out, true);
    $transparent = imagecolorallocatealpha($out, 0, 0, 0, 127);
    imagefilledrectangle($out, 0, 0, $size, $size, $transparent);
    imagecopyresampled($out, $img, 0, 0, 0, 0, $size, $size, $w, $h);
    imagedestroy($img);
    $dir = APP_ROOT . '/uploads/avatars';
    if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
        imagedestroy($out);
        throw new Exception('头像目录创建失败');
    }
    $filename = 'reg_' . date('Ymd') . '_' . random_string(12) . '.png';
    $full = $dir . '/' . $filename;
    if (!@imagepng($out, $full, 6)) {
        imagedestroy($out);
        throw new Exception('头像写入失败');
    }
    imagedestroy($out);
    return 'uploads/avatars/' . $filename;
}

/** 用户名可见性：管理员可见全部，本人可见自己；其他普通用户显示“已隐藏”。 */
function username_visible($user, $viewer = null)
{
    if (is_numeric($user)) {
        $user = user_by_id((int) $user);
    }
    if (!$user) {
        return '已隐藏';
    }
    $username = trim((string) ($user['username'] ?? ''));
    if ($username === '') {
        return '已隐藏';
    }
    if ($viewer === null) {
        $viewer = function_exists('current_user') ? current_user() : null;
    }
    if (is_admin($viewer)) {
        return $username;
    }
    if ($viewer && (int) ($viewer['id'] ?? 0) > 0 && (int) ($viewer['id'] ?? 0) === (int) ($user['id'] ?? 0)) {
        return $username;
    }
    return '已隐藏';
}

function display_name($user)
{
    if (is_numeric($user)) {
        $user = user_by_id((int) $user);
    }
    if (!$user) {
        return '已注销用户';
    }
    $name = $user['nickname'] !== '' ? $user['nickname'] : username_visible($user);
    // 当前登录用户给好友设置的备注名全站生效（帖子、网盘、世界圈、评论、通知等）
    static $remarkCache = [];
    $viewer = function_exists('current_user') ? current_user() : null;
    // 通知行同时带 user_id（收件人）和 from_id（发件人），备注要取发件人。
    if (array_key_exists('from_id', $user)) {
        $uid = (int) $user['from_id'];
    } elseif (array_key_exists('user_id', $user)) {
        $uid = (int) $user['user_id'];
    } elseif (array_key_exists('friend_id', $user)) {
        $uid = (int) $user['friend_id'];
    } else {
        $uid = (int) ($user['id'] ?? 0);
    }
    $viewerId = $viewer ? (int) ($viewer['id'] ?? 0) : 0;
    if ($viewerId > 0 && $uid > 0 && $uid !== $viewerId) {
        $key = $viewerId . ':' . $uid;
        if (!array_key_exists($key, $remarkCache)) {
            $remarkCache[$key] = (string) DB::val('SELECT remark FROM ' . DB::table('friends') . ' WHERE user_id = ? AND friend_id = ?', [$viewerId, $uid], '');
        }
        if ($remarkCache[$key] !== '') {
            $name = $remarkCache[$key];
        }
    }
    return $name;
}

function gender_text($gender)
{
    $map = ['male' => '男', 'female' => '女', 'secret' => '保密'];
    return $map[$gender] ?? '保密';
}

function gender_icon($gender)
{
    if ($gender === 'male') {
        return '♂';
    }
    if ($gender === 'female') {
        return '♀';
    }
    return '·';
}

function level_of($points)
{
    $points = (int) $points;
    static $names = null;
    if ($names === null) {
        $names = json_decode((string) setting('level_names', ''), true);
        if (!is_array($names) || count($names) < 5) {
            $names = ['初雪', '霜华', '白鹭', '神里流', '霜见'];
        }
    }
    static $needs = null;
    if ($needs === null) {
        $defaults = [100, 200, 500, 1200];
        $needs = [];
        for ($i = 1; $i <= 4; $i++) {
            $n = (int) setting('level_up_' . $i, (string) $defaults[$i - 1]);
            $needs[] = max(1, min(99999, $n));
        }
    }
    $levels = [];
    $min = 0;
    for ($i = 0; $i < 5; $i++) {
        $need = $i < 4 ? (int) $needs[$i] : 0;
        $levels[] = ['min' => $min, 'name' => $names[$i], 'next' => $need ? $min + $need : 0];
        $min += $need;
    }
    $idx = 0;
    foreach ($levels as $i => $lv) {
        if ($points >= $lv['min']) {
            $idx = $i;
        }
    }
    $cur = $levels[$idx];
    $next = $cur['next'];
    $progress = $next ? min(100, (int) round(($points - $cur['min']) / max(1, $next - $cur['min']) * 100)) : 100;
    return [
        'level'    => $idx + 1,
        'name'     => $cur['name'],
        'points'   => $points,
        'min'      => $cur['min'],
        'next'     => $next,
        'to_next'  => $next ? max(0, $next - $points) : 0,
        'progress' => $progress,
    ];
}

function is_admin($user = null)
{
    if ($user === null) {
        $user = current_user();
    }
    return $user && in_array($user['role'], ['admin', 'superadmin'], true);
}

/** 积分流水动作的中文名称 */
function point_action_label($action)
{
    $map = [
        'checkin'      => '每日签到',
        'post'         => '发布帖子',
        'comment'      => '发表评论',
        'like'         => '点赞',
        'fav'          => '收藏',
        'fishing'      => '钓鱼兑换',
        'fishing_cast' => '钓鱼投入',
        'fishing_win'  => '钓鱼返还',
        'transfer_in'  => '收到转账',
        'transfer_out' => '转出积分',
        'admin'        => '管理员调整',
        'admin_edit'   => '管理员修改',
        'profile'      => '资料修改',
        'verify'       => '认证支付',
        'verify_refund'=> '认证退款',
        'download'     => '下载附件',
        'purchase'     => '购买内容',
        'pay'          => '积分支付',
        'plugin_buy'   => '购买插件',
    ];
    $action = (string) $action;
    return $map[$action] ?? ($action !== '' ? $action : '积分变动');
}

function points_text($user)
{
    if (is_numeric($user)) {
        $user = user_by_id((int) $user);
    }
    if ($user && ($user['role'] ?? '') === 'superadmin') {
        return '∞';
    }
    return (string) (int) ($user['points'] ?? 0);
}

function account_is_protected($user)
{
    return $user && (int) ($user['account_protected'] ?? 0) === 1;
}

/** 当前站点唯一的超级管理员 */
function superadmin_account()
{
    return DB::one('SELECT * FROM ' . DB::table('users') . " WHERE role = 'superadmin' LIMIT 1");
}

/** 超级管理员保护锁是否开启（必须同时有已设置的安全码） */
function superadmin_lock_is_on()
{
    return setting('superadmin_lock_state', '0') === '1'
        && setting('superadmin_lock_hash', '') !== '';
}

/** 校验 6 位安全码格式 */
function superadmin_lock_code_format_ok($code)
{
    return preg_match('/^\d{6}$/', (string) $code) === 1;
}

/** 当前是否处于安全码错误锁定冷却 */
function superadmin_lock_rate_limited()
{
    $fails = (int) setting('superadmin_lock_fails', '0');
    $last = (int) setting('superadmin_lock_fail_at', '0');
    return $fails >= 5 && $last > 0 && time() - $last < 600;
}

/** 记录一次安全码错误，5 次后锁 10 分钟 */
function superadmin_lock_record_failure()
{
    $fails = (int) setting('superadmin_lock_fails', '0');
    $last = (int) setting('superadmin_lock_fail_at', '0');
    if ($last > 0 && time() - $last >= 600) {
        $fails = 0;
    }
    $fails++;
    set_setting('superadmin_lock_fails', (string) $fails);
    set_setting('superadmin_lock_fail_at', (string) time());
}

function superadmin_lock_clear_failures()
{
    set_setting('superadmin_lock_fails', '0');
    set_setting('superadmin_lock_fail_at', '0');
}

/** 验证 6 位安全码；通过后清除错误计数 */
function superadmin_lock_verify_code($code)
{
    if (!superadmin_lock_is_on() || !superadmin_lock_code_format_ok($code) || superadmin_lock_rate_limited()) {
        return false;
    }
    if (password_verify((string) $code, setting('superadmin_lock_hash', ''))) {
        superadmin_lock_clear_failures();
        return true;
    }
    superadmin_lock_record_failure();
    return false;
}

/** 开启保护并写入安全码哈希 */
function superadmin_lock_enable($code)
{
    set_setting('superadmin_lock_hash', password_hash((string) $code, PASSWORD_DEFAULT));
    set_setting('superadmin_lock_state', '1');
    superadmin_lock_clear_failures();
}

/** 关闭保护并清空安全码 */
function superadmin_lock_disable()
{
    set_setting('superadmin_lock_state', '0');
    set_setting('superadmin_lock_hash', '');
    superadmin_lock_clear_failures();
}

/** 给超级管理员绑定邮箱发送解锁验证码 */
function superadmin_lock_send_email_code()
{
    $sa = superadmin_account();
    if (!$sa) {
        return [false, '未找到超级管理员账号'];
    }
    $email = trim((string) ($sa['email'] ?? ''));
    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return [false, '超级管理员尚未绑定有效邮箱，请先关闭保护并设置邮箱'];
    }

    $code = sprintf('%06d', random_int(0, 999999));
    DB::insert('email_codes', [
        'user_id'    => (int) $sa['id'],
        'email'      => $email,
        'code'       => $code,
        'purpose'    => 'superadmin_unlock',
        'expires_at' => time() + 600,
        'used'       => 0,
    ]);
    $siteName = setting('site_name', '木漏茶室');
    $html = mail_verification_card([
        'site' => $siteName,
        'title' => '超级管理员保护解锁',
        'intro' => display_name($sa) . '，你正在关闭「' . $siteName . '」的超级管理员保护锁。',
        'code' => $code,
        'note' => '验证码 10 分钟内有效。若非本人操作，请立即检查账号安全。',
        'badge' => 'ADMIN UNLOCK',
    ]);
    list($ok, $msg) = send_mail($email, $siteName . ' 超级管理员保护解锁验证码', $html);
    $_SESSION['sa_lock_email_sent'] = 1;
    $_SESSION['sa_lock_email_attempts'] = 0;
    return [$ok, ($ok ? '解锁验证码已发送到 ' : '邮件未能发送：') . $email . ($ok ? '' : '（' . $msg . '，验证码也会记录在 data/mail.log）')];
}

/** 用绑定邮箱验证码关闭保护 */
function superadmin_lock_consume_email_code($code)
{
    $sa = superadmin_account();
    if (!$sa) {
        return [false, '未找到超级管理员账号'];
    }
    $attempts = (int) ($_SESSION['sa_lock_email_attempts'] ?? 0);
    if ($attempts >= 5) {
        return [false, '验证码错误次数过多，请重新获取验证码'];
    }
    $code = trim((string) $code);
    if (!preg_match('/^\d{6}$/', $code)) {
        $_SESSION['sa_lock_email_attempts'] = $attempts + 1;
        return [false, '请输入 6 位数字验证码'];
    }
    $row = DB::one(
        'SELECT * FROM ' . DB::table('email_codes') . '
         WHERE user_id = ? AND purpose = ? AND code = ? AND used = 0 AND expires_at > ?
         ORDER BY id DESC LIMIT 1',
        [(int) $sa['id'], 'superadmin_unlock', $code, time()]
    );
    if (!$row) {
        $_SESSION['sa_lock_email_attempts'] = $attempts + 1;
        return [false, '验证码错误或已过期'];
    }
    DB::run('UPDATE ' . DB::table('email_codes') . ' SET used = 1 WHERE id = ?', [(int) $row['id']]);
    superadmin_lock_disable();
    unset($_SESSION['sa_lock_email_sent'], $_SESSION['sa_lock_email_attempts']);
    return [true, '邮箱验证通过，超级管理员保护已关闭'];
}

function is_superadmin($user = null)
{
    if ($user === null) {
        $user = current_user();
    }
    return $user && $user['role'] === 'superadmin';
}

/** 系统升级专用超级管理员：必须是超级管理员，且已绑定指定邮箱。 */
function is_upgrade_superadmin($user = null)
{
    if ($user === null) {
        $user = current_user();
    }
    if (!is_superadmin($user)) {
        return false;
    }
    return strtolower(trim((string) ($user['email'] ?? ''))) === strtolower(UPGRADE_OWNER_EMAIL);
}

/** 部署页创建的管理员：永久锁定超级管理员身份，不能移交、降级或注销。 */
function is_installer_admin($user)
{
    return $user && is_array($user) && (int) ($user['is_installer_admin'] ?? 0) === 1;
}

/** 账号是否禁止自助修改用户名 / 密码：普通账号保护，或超级管理员保护锁开启 */
function account_self_service_locked($user)
{
    if (!$user) {
        return false;
    }
    if (account_is_protected($user)) {
        return true;
    }
    return ($user['role'] ?? '') === 'superadmin' && superadmin_lock_is_on();
}

/**
 * 是否允许用户自行绑定 / 更换邮箱。
 * 所有普通用户都可以使用；受保护账号仅允许在尚未绑定邮箱时完成首次绑定，
 * 超级管理员保护锁开启时仍然禁止，避免保护锁被邮件验证码绕过。
 */
/** 读取账号当前真实邮箱验证状态，避免不同页面拿到过期数据后显示不一致 */
function email_verified_fresh($user)
{
    if (!$user) {
        return false;
    }
    $id = (int) ($user['id'] ?? 0);
    if ($id <= 0) {
        return false;
    }
    $value = DB::val('SELECT email_verified FROM ' . DB::table('users') . ' WHERE id = ?', [$id], 0);
    return (int) $value === 1;
}

/** 源码下载中心严格访问限制只对 csrc.954377.xyz 生效，其他站点保持原样。 */
function source_center_host_restricted()
{
    $host = strtolower(trim((string) ($_SERVER['HTTP_HOST'] ?? '')));
    $host = preg_replace('/:\d+$/', '', $host);
    return $host === 'csrc.954377.xyz';
}

/** csrc 站点同时关闭在线升级入口与后台升级能力，其他站点不受影响。 */
function site_upgrade_host_restricted()
{
    return source_center_host_restricted();
}

/**
 * 判断当前用户能否进入源码下载中心。
 * csrc.954377.xyz 站点关闭源码下载中心入口，其他站点保持原样。
 */
function source_center_access_state($user = null)
{
    if (!source_center_host_restricted()) {
        return ['allowed' => true, 'reason' => ''];
    }
    return ['allowed' => false, 'reason' => 'disabled'];
}

function email_binding_allowed($user)
{
    if (!$user) {
        return false;
    }
    if (($user['role'] ?? '') === 'superadmin' && superadmin_lock_is_on()) {
        return false;
    }
    if (trim((string) ($user['email'] ?? '')) === '') {
        return true;
    }
    return !account_is_protected($user);
}

/** 角色名称 */
function role_options()
{
    return [
        'user'      => '普通用户',
        'moderator' => '版主',
        'vip'       => '贵宾',
        'admin'     => '管理员',
        'superadmin' => '超级管理员',
    ];
}

function role_label($role)
{
    $options = role_options();
    return $options[(string) $role] ?? '普通用户';
}

/** 普通用户 / 管理员可单独开关的前台功能 */
function site_feature_registry()
{
    return [
        'post'       => '发帖与编辑',
        'comment'    => '评论与回复',
        'like'       => '点赞',
        'favorite'   => '收藏',
        'report'     => '举报',
        'friends'    => '好友与私信',
        'chat_room'  => '聊天大厅',
        'world'      => '世界圈',
        'gallery'    => '图床',
        'netdisk'    => '网盘',
        'checkin'    => '每日签到',
        'transfer'   => '积分转账',
        'download'   => '附件下载',
        'verify'     => '认证申请',
    ];
}

/** 功能权限：未单独配置时默认全部开放 */
function user_feature_enabled($user, $key)
{
    if (!$user) {
        return true;
    }
    if (($user['role'] ?? '') === 'superadmin') {
        return true;
    }
    $raw = trim((string) ($user['feature_perms'] ?? ''));
    if ($raw === '') {
        return true;
    }
    $perms = json_decode($raw, true);
    if (!is_array($perms)) {
        return true;
    }
    return !array_key_exists($key, $perms) || (int) $perms[$key] === 1;
}

/** 页面入口功能校验：未开放时返回首页 */
function feature_guard($key)
{
    $user = current_user();
    if ($user && !user_feature_enabled($user, $key)) {
        $labels = site_feature_registry();
        flash('「' . ($labels[$key] ?? '该功能') . '」已被管理员关闭', 'err');
        redirect(page_url('home'));
    }
}

/** 当前用户是否被关闭了某个功能 */
function feature_denied($user, $key)
{
    return $user && !user_feature_enabled($user, $key);
}

/** 签到随机积分范围 */
function checkin_reward_points()
{
    $min = max(0, (int) setting('points_checkin_min', 1));
    $max = max($min, (int) setting('points_checkin_max', 5));
    if ($max <= 0) {
        return 0;
    }
    return random_int($min, $max);
}

/** 执行签到，返回 [是否成功, 提示, 连续天数, 获得积分] */
function perform_checkin($user)
{
    if (!$user) {
        return [false, '请先登录', 0, 0];
    }
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));
    if ((string) ($user['last_checkin'] ?? '') === $today) {
        return [false, '今天已经签到过了，明天再来吧', (int) ($user['streak'] ?? 0), 0];
    }
    $streak = ((string) ($user['last_checkin'] ?? '') === $yesterday) ? (int) ($user['streak'] ?? 0) + 1 : 1;
    $points = checkin_reward_points();
    DB::run('UPDATE ' . DB::table('users') . ' SET streak = ?, last_checkin = ? WHERE id = ?', [$streak, $today, (int) $user['id']]);
    if ($points > 0) {
        add_points((int) $user['id'], $points);
        DB::insert('point_logs', [
            'user_id'    => (int) $user['id'],
            'action'     => 'checkin',
            'delta'      => $points,
            'note'       => '每日签到随机奖励 ' . $points . ' 积分',
            'created_at' => now(),
        ]);
    }
    return [true, '签到成功，连续 ' . $streak . ' 天' . ($points > 0 ? '，+' . $points . ' 积分' : ''), $streak, $points];
}

/** 邮箱脱敏展示 */
function email_mask($email)
{
    $email = trim((string) $email);
    if ($email === '' || strpos($email, '@') === false) {
        return $email;
    }
    list($name, $domain) = explode('@', $email, 2);
    $visible = mb_substr($name, 0, 2);
    return $visible . str_repeat('*', max(2, mb_strlen($name) - 2)) . '@' . $domain;
}

/** 更换邮箱：发送验证码到原绑定邮箱；未绑定时发送到新邮箱 */
function email_change_send_code($user, $newEmail)
{
    if (!$user) {
        return [false, '请先登录'];
    }
    if (!email_binding_allowed($user)) {
        return [false, '当前账号处于保护状态，已有邮箱不能自行更换，请联系管理员'];
    }
    $newEmail = trim((string) $newEmail);
    if ($newEmail === '' || !filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
        return [false, '请输入有效的邮箱地址'];
    }
    if ($newEmail === (string) ($user['email'] ?? '')) {
        return [false, '新邮箱与当前绑定邮箱相同'];
    }
    if (DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE email = ? AND email <> \'\' AND id <> ?', [$newEmail, (int) $user['id']])) {
        return [false, '该邮箱已被其他账号绑定'];
    }
    $oldEmail = trim((string) ($user['email'] ?? ''));
    $source = ($oldEmail !== '' && filter_var($oldEmail, FILTER_VALIDATE_EMAIL)) ? $oldEmail : $newEmail;
    $code = sprintf('%06d', random_int(0, 999999));
    DB::insert('email_codes', [
        'user_id'    => (int) $user['id'],
        'email'      => $source,
        'code'       => $code,
        'purpose'    => 'email_change',
        'expires_at' => time() + 600,
        'used'       => 0,
    ]);
    $siteName = setting('site_name', '木漏茶室');
    $html = mail_verification_card([
        'site' => $siteName,
        'title' => '更换绑定邮箱',
        'intro' => display_name($user) . '，你正在更换「' . $siteName . '」账号的绑定邮箱，新邮箱为：' . $newEmail . '。',
        'code' => $code,
        'note' => '验证码 10 分钟内有效。若非本人操作，请忽略本邮件并检查账号安全。',
        'badge' => 'EMAIL CHANGE',
        'link' => full_url('index.php'),
        'link_label' => '打开木漏茶室',
    ]);
    list($ok, $msg) = send_mail($source, $siteName . ' 更换绑定邮箱验证码', $html);
    $_SESSION['email_change_uid'] = (int) $user['id'];
    $_SESSION['email_change_new'] = $newEmail;
    $_SESSION['email_change_source'] = $source;
    $_SESSION['email_change_attempts'] = 0;
    return [$ok, ($ok ? '验证码已发送到 ' : '邮件未能发送：') . email_mask($source) . ($ok ? '' : '（' . $msg . '，验证码也会记录在 data/mail.log）')];
}

/** 校验邮箱验证码并更新邮箱 */
function email_change_confirm($user, $code)
{
    if (!$user) {
        return [false, '请先登录'];
    }
    if (!email_binding_allowed($user)) {
        return [false, '当前账号处于保护状态，已有邮箱不能自行更换，请联系管理员'];
    }
    if ((int) ($_SESSION['email_change_uid'] ?? 0) !== (int) $user['id']) {
        return [false, '会话已过期，请重新获取验证码'];
    }
    $attempts = (int) ($_SESSION['email_change_attempts'] ?? 0);
    if ($attempts >= 5) {
        return [false, '验证码错误次数过多，请重新获取验证码'];
    }
    $code = trim((string) $code);
    if (!preg_match('/^\d{6}$/', $code)) {
        $_SESSION['email_change_attempts'] = $attempts + 1;
        return [false, '请输入 6 位数字验证码'];
    }
    $newEmail = trim((string) ($_SESSION['email_change_new'] ?? ''));
    if ($newEmail === '' || !filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
        return [false, '待绑定的新邮箱无效，请重新发起'];
    }
    if ($newEmail !== (string) ($user['email'] ?? '')
        && DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE email = ? AND email <> \'\' AND id <> ?', [$newEmail, (int) $user['id']])) {
        return [false, '该邮箱已被其他账号绑定'];
    }
    $row = DB::one(
        'SELECT * FROM ' . DB::table('email_codes') . '
         WHERE user_id = ? AND purpose = ? AND code = ? AND used = 0 AND expires_at > ?
         ORDER BY id DESC LIMIT 1',
        [(int) $user['id'], 'email_change', $code, time()]
    );
    if (!$row) {
        $_SESSION['email_change_attempts'] = $attempts + 1;
        return [false, '验证码错误或已过期'];
    }
    // 新邮箱若是从“未绑定邮箱”直接绑定的，验证码发到了新邮箱，视为已验证；
    // 若原本已有邮箱，验证码只证明原邮箱，新邮箱需要重新验证，状态重置为未验证。
    $oldEmail = trim((string) ($user['email'] ?? ''));
    $newVerified = $oldEmail === '' ? 1 : 0;
    DB::run('UPDATE ' . DB::table('users') . ' SET email = ?, email_verified = ? WHERE id = ?', [$newEmail, $newVerified, (int) $user['id']]);
    DB::run('UPDATE ' . DB::table('email_codes') . ' SET used = 1 WHERE id = ?', [(int) $row['id']]);
    unset($_SESSION['email_change_uid'], $_SESSION['email_change_new'], $_SESSION['email_change_source'], $_SESSION['email_change_attempts']);
    return [true, '邮箱已更新为 ' . $newEmail];
}

function add_points($userId, $delta)
{
    if (!$userId) {
        return;
    }
    $user = user_by_id((int) $userId);
    if ($user && ($user['role'] ?? '') === 'superadmin') {
        return;
    }
    $delta = (int) $delta;
    // 消耗积分不减少经验；获得积分时同步增加经验
    if ($delta > 0) {
        DB::run('UPDATE ' . DB::table('users') . ' SET points = points + ?, exp = exp + ? WHERE id = ?', [$delta, $delta, (int) $userId]);
    } else {
        DB::run('UPDATE ' . DB::table('users') . ' SET points = points + ? WHERE id = ?', [$delta, (int) $userId]);
    }
}

/**
 * 按后台积分规则发放奖励：支持每日有效次数、超限后不发或倒扣
 */
function reward_points($userId, $action, $refId = 0)
{
    $baseKey = 'points_' . $action;
    $base = (int) setting($baseKey, $action === 'post' ? 5 : ($action === 'comment' ? 2 : 3));
    $limit = in_array($action, ['post', 'comment'], true) ? (int) setting('points_' . $action . '_limit', 0) : 0;
    $today = date('Y-m-d 00:00:00');
    $used = 0;
    if ($limit > 0) {
        $used = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('point_logs') . ' WHERE user_id = ? AND action = ? AND created_at >= ?', [$userId, $action, $today], 0);
    }
    $delta = $base;
    $note = '正常奖励';
    if ($limit > 0 && $used >= $limit) {
        if (setting('points_over_action', 'none') === 'deduct') {
            $delta = -$base;
            $note = '超过每日有效次数，倒扣奖励';
        } else {
            $delta = 0;
            $note = '超过每日有效次数，本次无积分';
        }
    }
    $points = (int) DB::val('SELECT points FROM ' . DB::table('users') . ' WHERE id = ?', [$userId], 0);
    if ($delta < 0) {
        $delta = -min($points, abs($delta));
    }
    if ($delta !== 0) {
        add_points($userId, $delta);
    }
    DB::insert('point_logs', [
        'user_id'    => (int) $userId,
        'action'     => $action,
        'delta'      => (int) $delta,
        'note'       => $note . ($refId ? ' #' . (int) $refId : ''),
        'ref_id'     => (int) $refId,
        'created_at' => now(),
    ]);
    return $delta;
}

/**
 * 点赞 / 收藏奖励：每个用户对同一篇帖子只奖励一次，并按每日有效次数与积分上限控制。
 * 超过上限后按 points_over_action 选择无积分或扣除本次基础积分。
 */
function reward_interaction_points($userId, $action, $postId, $label = '互动')
{
    if (!in_array($action, ['like', 'fav'], true)) {
        return 0;
    }
    $base = max(0, (int) setting('points_' . $action, 1));
    if ($base <= 0) {
        return 0;
    }
    $paid = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('point_logs') . '
                           WHERE user_id = ? AND action = ? AND ref_id = ?',
                           [(int) $userId, $action, (int) $postId], 0);
    if ($paid) {
        return 0;
    }
    $today = date('Y-m-d 00:00:00');
    $limit = max(0, (int) setting('points_' . $action . '_limit', 10));
    $cap = max(0, (int) setting('points_' . $action . '_cap', 10));
    $count = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('point_logs') . '
                            WHERE user_id = ? AND action = ? AND delta > 0 AND created_at >= ?',
                            [(int) $userId, $action, $today], 0);
    $sum = (int) DB::val('SELECT COALESCE(SUM(delta), 0) FROM ' . DB::table('point_logs') . '
                          WHERE user_id = ? AND action = ? AND delta > 0 AND created_at >= ?',
                         [(int) $userId, $action, $today], 0);
    $over = ($limit > 0 && $count >= $limit) || ($cap > 0 && $sum >= $cap);
    $delta = $base;
    $note = $label . '奖励';
    if ($over) {
        if (setting('points_over_action', 'none') === 'deduct') {
            $points = (int) DB::val('SELECT points FROM ' . DB::table('users') . ' WHERE id = ?', [(int) $userId], 0);
            $delta = -min($points, $base);
            $note = $label . '超过每日有效次数或积分上限，扣除积分';
        } else {
            $delta = 0;
            $note = $label . '超过每日有效次数或积分上限，本次无积分';
        }
    } elseif ($cap > 0) {
        $delta = min($base, max(0, $cap - $sum));
        if ($delta <= 0) {
            $note = $label . '已达每日积分上限，本次无积分';
        }
    }
    if ($delta !== 0) {
        add_points($userId, $delta);
    }
    DB::insert('point_logs', [
        'user_id'    => (int) $userId,
        'action'     => $action,
        'delta'      => (int) $delta,
        'note'       => $note . ' #' . (int) $postId,
        'ref_id'     => (int) $postId,
        'created_at' => now(),
    ]);
    return $delta;
}

function transfer_points($fromId, $toId, $amount, $note = '', $channel = '')
{
    $amount = (int) $amount;
    $min = max(1, (int) setting('transfer_min', 1));
    if ($amount < $min) {
        throw new Exception('最少转账 ' . $min . ' 积分');
    }
    $from = user_by_id($fromId);
    $to = user_by_id($toId);
    if (!$from || !$to) { throw new Exception('账号不存在'); }
    if ((int) $fromId === (int) $toId) { throw new Exception('不能给自己转账'); }
    if (($from['role'] ?? '') !== 'superadmin' && (int) $from['points'] < $amount) { throw new Exception('积分不足，不支持透支'); }
    add_points($fromId, -$amount);
    add_points($toId, $amount);
    DB::insert('point_logs', ['user_id' => (int) $fromId, 'action' => 'transfer_out', 'delta' => -$amount, 'note' => '转给 ' . display_name($to) . ' #' . $toId . ($note !== '' ? '：' . mb_substr($note, 0, 60) : ''), 'created_at' => now()]);
    DB::insert('point_logs', ['user_id' => (int) $toId, 'action' => 'transfer_in', 'delta' => $amount, 'note' => '来自 ' . display_name($from) . ' #' . $fromId . ($note !== '' ? '：' . mb_substr($note, 0, 60) : ''), 'created_at' => now()]);
    notify($toId, $fromId, 'points', $fromId, display_name($from) . ' 给你转账 ' . $amount . ' 积分');

    // 转账记录以「像钱一样的转账卡片」显示在聊天大厅或私信会话中
    $fromAfter = user_by_id($fromId);
    $toAfter = user_by_id($toId);
    $payload = json_encode([
        'from_id'      => (int) $fromId,
        'to_id'        => (int) $toId,
        'from_name'    => display_name($from),
        'to_name'      => display_name($to),
        'amount'       => $amount,
        'from_balance' => (int) ($fromAfter['points'] ?? 0),
        'to_balance'   => (int) ($toAfter['points'] ?? 0),
        'note'         => mb_substr((string) $note, 0, 60),
        'created_at'   => now(),
    ], JSON_UNESCAPED_UNICODE);
    if ($channel === 'chat') {
        DB::insert('chat', [
            'user_id'    => (int) $fromId,
            'type'       => 'transfer',
            'content'    => $payload,
            'path'       => '',
            'is_deleted' => 0,
            'created_at' => now(),
        ]);
    } elseif ($channel === 'message') {
        DB::insert('messages', [
            'from_id'    => (int) $fromId,
            'to_id'      => (int) $toId,
            'content'    => $payload,
            'type'       => 'transfer',
            'path'       => '',
            'is_read'    => 0,
            'created_at' => now(),
        ]);
    }
    return true;
}

/** 解析转账卡片数据 */
function transfer_notice_data($content)
{
    $data = json_decode((string) $content, true);
    return is_array($data) ? $data : [];
}

function profile_change_check($userId, $kind, $limitSetting)
{
    $limit = (int) setting($limitSetting, 3);
    if ($limit <= 0) { return true; }
    $weekAgo = date('Y-m-d H:i:s', strtotime('-7 days'));
    $used = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('profile_changes') . ' WHERE user_id = ? AND kind = ? AND created_at >= ?', [$userId, $kind, $weekAgo], 0);
    return $used < $limit;
}

function profile_change_log($userId, $kind)
{
    DB::insert('profile_changes', ['user_id' => (int) $userId, 'kind' => $kind, 'created_at' => now()]);
}

/** 头像 / 用户名修改额度；管理员、超级管理员不受限 */
function profile_change_exempt($user)
{
    return $user && in_array((string) ($user['role'] ?? ''), ['admin', 'superadmin'], true);
}

function profile_change_used_count($userId, $kind)
{
    return (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('profile_changes') . ' WHERE user_id = ? AND kind = ?', [(int) $userId, (string) $kind], 0);
}

function profile_change_quota($user, $kind)
{
    if ($kind === 'avatar') {
        return [
            'free' => max(0, (int) ($user['avatar_free_limit'] ?? 3)),
            'unlimited' => (int) ($user['avatar_unlimited'] ?? 0) === 1,
            'cost' => max(0, (int) ($user['avatar_change_cost'] ?? 20)),
        ];
    }
    return [
        'free' => max(0, (int) ($user['username_free_limit'] ?? 0)),
        'unlimited' => (int) ($user['username_unlimited'] ?? 0) === 1,
        'cost' => max(0, (int) ($user['username_change_cost'] ?? 50)),
    ];
}

function profile_change_cost($user, $kind)
{
    if (!$user || profile_change_exempt($user)) { return 0; }
    $quota = profile_change_quota($user, $kind);
    if ($quota['unlimited']) { return 0; }
    $used = profile_change_used_count((int) $user['id'], $kind);
    return $used < $quota['free'] ? 0 : $quota['cost'];
}

function profile_change_remaining($user, $kind)
{
    if (!$user || profile_change_exempt($user)) { return '不限'; }
    $quota = profile_change_quota($user, $kind);
    if ($quota['unlimited']) { return '不限'; }
    return max(0, $quota['free'] - profile_change_used_count((int) $user['id'], $kind));
}

function profile_change_quota_text($user, $kind)
{
    if (!$user || profile_change_exempt($user)) { return '管理员不受次数和积分限制'; }
    $quota = profile_change_quota($user, $kind);
    if ($quota['unlimited']) { return '可无限次修改'; }
    $remaining = profile_change_remaining($user, $kind);
    if ($remaining > 0) {
        return '免费还可修改 ' . $remaining . ' 次' . ($quota['cost'] > 0 ? '，超出后每次 ' . $quota['cost'] . ' 积分' : '');
    }
    return $quota['cost'] > 0 ? '免费次数已用完，每次修改扣 ' . $quota['cost'] . ' 积分' : '可继续修改';
}

function profile_change_charge($userId, $kind, $cost, $label)
{
    $cost = max(0, (int) $cost);
    if ($cost <= 0) { return 0; }
    $user = user_by_id((int) $userId);
    if (!$user) { throw new Exception('账号不存在'); }
    if (profile_change_exempt($user)) { return 0; }
    if ((int) $user['points'] < $cost) {
        throw new Exception('积分不足，本次修改需要 ' . $cost . ' 积分');
    }
    add_points((int) $userId, -$cost);
    DB::insert('point_logs', [
        'user_id' => (int) $userId,
        'action' => 'profile_' . $kind,
        'delta' => -$cost,
        'note' => $label . '（超出免费次数）',
        'created_at' => now(),
    ]);
    return $cost;
}

function notify($toUserId, $fromId, $type, $targetId, $content, $link = '', $payload = null)
{
    if (!$toUserId || $toUserId == $fromId) {
        return;
    }
    $data = [
        'user_id'    => (int) $toUserId,
        'from_id'    => (int) $fromId,
        'type'       => $type,
        'target_id'  => (int) $targetId,
        'content'    => mb_substr((string) $content, 0, 200),
        'link'       => mb_substr((string) $link, 0, 255),
        'is_read'    => 0,
        'created_at' => now(),
    ];
    if ($payload !== null) {
        $data['payload'] = (string) $payload;
    }
    DB::insert('notifications', $data);
}

/** 删除世界圈动态及其评论、点赞、媒体文件，并把相关举报标记为已处理 */
function moment_delete($momentId)
{
    $momentId = (int) $momentId;
    $moment = DB::one('SELECT * FROM ' . DB::table('moments') . ' WHERE id = ?', [$momentId]);
    if (!$moment) {
        return false;
    }
    DB::delete('moment_comments', 'moment_id = ?', [$momentId]);
    DB::delete('moment_likes', 'moment_id = ?', [$momentId]);
    DB::delete('moments', 'id = ?', [$momentId]);
    if (!empty($moment['media_path'])) {
        delete_upload($moment['media_path']);
    }
    DB::run('UPDATE ' . DB::table('reports') . " SET status = 1 WHERE target_type = 'moment' AND target_id = ?", [$momentId]);
    return true;
}

/** 当前管理员能否删除某位用户发布的内容：管理员不能动管理员/超级管理员，超级管理员可管理全部 */
function admin_can_delete_owner($author)
{
    $me = current_user();
    if (!$me || !is_admin($me)) {
        return false;
    }
    if (is_superadmin($me)) {
        return true;
    }
    $role = is_array($author) ? (string) ($author['role'] ?? 'user') : (string) $author;
    return !in_array($role, ['admin', 'superadmin'], true);
}

/** 世界圈动态删除权限（语义包装） */
function world_admin_can_delete($author)
{
    return admin_can_delete_owner($author);
}

/** 举报目标的中文名称 */
function report_target_label($targetType)
{
    $map = [
        'post'    => '帖子',
        'moment'  => '世界圈动态',
        'gallery' => '图床图片',
        'netdisk' => '网盘文件',
        'user'    => '用户',
    ];
    return $map[(string) $targetType] ?? '内容';
}

/** 举报处理结果回信给举报人 */
function report_notify_reporter($report, $result, $actor, $note = '')
{
    $report = is_array($report) ? $report : [];
    $reporterId = (int) ($report['user_id'] ?? 0);
    if ($reporterId <= 0) {
        return;
    }
    $label = report_target_label((string) ($report['target_type'] ?? ''));
    $content = '你举报的' . $label . '已' . $result;
    if ($note !== '') {
        $content .= '：' . mb_substr($note, 0, 120);
    }
    notify($reporterId, (int) ($actor['id'] ?? 0), 'report_result', (int) ($report['id'] ?? 0), $content);
}

/** 举报后通知全部管理员与超级管理员 */
function notify_admins_report($reporterId, $targetType, $targetId, $reason, $excerpt = '')
{
    $reporter = user_by_id((int) $reporterId);
    $reporterName = display_name($reporter);
    $targetType = (string) $targetType;
    $type = 'report_' . $targetType;
    $label = report_target_label($targetType);
    $excerpt = trim(preg_replace('/\s+/u', ' ', strip_tags((string) $excerpt)));
    $reason = trim(preg_replace('/\s+/u', ' ', strip_tags((string) $reason)));
    $content = '举报提醒：' . $reporterName . ' 举报了' . $label;
    if ($excerpt !== '') {
        $content .= '「' . mb_substr($excerpt, 0, 60) . '」';
    }
    if ($reason !== '') {
        $content .= '；原因：' . mb_substr($reason, 0, 80);
    }
    $admins = DB::all('SELECT id FROM ' . DB::table('users') . " WHERE role IN ('admin','superadmin') AND status = 1");
    foreach ($admins as $adminRow) {
        notify((int) $adminRow['id'], (int) $reporterId, $type, (int) $targetId, $content);
    }
    return count($admins);
}

/** 帖子审核开关是否开启 */
function post_review_enabled()
{
    return setting('post_review_enabled', '0') === '1';
}

/** 当前用户发布新帖是否需要审核：管理员与超级管理员始终免审 */
function post_review_required_for($user)
{
    return post_review_enabled() && (!is_array($user) || !is_admin($user));
}

/** 帖子状态文案：1 已发布、0 已隐藏、2 审核中、3 已驳回 */
function post_status_text($status)
{
    $map = [1 => '已发布', 0 => '已隐藏', 2 => '审核中', 3 => '已驳回', 4 => '定时发布'];
    return $map[(int) $status] ?? '未知';
}

/** 待审核帖子总数；传用户 ID 时统计该用户 */
function post_review_pending_count($userId = 0)
{
    $userId = (int) $userId;
    return $userId > 0
        ? DB::count('posts', 'user_id = ? AND status = 2', [$userId])
        : DB::count('posts', 'status = 2');
}

/** 新帖进入待审核后，通知全部管理员与超级管理员 */
function post_review_notify_admins($post, $author)
{
    $post = is_array($post) ? $post : [];
    $postId = (int) ($post['id'] ?? 0);
    $authorId = (int) ($post['user_id'] ?? ($author['id'] ?? 0));
    $authorName = display_name($author ?: $authorId);
    $title = trim((string) ($post['title'] ?? ''));
    $content = $authorName . ' 发布了待审核帖子《' . mb_substr($title, 0, 80) . '》';
    $admins = DB::all('SELECT id FROM ' . DB::table('users') . " WHERE role IN ('admin','superadmin') AND status = 1");
    foreach ($admins as $adminRow) {
        notify((int) $adminRow['id'], $authorId, 'post_review', $postId, $content);
    }
    return count($admins);
}

/** 审核通过：状态改为已发布，通知作者，并补发发帖积分 */
function post_review_approve($postId, $actor)
{
    $postId = (int) $postId;
    $post = DB::one('SELECT * FROM ' . DB::table('posts') . ' WHERE id = ?', [$postId]);
    $oldStatus = (int) ($post['status'] ?? 0);
    // 2 = 待审核；3 = 曾驳回。允许把已驳回的帖子重新审核通过。
    if (!$post || !in_array($oldStatus, [2, 3], true)) {
        return false;
    }
    $isReapprove = $oldStatus === 3;
    DB::update('posts', [
        'status'      => 1,
        'review_note' => '',
        'reviewed_by' => (int) ($actor['id'] ?? 0),
        'reviewed_at' => now(),
        'updated_at'  => now(),
    ], 'id = ?', [$postId]);
    $delta = reward_points((int) $post['user_id'], 'post', $postId);
    notify((int) $post['user_id'], (int) ($actor['id'] ?? 0), 'post_approved', $postId,
        '你的帖子《' . mb_substr((string) $post['title'], 0, 80) . '》' . ($isReapprove ? '已重新审核通过' : '已审核通过') . ($delta > 0 ? '，+' . $delta . ' 积分' : ''));
    return true;
}

/** 审核驳回：记录理由，通知作者；帖子不进入公开列表 */
function post_review_reject($postId, $reason, $actor)
{
    $postId = (int) $postId;
    $reason = trim(preg_replace('/\s+/u', ' ', strip_tags((string) $reason)));
    if ($reason === '') {
        return false;
    }
    $reason = mb_substr($reason, 0, 200);
    $post = DB::one('SELECT * FROM ' . DB::table('posts') . ' WHERE id = ?', [$postId]);
    if (!$post || (int) $post['status'] !== 2) {
        return false;
    }
    DB::update('posts', [
        'status'      => 3,
        'review_note' => $reason,
        'reviewed_by' => (int) ($actor['id'] ?? 0),
        'reviewed_at' => now(),
        'updated_at'  => now(),
    ], 'id = ?', [$postId]);
    notify((int) $post['user_id'], (int) ($actor['id'] ?? 0), 'post_rejected', $postId,
        '你的帖子《' . mb_substr((string) $post['title'], 0, 80) . '》审核未通过：' . $reason);
    return true;
}

// ---------- 分页 ----------
function paginate($total, $perPage = 12, $page = null)
{
    $total = max(0, (int) $total);
    $perPage = max(1, (int) $perPage);
    $pages = max(1, (int) ceil($total / $perPage));
    $page = $page === null ? max(1, (int) input('p', 1)) : (int) $page;
    $page = min($pages, max(1, $page));
    return [
        'total'  => $total,
        'page'   => $page,
        'pages'  => $pages,
        'offset' => ($page - 1) * $perPage,
        'limit'  => $perPage,
    ];
}

function pager_html($pager, $pageName = 'home', array $extra = [])
{
    if ($pager['pages'] <= 1) {
        return '';
    }
    $html = '<div class="pager">';
    for ($i = 1; $i <= $pager['pages']; $i++) {
        if ($pager['pages'] > 9 && abs($i - $pager['page']) > 3 && $i !== 1 && $i !== $pager['pages']) {
            if ($i === 2 || $i === $pager['pages'] - 1) {
                $html .= '<span class="pg-dot">…</span>';
            }
            continue;
        }
        $extra['p'] = $i;
        $cls = $i === $pager['page'] ? 'pg on' : 'pg';
        $html .= '<a class="' . $cls . '" href="' . e(page_url($pageName, $extra)) . '">' . $i . '</a>';
    }
    return $html . '</div>';
}


/**
 * 网盘分享链接识别：只抓取常见网盘域名，避免任意 URL 造成 SSRF。
 * 识别失败时仍返回链接和用户填写的提取码，页面可继续手动补充。
 */
function netdisk_fetch_allowed($host)
{
    $host = strtolower(trim((string) $host));
    $domains = [
        'pan.baidu.com', 'yun.baidu.com', 'eyun.baidu.com',
        'lanzou.com', 'lanzoui.com', 'lanzoux.com', 'lanzouw.com', 'lanzouy.com', 'lanzouj.com',
        'aliyundrive.com', 'alipan.com', 'pan.quark.cn',
        '115.com', 'cloud.189.cn', 'caiyun.139.com', 'xunlei.com',
        '123pan.com', '123684.com', '123865.com', '6pan.cn',
        'drive.uc.cn', 'pan.uc.cn', 'weiyun.com',
    ];
    foreach ($domains as $d) {
        if ($host === $d || substr($host, -strlen('.' . $d)) === '.' . $d) {
            return true;
        }
    }
    return false;
}

function netdisk_fetch_html($url, $depth = 0)
{
    if ($depth > 3 || !netdisk_fetch_allowed((string) parse_url($url, PHP_URL_HOST))) {
        return '';
    }
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => true,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 8,
            CURLOPT_MAXFILESIZE    => 3 * 1024 * 1024,
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120 Safari/537.36',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_PROTOCOLS      => CURLPROTO_HTTP | CURLPROTO_HTTPS,
        ]);
        $raw = curl_exec($ch);
        $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $headerSize = (int) curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr((string) $raw, 0, $headerSize);
        $body = substr((string) $raw, $headerSize);
        curl_close($ch);
        if ($code >= 200 && $code < 300) {
            return $body;
        }
        if ($code >= 300 && $code < 400 && preg_match('/^Location:\s*(.+)$/im', $headers, $m)) {
            $next = trim($m[1]);
            if (strpos($next, '//') === 0) {
                $next = parse_url($url, PHP_URL_SCHEME) . ':' . $next;
            } elseif (strpos($next, '/') === 0) {
                $next = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . $next;
            } elseif (!preg_match('#^https?://#i', $next)) {
                $base = rtrim(preg_replace('#/[^/]*$#', '', $url), '/');
                $next = $base . '/' . $next;
            }
            return netdisk_fetch_html($next, $depth + 1);
        }
        return '';
    }
    $ctx = stream_context_create([
        'http' => ['timeout' => 8, 'follow_location' => 0, 'user_agent' => 'Mozilla/5.0 KomorebiLinkBot'],
        'ssl'  => ['verify_peer' => true, 'verify_peer_name' => true],
    ]);
    $html = @file_get_contents($url, false, $ctx, 0, 3 * 1024 * 1024);
    return $html === false ? '' : (string) $html;
}

function netdisk_parse_link($url, $code = '')
{
    $url = trim((string) $url);
    if ($url === '' || !preg_match('#^https?://#i', $url) || !filter_var($url, FILTER_VALIDATE_URL)) {
        throw new Exception('请输入完整的网盘分享链接（http:// 或 https:// 开头）');
    }
    $host = strtolower((string) parse_url($url, PHP_URL_HOST));
    $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
    if (!in_array($scheme, ['http', 'https'], true)) {
        throw new Exception('只支持 http:// 或 https:// 链接');
    }
    $query = [];
    parse_str((string) parse_url($url, PHP_URL_QUERY), $query);
    $queryCode = '';
    foreach (['pwd', 'password', 'passcode', 'code'] as $k) {
        if (!empty($query[$k])) { $queryCode = (string) $query[$k]; break; }
    }
    $code = trim((string) $code) !== '' ? trim((string) $code) : $queryCode;
    $fetchUrl = $url;
    if ($code !== '' && !isset($query['pwd']) && in_array($host, ['pan.baidu.com', 'yun.baidu.com'], true)) {
        $fetchUrl .= (strpos($fetchUrl, '?') === false ? '?' : '&') . 'pwd=' . rawurlencode($code);
    }
    $html = netdisk_fetch_allowed($host) ? netdisk_fetch_html($fetchUrl) : '';
    $name = '';
    $size = '';
    $fetchedCode = '';
    $errorPage = false;
    if ($html !== '') {
        if (function_exists('mb_detect_encoding')) {
            $enc = mb_detect_encoding($html, ['UTF-8', 'GB18030'], true);
            if ($enc && $enc !== 'UTF-8') { $html = mb_convert_encoding($html, 'UTF-8', $enc); }
        }
        $errorPage = (bool) preg_match('/页面不存在|链接不存在|分享已取消|文件已取消|访问的页面不存在|安全验证|验证码/u', $html);
        if (preg_match('/<title[^>]*>(.*?)<\/title>/is', $html, $m)) {
            $name = html_entity_decode(strip_tags($m[1]), ENT_QUOTES | ENT_HTML5, 'UTF-8');
            $name = preg_replace('/\s*[-_|]\s*(百度网盘|蓝奏云|夸克网盘|阿里云盘|115网盘|天翼云盘|迅雷云盘|123云盘|微云).*$/u', '', $name);
            $name = preg_replace('/[\s_\-|]*(免费高速下载|高速下载|在线预览|立即下载|提取文件).*$/u', '', $name);
            $name = trim(preg_replace('/\s+/u', ' ', $name));
            if (preg_match('/\.(html?|php|aspx?)$/i', $name)) { $name = ''; }
        }
        if (!$errorPage) {
        foreach ([
            '/(?:文件名称|文件名|名称)\s*[：:]\s*([^\n\r<]{1,120})/u',
            '/"file_name"\s*:\s*"([^"]+)"/u',
            '/"server_filename"\s*:\s*"([^"]+)"/u',
            '/"name"\s*:\s*"([^"]+\.(?:zip|rar|7z|pdf|txt|docx?|xlsx?|pptx?|mp4|mkv|mp3|flac|apk|exe|iso|jpg|png|gif))"/iu',
        ] as $pattern) {
            if (preg_match($pattern, $html, $m)) {
                $candidate = trim(html_entity_decode($m[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'));
                if ($candidate !== '' && mb_strlen($candidate) <= 120
                    && !preg_match('/\.(html?|php|aspx?)$/i', $candidate)
                    && !in_array(mb_strtolower($candidate), ['百度网盘', '蓝奏云', '夸克网盘', '阿里云盘'], true)) {
                    $name = $candidate;
                    break;
                }
            }
        }
        if (preg_match('/(?:文件大小|大小)\s*[：:]\s*([0-9.]+\s*(?:B|KB|MB|GB|TB))/iu', $html, $m)) {
            $size = trim($m[1]);
        } elseif (preg_match('/"size"\s*:\s*"?([0-9]+)(?:"|,)/', $html, $m)) {
            $size = format_size((int) $m[1]);
        }
        }
        if ($errorPage || $name === '') { $size = ''; }
        if (preg_match('/(?:提取码|访问密码|文件密码|密码)\s*[：:]\s*([A-Za-z0-9]{3,12})/iu', $html, $m)) {
            $fetchedCode = trim($m[1]);
        }
    }
    if ($code === '') { $code = $fetchedCode; }
    if ($name === '') {
        $path = (string) parse_url($url, PHP_URL_PATH);
        $base = basename($path);
        if ($base !== '' && preg_match('/\.\w{2,6}$/', $base)) {
            $name = urldecode($base);
        } else {
            $label = '网盘文件';
            if (strpos($host, 'baidu.com') !== false) { $label = '百度网盘文件'; }
            elseif (strpos($host, 'lanzou') !== false) { $label = '蓝奏云文件'; }
            elseif (strpos($host, 'quark.cn') !== false) { $label = '夸克网盘文件'; }
            elseif (strpos($host, 'aliyundrive') !== false || strpos($host, 'alipan') !== false) { $label = '阿里云盘文件'; }
            $name = $label;
        }
    }
    return [
        'link' => $url,
        'name' => mb_substr($name, 0, 120),
        'size' => mb_substr($size, 0, 40),
        'code' => mb_substr($code, 0, 40),
        'host' => $host,
        'partial' => $html === '' || $name === '' || $size === '' || $errorPage,
        'msg' => ($html === '' || $errorPage || $name === '百度网盘文件' || $name === '蓝奏云文件' || $name === '夸克网盘文件' || $name === '阿里云盘文件')
            ? '该分享页无法直接读取（可能需要登录或分享已失效），已填好链接和提取码，请手动补充文件名和大小'
            : '已识别网盘信息，请核对后发布',
    ];
}

function upload_limit_bytes($key, $defaultMb = 1000)
{
    $mb = (int) setting($key, (string) $defaultMb);
    return $mb > 0 ? $mb * 1024 * 1024 : 0;
}

// ---------- 文件上传 ----------
function image_upload_extensions()
{
    return ['jpg', 'jpeg', 'jpe', 'jfif', 'png', 'apng', 'gif', 'webp', 'bmp', 'avif', 'heic', 'heif', 'tif', 'tiff', 'ico', 'svg'];
}

function gif_is_animated($relPath)
{
    $full = APP_ROOT . '/' . str_replace('\\', '/', (string) $relPath);
    if (!is_file($full)) { return false; }
    $bytes = @file_get_contents($full, false, null, 0, 2 * 1024 * 1024);
    if ($bytes === false) { return false; }
    return substr_count($bytes, "\x00\x21\xF9\x04") >= 2;
}

function live_photo_valid_path($relPath)
{
    $relPath = str_replace('\\', '/', (string) $relPath);
    return (bool) preg_match('#^uploads/live/[A-Za-z0-9._-]+\.gif$#', $relPath)
        && is_file(APP_ROOT . '/' . $relPath);
}

function live_photo_gif($photoRel, $motionRel)
{
    $photoRel = str_replace('\\', '/', (string) $photoRel);
    $motionRel = str_replace('\\', '/', (string) $motionRel);
    if (strpos($photoRel, 'uploads/live/') !== 0 || strpos($motionRel, 'uploads/live/') !== 0
        || strpos($photoRel, '..') !== false || strpos($motionRel, '..') !== false) {
        return null;
    }
    if (!is_file(APP_ROOT . '/' . $photoRel) || !is_file(APP_ROOT . '/' . $motionRel)) {
        return null;
    }
    if (!function_exists('exec')) {
        return null;
    }
    $ffmpeg = media_ffmpeg_binary();
    if ($ffmpeg === '') {
        return null;
    }
    $outRel = 'uploads/live/live_' . bin2hex(random_bytes(8)) . '.gif';
    $outFull = APP_ROOT . '/' . $outRel;
    @mkdir(dirname($outFull), 0777, true);
    $filters = [
        'fps=10,scale=540:-2:flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=128[p];[s1][p]paletteuse',
        'fps=8,scale=360:-2:flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=96[p];[s1][p]paletteuse',
    ];
    foreach ($filters as $filter) {
        $cmd = escapeshellarg($ffmpeg) . ' -y -hide_banner -loglevel error -i ' . escapeshellarg(APP_ROOT . '/' . $motionRel)
            . ' -t 4 -vf ' . escapeshellarg($filter) . ' -loop 0 ' . escapeshellarg($outFull) . ' 2>&1';
        @exec($cmd, $out, $code);
        if ($code === 0 && is_file($outFull) && filesize($outFull) > 0 && filesize($outFull) <= 15 * 1024 * 1024) {
            return $outRel;
        }
        @unlink($outFull);
    }
    return null;
}

function live_photo_static_gif($photoRel)
{
    $photoRel = str_replace('\\', '/', (string) $photoRel);
    if (strpos($photoRel, 'uploads/live/') !== 0 || strpos($photoRel, '..') !== false) {
        return null;
    }
    $full = APP_ROOT . '/' . $photoRel;
    if (!is_file($full)) {
        return null;
    }
    $outRel = 'uploads/live/live_static_' . bin2hex(random_bytes(8)) . '.gif';
    $target = APP_ROOT . '/' . $outRel;
    @mkdir(dirname($target), 0777, true);

    if (function_exists('exec')) {
        $convert = '';
        foreach (['/usr/bin/convert', '/usr/local/bin/convert', '/opt/homebrew/bin/convert', '/usr/bin/magick', '/usr/local/bin/magick'] as $bin) {
            if (is_executable($bin)) { $convert = $bin; break; }
        }
        if ($convert !== '') {
            $cmd = escapeshellarg($convert) . ' ' . escapeshellarg($full)
                . ' -auto-orient -strip -resize ' . escapeshellarg('720x720>')
                . ' -quality 88 ' . escapeshellarg($target) . ' 2>&1';
            @exec($cmd, $out, $code);
            if ($code === 0 && is_file($target) && filesize($target) > 0) {
                return $outRel;
            }
            @unlink($target);
        }
    }

    if (function_exists('imagecreatefromjpeg')) {
        $ext = strtolower((string) pathinfo($full, PATHINFO_EXTENSION));
        $img = null;
        if (in_array($ext, ['jpg', 'jpeg'], true)) { $img = @imagecreatefromjpeg($full); }
        elseif ($ext === 'png') { $img = @imagecreatefrompng($full); }
        elseif ($ext === 'webp' && function_exists('imagecreatefromwebp')) { $img = @imagecreatefromwebp($full); }
        if ($img) {
            $w = imagesx($img);
            $h = imagesy($img);
            if ($w > 720) {
                $nh = max(1, (int) round($h * 720 / $w));
                $scaled = imagecreatetruecolor(720, $nh);
                imagecopyresampled($scaled, $img, 0, 0, 0, 0, 720, $nh, $w, $h);
                imagedestroy($img);
                $img = $scaled;
            }
            $ok = @imagegif($img, $target);
            imagedestroy($img);
            if ($ok && is_file($target) && filesize($target) > 0) { return $outRel; }
            @unlink($target);
        }
    }
    return null;
}

function image_make_compatible($relPath)
{
    $relPath = str_replace('\\', '/', (string) $relPath);
    if ((strpos($relPath, 'uploads/') !== 0 && strpos($relPath, 'storage/drive/') !== 0)
        || strpos($relPath, '..') !== false) {
        return null;
    }
    $full = APP_ROOT . '/' . $relPath;
    if (!is_file($full)) {
        return null;
    }
    $ext = strtolower((string) pathinfo($full, PATHINFO_EXTENSION));
    if (!in_array($ext, ['heic', 'heif', 'avif', 'tif', 'tiff', 'bmp', 'ico'], true)) {
        return $relPath;
    }
    $targetRel = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '_view.jpg', $relPath);
    $targetFull = APP_ROOT . '/' . $targetRel;
    if (is_file($targetFull) && filesize($targetFull) > 0 && @filemtime($targetFull) >= @filemtime($full)) {
        return $targetRel;
    }
    if (!function_exists('exec')) { return null; }
    $convert = '';
    foreach (['/usr/bin/convert', '/usr/local/bin/convert', '/opt/homebrew/bin/convert', '/usr/bin/magick', '/usr/local/bin/magick'] as $bin) {
        if (is_executable($bin)) { $convert = $bin; break; }
    }
    if ($convert === '') {
        return null;
    }
    @mkdir(dirname($targetFull), 0777, true);
    $cmd = escapeshellarg($convert) . ' ' . escapeshellarg($full) . ' -auto-orient -strip -quality 86 ' . escapeshellarg($targetFull) . ' 2>&1';
    @exec($cmd, $out, $code);
    if ($code === 0 && is_file($targetFull) && filesize($targetFull) > 0) {
        return $targetRel;
    }
    @unlink($targetFull);
    return null;
}

function image_svg_is_safe($content)
{
    if (preg_match('/<!DOCTYPE|<!ENTITY|<\s*(script|foreignObject|iframe|embed|object|animate|set)\b|\bon[a-z]+\s*=|javascript:/i', $content)) {
        return false;
    }
    return true;
}

function upload_store($field, $subdir, array $options = [])
{
    if (!isset($_FILES[$field]) || !is_array($_FILES[$field])) {
        throw new Exception('没有接收到文件');
    }
    $file = $_FILES[$field];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $msgs = [
            UPLOAD_ERR_INI_SIZE  => '文件超过 php.ini 允许的大小',
            UPLOAD_ERR_FORM_SIZE => '文件超过表单允许的大小',
            UPLOAD_ERR_PARTIAL   => '文件只上传了一部分',
            UPLOAD_ERR_NO_FILE   => '没有选择文件',
            UPLOAD_ERR_NO_TMP_DIR => '缺少临时目录',
            UPLOAD_ERR_CANT_WRITE => '写入磁盘失败',
        ];
        throw new Exception($msgs[$file['error']] ?? '上传失败');
    }

    $maxSize = (int) ($options['max'] ?? 10 * 1024 * 1024);
    $maxLabel = trim((string) ($options['max_label'] ?? '文件'));
    if ($maxLabel === '') { $maxLabel = '文件'; }
    // 0 = 应用层不限制大小，交给 PHP / 主机配置决定
    if ($maxSize > 0 && $file['size'] > $maxSize) {
        throw new Exception($maxLabel . '超过上传上限，最大允许 ' . format_size($maxSize) . '，已驳回');
    }

    $original = basename($file['name']);
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
    $allowAll = !empty($options['allow_all']);
    $allow = $options['allow'] ?? ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];

    // 先识别 MIME：世界圈音乐允许所有真实音频格式（含扩展名不在白名单的格式）
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);
    $mimeAudio = strpos((string) $mime, 'audio/') === 0;
    $mimeVideo = strpos((string) $mime, 'video/') === 0;
    $mimeAudioAllow = !empty($options['mime_audio']) && $mimeAudio;
    $mimeMediaAllow = !empty($options['mime_media']) && ($mimeAudio || $mimeVideo);
    $mimeAllow = $mimeAudioAllow || $mimeMediaAllow;
    if (!$allowAll && !in_array($ext, $allow, true) && !$mimeAllow) {
        throw new Exception('不支持的文件类型：' . e($ext));
    }
    // 全部格式开放或 MIME 音频兜底时，服务端可执行扩展仍落盘为 .dat，避免上传目录被直接执行。
    $dangerousExt = ['php','php3','php4','php5','php7','php8','phtml','phar','phps','htaccess','htpasswd','cgi','pl','py','jsp','asp','aspx','sh','js','html','htm','svg'];
    $storedExt = $ext !== '' ? $ext : 'dat';
    if (($allowAll || $mimeAllow) && in_array($ext, $dangerousExt, true)) {
        $storedExt = 'dat';
    }
    $isImage = strpos((string) $mime, 'image/') === 0;
    // 部分虚拟主机的 fileinfo 数据库识别不了 HEIC / HEIF，会返回 application/octet-stream。
    if (!$isImage && in_array($ext, ['heic', 'heif'], true) && $mime === 'application/octet-stream') {
        $isImage = true;
    }
    $isVideo = strpos((string) $mime, 'video/') === 0;
    if (!$isVideo && in_array($ext, ['mp4', 'm4v', 'mov', 'webm', 'ogv'], true)) {
        // 部分主机的 fileinfo 数据库较旧，用容器文件头兜底识别，避免把有效视频当图片拒绝。
        $head = @file_get_contents($file['tmp_name'], false, null, 0, 64);
        if (is_string($head) && $head !== '') {
            if (in_array($ext, ['mp4', 'm4v', 'mov'], true) && strpos($head, 'ftyp') !== false) {
                $isVideo = true;
            } elseif ($ext === 'webm' && strpos($head, "\x1A\x45\xDF\xA3") === 0) {
                $isVideo = true;
            } elseif ($ext === 'ogv' && strpos($head, 'OggS') === 0) {
                $isVideo = true;
            }
        }
    }
    if (!empty($options['video'])) {
        if (!in_array($ext, avatar_video_extensions(), true) || !$isVideo) {
            throw new Exception('该文件不是有效视频，请上传 MP4 / WebM / MOV 格式');
        }
    }
    if (!empty($options['image'])) {
        if (!in_array($ext, image_upload_extensions(), true) || !$isImage) {
            throw new Exception('该文件不是有效图片');
        }
        if ($ext === 'svg') {
            $svg = (string) file_get_contents($file['tmp_name']);
            if (!image_svg_is_safe($svg)) {
                throw new Exception('SVG 图片包含不安全的脚本内容');
            }
        }
        // HEIC / HEIF / AVIF / SVG / ICO 等格式 getimagesize 支持有限，仅做 MIME 校验
        if (!in_array($ext, ['heic', 'heif', 'avif', 'svg', 'ico'], true)) {
            $info = @getimagesize($file['tmp_name']);
            if (!$info) {
                throw new Exception('图片内容校验失败');
            }
        }
    }

    $subdir = trim(str_replace(['..', '\\'], '', $subdir), '/');
    $dir = APP_ROOT . '/uploads/' . $subdir;
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    if (!is_writable($dir)) {
        throw new Exception('上传目录不可写：uploads/' . $subdir);
    }

    $fileName = date('Ym') . '_' . bin2hex(random_bytes(8)) . '.' . $storedExt;
    $target = $dir . '/' . $fileName;
    if (!@move_uploaded_file($file['tmp_name'], $target)) {
        throw new Exception('保存文件失败，请检查目录权限');
    }
    @chmod($target, 0644);

    return [
        'path' => 'uploads/' . $subdir . '/' . $fileName,
        'name' => $original,
        'size' => (int) $file['size'],
        'mime' => $mime,
    ];
}

function local_upload_rel_from_url($url)
{
    $url = trim((string) $url);
    if ($url === '') {
        return '';
    }
    $path = (string) parse_url($url, PHP_URL_PATH);
    $pos = strpos($path, 'uploads/');
    if ($pos === false) {
        return '';
    }
    $rel = rawurldecode(substr($path, $pos));
    $rel = str_replace('\\', '/', $rel);
    if (strpos($rel, 'uploads/') !== 0 || strpos($rel, '..') !== false) {
        return '';
    }
    $uploadsRoot = realpath(APP_ROOT . '/uploads');
    $full = realpath(APP_ROOT . '/' . $rel);
    if (!$full || !$uploadsRoot || strpos($full, $uploadsRoot) !== 0 || !is_file($full)) {
        return '';
    }
    return $rel;
}

function media_kind_by_name($name)
{
    $ext = strtolower(pathinfo((string) $name, PATHINFO_EXTENSION));
    if (in_array($ext, image_upload_extensions(), true)) {
        return 'image';
    }
    if (in_array($ext, chat_video_extensions(), true)) {
        return 'video';
    }
    if (in_array($ext, chat_audio_extensions(), true)) {
        return 'audio';
    }
    return '';
}

function netdisk_unique_code()
{
    for ($i = 0; $i < 20; $i++) {
        $code = random_code(6);
        if (!DB::val('SELECT COUNT(*) FROM ' . DB::table('netdisk') . ' WHERE share_code = ?', [$code])) {
            return $code;
        }
    }
    return strtoupper(bin2hex(random_bytes(4)));
}

function netdisk_save_from_path($userId, $sourceRel, $displayName)
{
    $sourceRel = str_replace('\\', '/', (string) $sourceRel);
    if (strpos($sourceRel, 'uploads/') !== 0 && strpos($sourceRel, 'storage/drive/') !== 0) {
        throw new Exception('不支持保存这个文件');
    }
    if (strpos($sourceRel, '..') !== false) {
        throw new Exception('文件路径无效');
    }
    $full = realpath(APP_ROOT . '/' . $sourceRel);
    $root = realpath(APP_ROOT);
    if (!$full || !$root || strpos($full, $root) !== 0 || !is_file($full)) {
        throw new Exception('源文件不存在');
    }
    $size = (int) @filesize($full);
    if ($size <= 0) {
        throw new Exception('源文件为空');
    }
    if ($size > 200 * 1024 * 1024) {
        throw new Exception('文件超过 200MB，无法保存到网盘');
    }
    $ext = strtolower(pathinfo($full, PATHINFO_EXTENSION));
    $name = trim((string) $displayName);
    if ($name === '') {
        $name = basename($full);
    }
    if ($ext !== '' && strtolower(pathinfo($name, PATHINFO_EXTENSION)) !== $ext) {
        $name = preg_replace('/\.\w+$/', '', $name) . '.' . $ext;
    }
    $name = mb_substr($name, 0, 200);
    $dir = APP_ROOT . '/storage/drive';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    $stored = date('Ym') . '_' . bin2hex(random_bytes(10)) . ($ext !== '' ? '.' . $ext : '');
    if (!@copy($full, $dir . '/' . $stored)) {
        throw new Exception('写入网盘失败，请检查 storage/drive 权限');
    }
    $code = netdisk_unique_code();
    DB::insert('netdisk', [
        'user_id'        => (int) $userId,
        'name'           => $name,
        'path'           => 'storage/drive/' . $stored,
        'size'           => $size,
        'share_code'     => $code,
        'share_password' => '',
        'is_public'      => 0,
        'downloads'      => 0,
        'created_at'     => now(),
    ]);
    return ['code' => $code, 'name' => $name, 'size' => $size];
}

function netdisk_remote_host_allowed($host)
{
    $host = strtolower(trim((string) $host));
    if ($host === '' || in_array($host, ['localhost', '127.0.0.1', '0.0.0.0', '::1'], true)) {
        return false;
    }
    if (filter_var($host, FILTER_VALIDATE_IP)) {
        return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
    }
    $ips = @gethostbynamel($host) ?: [];
    $records = @dns_get_record($host, DNS_AAAA);
    if (is_array($records)) {
        foreach ($records as $record) {
            if (!empty($record['ipv6'])) {
                $ips[] = $record['ipv6'];
            }
        }
    }
    if (!$ips) {
        return true;
    }
    foreach ($ips as $ip) {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
            return false;
        }
    }
    return true;
}

function netdisk_save_from_url($userId, $url, $displayName)
{
    $url = trim((string) $url);
    if (!preg_match('#^https?://#i', $url)) {
        throw new Exception('图片或视频地址无效');
    }
    $host = strtolower((string) parse_url($url, PHP_URL_HOST));
    if (!netdisk_remote_host_allowed($host)) {
        throw new Exception('不允许保存本地或内网地址');
    }
    $tmpDir = APP_ROOT . '/storage/tmp';
    if (!is_dir($tmpDir)) {
        @mkdir($tmpDir, 0775, true);
    }
    $tmp = tempnam($tmpDir, 'km_save_');
    if ($tmp === false) {
        throw new Exception('创建临时文件失败');
    }
    $fp = fopen($tmp, 'wb');
    $received = 0;
    $max = 200 * 1024 * 1024;
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_ENCODING       => '',
        CURLOPT_COOKIEFILE     => '',
        CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        CURLOPT_HTTPHEADER     => ['Accept: image/avif,image/webp,image/apng,image/*,video/*,*/*;q=0.8', 'Referer: ' . $url],
        CURLOPT_WRITEFUNCTION  => function ($ch, $chunk) use ($fp, &$received, $max) {
            $received += strlen($chunk);
            if ($received > $max) {
                return 0;
            }
            $written = fwrite($fp, $chunk);
            return $written === false ? 0 : $written;
        },
    ]);
    $ok = curl_exec($ch);
    $err = curl_error($ch);
    $type = strtolower((string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
    $http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $finalUrl = (string) curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    fclose($fp);
    if ($received > $max) {
        @unlink($tmp);
        throw new Exception('文件超过 200MB，无法保存到网盘');
    }
    if ($ok === false || $http >= 400 || !is_file($tmp) || filesize($tmp) < 100) {
        @unlink($tmp);
        throw new Exception('下载图片或视频失败：' . ($err !== '' ? $err : '文件为空'));
    }
    $finalHost = strtolower((string) parse_url($finalUrl, PHP_URL_HOST));
    if ($finalHost !== '' && !netdisk_remote_host_allowed($finalHost)) {
        @unlink($tmp);
        throw new Exception('文件地址跳转到了内网，已停止保存');
    }
    $extMap = [
        'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif',
        'image/webp' => 'webp', 'image/bmp' => 'bmp', 'image/avif' => 'avif',
        'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
        'video/x-m4v' => 'm4v', 'video/ogg' => 'ogv',
    ];
    $baseType = trim(explode(';', $type)[0]);
    if (!isset($extMap[$baseType])) {
        @unlink($tmp);
        throw new Exception('这个地址不是可直接保存的图片或视频');
    }
    $ext = $extMap[$baseType];
    $name = trim((string) $displayName);
    if ($name === '') {
        $name = '保存的媒体.' . $ext;
    }
    $name = preg_replace('/\.\w+$/', '', $name) . '.' . $ext;
    $name = mb_substr($name, 0, 200);
    $dir = APP_ROOT . '/storage/drive';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    $stored = date('Ym') . '_' . bin2hex(random_bytes(10)) . '.' . $ext;
    if (!@rename($tmp, $dir . '/' . $stored)) {
        if (!@copy($tmp, $dir . '/' . $stored)) {
            @unlink($tmp);
            throw new Exception('写入网盘失败，请检查 storage/drive 权限');
        }
        @unlink($tmp);
    }
    $size = (int) filesize($dir . '/' . $stored);
    $code = netdisk_unique_code();
    DB::insert('netdisk', [
        'user_id'        => (int) $userId,
        'name'           => $name,
        'path'           => 'storage/drive/' . $stored,
        'size'           => $size,
        'share_code'     => $code,
        'share_password' => '',
        'is_public'      => 0,
        'downloads'      => 0,
        'created_at'     => now(),
    ]);
    return ['code' => $code, 'name' => $name, 'size' => $size];
}

function post_media_save_html($html, $postId, $canSave)
{
    if (!$canSave || trim((string) $html) === '' || !class_exists('DOMDocument')) {
        return $html;
    }
    $wrapped = '<div id="km-media-root">' . $html . '</div>';
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML('<?xml encoding="UTF-8">' . $wrapped, LIBXML_NOWARNING | LIBXML_NOERROR);
    libxml_clear_errors();
    $root = $doc->getElementById('km-media-root');
    if (!$root) {
        return $html;
    }
    $nodes = [];
    foreach ($root->getElementsByTagName('img') as $node) { $nodes[] = $node; }
    foreach ($root->getElementsByTagName('video') as $node) { $nodes[] = $node; }
    foreach ($root->getElementsByTagName('audio') as $node) {
        $src = trim((string) $node->getAttribute('src'));
        if ($src === '' || $node->getAttribute('data-km-save-post') === '1') {
            continue;
        }
        $rel = local_upload_rel_from_url($src);
        $kind = $rel !== '' ? media_kind_by_name($rel) : media_kind_by_name((string) parse_url($src, PHP_URL_PATH));
        if ($kind !== 'audio') { continue; }
        $node->setAttribute('data-km-save-post', '1');
        $node->setAttribute('data-km-save-post-id', (string) (int) $postId);
        $node->setAttribute('data-km-save-url', $src);
        $node->setAttribute('data-km-save-kind', 'audio');
        $node->setAttribute('data-km-card-style', 'panel');
    }
    foreach ($nodes as $node) {
        $src = trim((string) $node->getAttribute('src'));
        if ($src === '' || $node->getAttribute('data-km-save') === '1') {
            continue;
        }
        $rel = local_upload_rel_from_url($src);
        if ($rel !== '') {
            $kind = media_kind_by_name($rel);
        } elseif (preg_match('#^https?://#i', $src)) {
            $kind = media_kind_by_name((string) parse_url($src, PHP_URL_PATH));
            if ($kind === '') {
                $kind = strtolower($node->nodeName) === 'video' ? 'video' : 'image';
            }
        } else {
            continue;
        }
        if ($kind === '') {
            continue;
        }
        $node->setAttribute('data-km-save', '1');
        $wrapper = $doc->createElement('span');
        $wrapper->setAttribute('class', 'post-media-item');
        $node->parentNode->insertBefore($wrapper, $node);
        $wrapper->appendChild($node);
        $btn = $doc->createElement('button');
        $btn->setAttribute('type', 'button');
        $btn->setAttribute('class', 'post-save-media');
        $btn->setAttribute('data-save-post-media', '1');
        $btn->setAttribute('data-post-id', (string) (int) $postId);
        $btn->setAttribute('data-media-url', $src);
        $btn->setAttribute('data-media-kind', $kind);
        $btn->appendChild($doc->createTextNode('保存到网盘'));
        $wrapper->appendChild($btn);
    }
    $out = '';
    foreach ($root->childNodes as $child) {
        $out .= $doc->saveHTML($child);
    }
    return $out;
}

function post_delete($id)
{
    $id = (int) $id;
    if ($id <= 0) {
        return;
    }
    $atts = DB::all('SELECT path FROM ' . DB::table('attachments') . ' WHERE post_id = ?', [$id]);
    foreach ($atts as $att) {
        if (!empty($att['path'])) {
            delete_upload($att['path']);
        }
    }
    DB::delete('attachments', 'post_id = ?', [$id]);
    DB::delete('comments', 'post_id = ?', [$id]);
    DB::delete('likes', 'post_id = ?', [$id]);
    DB::delete('favorites', 'post_id = ?', [$id]);
    DB::delete('post_views', 'post_id = ?', [$id]);
    DB::delete('post_unlocks', 'post_id = ?', [$id]);
    DB::delete('post_read_rewards', 'post_id = ?', [$id]);
    DB::delete('reports', 'target_type = ? AND target_id = ?', ['post', $id]);
    DB::delete('posts', 'id = ?', [$id]);
}

/**
 * 注册时的资料快照字段。只记录用户可自行编辑、且注册流程实际收集或默认写入的资料，
 * 不包含密码、积分、权限等不能通过“恢复注册资料”安全回滚的数据。
 */
function user_initial_profile_fields()
{
    return [
        'username', 'nickname', 'gender', 'email', 'email_verified',
        'avatar', 'bio', 'province', 'city', 'district', 'town', 'village',
        'show_location', 'show_ip', 'role', 'created_at',
    ];
}

function user_initial_profile_snapshot($user)
{
    $out = [];
    foreach (user_initial_profile_fields() as $field) {
        $out[$field] = $user[$field] ?? '';
    }
    $out['captured_at'] = now();
    return $out;
}

/** 创建用户后写入初始资料；注册流程上传头像后再覆盖 avatar */
function user_initial_profile_capture($uid, array $overrides = [])
{
    $uid = (int) $uid;
    $user = user_by_id($uid);
    if (!$user) {
        return [false, '账号不存在'];
    }
    $snapshot = user_initial_profile_snapshot($user);
    foreach ($overrides as $k => $v) {
        if (array_key_exists($k, $snapshot)) {
            $snapshot[$k] = $v;
        }
    }
    DB::run('UPDATE ' . DB::table('users') . ' SET initial_profile = ? WHERE id = ?',
        [json_encode($snapshot, JSON_UNESCAPED_UNICODE), $uid]);
    return [true, $snapshot];
}

function user_initial_profile_get($user)
{
    $raw = is_array($user) ? (string) ($user['initial_profile'] ?? '') : '';
    if ($raw === '') {
        return null;
    }
    $data = json_decode($raw, true);
    return is_array($data) ? $data : null;
}

/**
 * 一键恢复注册资料。
 * 账号密码、角色、积分、发帖与上传内容不在恢复范围内；用户名或邮箱被占用时跳过并提示。
 */
function user_restore_initial_profile($uid)
{
    $uid = (int) $uid;
    $user = user_by_id($uid);
    if (!$user) {
        return [false, '账号不存在'];
    }
    $snapshot = user_initial_profile_get($user);
    if (!$snapshot) {
        return [false, '该账号没有注册资料快照（升级前创建的老账号暂不支持）'];
    }

    $data = [];
    $changed = [];
    $skipped = [];

    $username = trim((string) ($snapshot['username'] ?? ''));
    if ($username !== '' && $username !== (string) $user['username']) {
        if (!preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]{2,20}$/u', $username)) {
            $skipped[] = '用户名格式不再有效';
        } elseif (user_by_username($username)) {
            $skipped[] = '原用户名已被其他账号占用';
        } else {
            $data['username'] = $username;
            $changed[] = '用户名';
        }
    }

    $email = trim((string) ($snapshot['email'] ?? ''));
    if ($email !== (string) ($user['email'] ?? '')) {
        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $skipped[] = '原邮箱格式无效';
        } elseif ($email !== '' && DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE email = ? AND id <> ?', [$email, $uid], 0)) {
            $skipped[] = '原邮箱已被其他账号绑定';
        } else {
            $data['email'] = $email;
            $data['email_verified'] = $email === '' ? 0 : (int) ($snapshot['email_verified'] ?? 0);
            $data['email_login_verify'] = 0;
            $changed[] = '邮箱';
        }
    }

    $map = [
        'nickname' => '昵称', 'gender' => '性别', 'bio' => '自我介绍',
        'province' => '省份', 'city' => '城市', 'district' => '区县',
        'town' => '街道 / 乡镇', 'village' => '村 / 社区',
        'show_location' => '地址展示范围', 'show_ip' => 'IP 展示设置',
    ];
    foreach ($map as $field => $label) {
        if (!array_key_exists($field, $snapshot)) { continue; }
        $new = $snapshot[$field];
        if ($field === 'nickname' && trim((string) $new) === '') {
            $new = (string) $user['username'];
        }
        if ($field === 'gender' && !in_array((string) $new, ['male', 'female', 'secret'], true)) {
            $new = 'secret';
        }
        if (in_array($field, ['show_location', 'show_ip'], true)) {
            $new = (int) $new;
        }
        if ((string) ($user[$field] ?? '') !== (string) $new) {
            $data[$field] = $new;
            $changed[] = $label;
        }
    }

    $avatar = (string) ($snapshot['avatar'] ?? '');
    if ($avatar !== (string) ($user['avatar'] ?? '')) {
        if ($avatar !== '' && strpos($avatar, 'uploads/') === 0 && !is_file(APP_ROOT . '/' . $avatar)) {
            $skipped[] = '原头像文件已不存在，已保留当前头像';
        } else {
            $data['avatar'] = $avatar;
            $changed[] = '头像';
        }
    }

    if (!$data) {
        return [true, '当前资料已经和注册时一致', [], $skipped];
    }
    DB::update('users', $data, 'id = ?', [$uid]);    return [true, '已恢复：' . implode('、', $changed), $changed, $skipped];
}

/** 删除前存档账号资料，供后台“被删除账号恢复”使用 */
/** 被删除账号的关联数据表：按用户本人及相关帖子/动态范围归档与恢复。 */
function account_data_table_specs($uid)
{
    $uid = (int) $uid;
    $posts = DB::table('posts');
    $moments = DB::table('moments');
    $postScope = 'post_id IN (SELECT id FROM ' . $posts . ' WHERE user_id = ?)';
    $momentScope = 'moment_id IN (SELECT id FROM ' . $moments . ' WHERE user_id = ?)';
    return [
        ['posts', 'user_id = ?', [$uid]],
        ['comments', 'user_id = ? OR ' . $postScope, [$uid, $uid]],
        ['likes', 'user_id = ? OR ' . $postScope, [$uid, $uid]],
        ['favorites', 'user_id = ? OR ' . $postScope, [$uid, $uid]],
        ['post_views', 'user_id = ? OR ' . $postScope, [$uid, $uid]],
        ['post_unlocks', 'user_id = ? OR ' . $postScope, [$uid, $uid]],
        ['post_read_rewards', 'user_id = ? OR ' . $postScope, [$uid, $uid]],
        ['attachments', 'user_id = ? OR ' . $postScope, [$uid, $uid]],
        ['netdisk', 'user_id = ?', [$uid]],
        ['netdisk_folders', 'user_id = ?', [$uid]],
        ['gallery', 'user_id = ?', [$uid]],
        ['chat', 'user_id = ?', [$uid]],
        ['chat_mutes', 'user_id = ?', [$uid]],
        ['chat_calls', 'host_id = ?', [$uid]],
        ['chat_call_members', 'user_id = ?', [$uid]],
        ['chat_signals', 'from_id = ? OR to_id = ?', [$uid, $uid]],
        ['moments', 'user_id = ?', [$uid]],
        ['moment_likes', 'user_id = ? OR ' . $momentScope, [$uid, $uid]],
        ['moment_comments', 'user_id = ? OR ' . $momentScope, [$uid, $uid]],
        ['messages', 'from_id = ? OR to_id = ?', [$uid, $uid]],
        ['notifications', 'user_id = ? OR from_id = ?', [$uid, $uid]],
        ['reports', "user_id = ? OR (target_type = 'post' AND target_id IN (SELECT id FROM " . $posts . " WHERE user_id = ?))", [$uid, $uid]],
        ['point_logs', 'user_id = ?', [$uid]],
        ['profile_changes', 'user_id = ?', [$uid]],
        ['transfers', 'from_id = ? OR to_id = ?', [$uid, $uid]],
        ['red_packets', 'sender_id = ?', [$uid]],
        ['drafts', 'user_id = ?', [$uid]],
        ['friends', 'user_id = ? OR friend_id = ?', [$uid, $uid]],
        ['friend_requests', 'from_id = ? OR to_id = ?', [$uid, $uid]],
        ['blocked_users', 'blocker_id = ? OR blocked_id = ?', [$uid, $uid]],
        ['profile_visits', 'profile_user_id = ? OR visitor_id = ?', [$uid, $uid]],
        ['follows', "follower_id = ? OR (target_type = 'user' AND target_id = ?)", [$uid, $uid]],
    ];
}

function account_table_columns($table)
{
    static $cache = [];
    if (isset($cache[$table])) { return $cache[$table]; }
    $cols = [];
    try {
        if (DB::$driver === 'sqlite') {
            foreach (DB::all('PRAGMA table_info(' . DB::table($table) . ')') as $row) {
                $cols[] = (string) $row['name'];
            }
        } else {
            foreach (DB::all('SELECT column_name FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ?', [DB::table($table)]) as $row) {
                $cols[] = (string) $row['column_name'];
            }
        }
    } catch (Throwable $e) {
        $cols = [];
    }
    return $cache[$table] = $cols;
}

function account_data_archive_dir($archiveId)
{
    return 'storage/deleted_accounts/archive-' . (int) $archiveId;
}

/** 删除前把用户相关行与实体文件完整写入存档，恢复时可原样重建。 */
function account_archive_user_data($archiveId, $user)
{
    $archiveId = (int) $archiveId;
    $uid = (int) ($user['id'] ?? 0);
    if ($archiveId <= 0 || $uid <= 0) { return false; }
    $dir = account_data_archive_dir($archiveId);
    $dirFull = APP_ROOT . '/' . $dir;
    if (!is_dir($dirFull . '/files')) { @mkdir($dirFull . '/files', 0775, true); }

    $data = [];
    $files = [];
    $addFile = function ($rel) use (&$files, $dirFull) {
        $rel = ltrim(str_replace('\\', '/', trim((string) $rel)), '/');
        if ($rel === '' || strpos($rel, '..') !== false) { return; }
        if (strpos($rel, 'uploads/') !== 0 && strpos($rel, 'storage/drive/') !== 0) { return; }
        $src = APP_ROOT . '/' . $rel;
        if (!is_file($src)) { return; }
        $files[$rel] = true;
        $dest = $dirFull . '/files/' . $rel;
        if (!is_dir(dirname($dest))) { @mkdir(dirname($dest), 0775, true); }
        if (!is_file($dest)) { @copy($src, $dest); }
    };

    foreach (['avatar', 'profile_bg', 'profile_bg_video'] as $field) {
        if (!empty($user[$field])) { $addFile($user[$field]); }
    }

    foreach (account_data_table_specs($uid) as $spec) {
        list($table, $where, $params) = $spec;
        try {
            $rows = DB::all('SELECT * FROM ' . DB::table($table) . ' WHERE ' . $where, $params);
        } catch (Throwable $e) {
            continue;
        }
        if (!$rows) { continue; }
        $data[$table] = $rows;
        foreach ($rows as $row) {
            foreach ($row as $value) {
                if (is_string($value) && $value !== '') { $addFile($value); }
            }
        }
    }

    $bundle = ['data' => $data, 'files' => array_keys($files)];
    $bundleJson = json_encode($bundle, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
    if ($bundleJson === false || @file_put_contents($dirFull . '/data.json', $bundleJson) === false) {
        return false;
    }
    $snapshot = $user;
    $snapshot['_deleted_at'] = now();
    $snapshot['_data_file'] = $dir . '/data.json';
    try {
        DB::update('deleted_accounts', ['snapshot' => json_encode($snapshot, JSON_UNESCAPED_UNICODE)], 'id = ?', [$archiveId]);
    } catch (Throwable $e) {
        return false;
    }
    return true;
}

/** 恢复账号内容行与文件；调用方负责账号本身与事务回滚。 */
function account_restore_user_data($archiveId, $snapshot, $newUid, $oldUid)
{
    $dir = account_data_archive_dir($archiveId);
    $bundle = [];
    $dataFile = trim((string) ($snapshot['_data_file'] ?? ''));
    if ($dataFile !== '' && strpos($dataFile, '..') === false) {
        $full = APP_ROOT . '/' . ltrim($dataFile, '/');
        if (is_file($full)) {
            $decoded = json_decode((string) @file_get_contents($full), true);
            if (is_array($decoded)) { $bundle = $decoded; }
        }
    }
    if (!$bundle) {
        $bundle = [
            'data' => is_array($snapshot['_data'] ?? null) ? $snapshot['_data'] : [],
            'files' => is_array($snapshot['_files'] ?? null) ? $snapshot['_files'] : [],
        ];
    }
    $files = is_array($bundle['files'] ?? null) ? $bundle['files'] : [];
    foreach ($files as $rel) {
        $rel = ltrim(str_replace('\\', '/', (string) $rel), '/');
        if ($rel === '' || strpos($rel, '..') !== false) { continue; }
        if (strpos($rel, 'uploads/') !== 0 && strpos($rel, 'storage/drive/') !== 0) { continue; }
        $src = APP_ROOT . '/' . $dir . '/files/' . $rel;
        $dest = APP_ROOT . '/' . $rel;
        if (!is_file($src)) { continue; }
        if (!is_dir(dirname($dest))) { @mkdir(dirname($dest), 0775, true); }
        if (!is_file($dest)) { @copy($src, $dest); }
    }

    $data = is_array($bundle['data'] ?? null) ? $bundle['data'] : [];
    $ownerCols = ['user_id', 'from_id', 'to_id', 'sender_id', 'receiver_id', 'follower_id',
        'following_id', 'visitor_id', 'owner_id', 'friend_id', 'blocker_id', 'blocked_id',
        'host_id', 'profile_user_id'];
    foreach ($data as $table => $rows) {
        if (!is_array($rows) || !$rows) { continue; }
        $cols = account_table_columns($table);
        if (!$cols) { continue; }
        try {
            foreach ($rows as $row) {
                if (!is_array($row)) { continue; }
                $vals = array_intersect_key($row, array_flip($cols));
                if (!$vals) { continue; }
                foreach ($ownerCols as $col) {
                    if (isset($vals[$col]) && (int) $vals[$col] === (int) $oldUid && (int) $oldUid !== (int) $newUid) {
                        $vals[$col] = (int) $newUid;
                    }
                }
                DB::insert($table, $vals);
            }
        } catch (Throwable $e) {
            return [false, '恢复「' . $table . '」数据失败：' . $e->getMessage()];
        }
    }
    return [true, ''];
}

function account_delete_archive($user, $deletedBy = 0, $summary = '')
{
    $uid = (int) ($user['id'] ?? 0);
    if ($uid <= 0) {
        return 0;
    }
    $avatarArchive = '';
    $avatar = trim((string) ($user['avatar'] ?? ''));
    if ($avatar !== '' && strpos($avatar, 'uploads/') === 0 && is_file(APP_ROOT . '/' . $avatar)) {
        $ext = strtolower((string) pathinfo($avatar, PATHINFO_EXTENSION));
        if ($ext === '' || !preg_match('/^[a-z0-9]{1,8}$/', $ext)) {
            $ext = 'bin';
        }
        $dir = APP_ROOT . '/storage/deleted_accounts';
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }
        $rel = 'storage/deleted_accounts/' . $uid . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $ext;
        if (@copy(APP_ROOT . '/' . $avatar, APP_ROOT . '/' . $rel)) {
            $avatarArchive = $rel;
        }
    }
    $snapshot = $user;
    $snapshot['_deleted_at'] = now();
    $snapshot['_avatar_archive'] = $avatarArchive;
    $id = DB::insert('deleted_accounts', [
        'original_uid' => $uid,
        'username' => (string) ($user['username'] ?? ''),
        'nickname' => (string) ($user['nickname'] ?? ''),
        'email' => (string) ($user['email'] ?? ''),
        'role' => (string) ($user['role'] ?? 'user'),
        'snapshot' => json_encode($snapshot, JSON_UNESCAPED_UNICODE),
        'summary' => mb_substr((string) $summary, 0, 255),
        'avatar_archive' => $avatarArchive,
        'deleted_by' => (int) $deletedBy,
        'created_at' => now(),
    ]);
    account_archive_user_data((int) $id, $user);
    return (int) $id;
}

function user_table_columns()
{
    static $cols = null;
    if (is_array($cols)) { return $cols; }
    $cols = [];
    try {
        if (DB::$driver === 'sqlite') {
            foreach (DB::all('PRAGMA table_info(' . DB::table('users') . ')') as $row) {
                $cols[] = (string) $row['name'];
            }
        } else {
            foreach (DB::all('SELECT column_name FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ?', [DB::table('users')]) as $row) {
                $cols[] = (string) $row['column_name'];
            }
        }
    } catch (Throwable $e) {
        $cols = [];
    }
    return $cols;
}

/** 从删除存档恢复账号；只恢复账号资料与登录能力，已按删除规则清理的内容不会回来 */
function account_restore_archive($archiveId, $adminId = 0)
{
    $archiveId = (int) $archiveId;
    $row = DB::one('SELECT * FROM ' . DB::table('deleted_accounts') . ' WHERE id = ? AND restored_at = \'\' AND restored_uid = 0', [$archiveId]);
    if (!$row) {
        return [false, '存档不存在或已经恢复过'];
    }
    $snapshot = json_decode((string) ($row['snapshot'] ?? ''), true);
    if (!is_array($snapshot)) {
        return [false, '存档数据损坏，无法恢复'];
    }
    $originalUid = (int) ($row['original_uid'] ?? 0);
    if ($originalUid > 0 && user_by_id($originalUid)) {
        return [false, '原账号 ID 已被新账号占用，无法原地恢复'];
    }
    $username = trim((string) ($snapshot['username'] ?? $row['username'] ?? ''));
    if ($username === '' || user_by_username($username)) {
        return [false, '原用户名已被占用，无法恢复'];
    }
    $email = trim((string) ($snapshot['email'] ?? ''));
    if ($email !== '' && DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE email = ?', [$email], 0)) {
        return [false, '原绑定邮箱已被其他账号占用，无法恢复'];
    }

    $cols = user_table_columns();
    $data = $cols ? array_intersect_key($snapshot, array_flip($cols)) : $snapshot;
    unset($data['id']);
    if ($originalUid > 0 && !user_by_id($originalUid)) {
        $data['id'] = $originalUid;
    }
    $data['username'] = $username;
    $data['status'] = 1;
    $data['auth_token'] = '';
    $data['auth_token_device'] = '';
    $data['login_fail_count'] = 0;
    $data['login_locked_until'] = '';
    $data['created_at'] = (string) ($snapshot['created_at'] ?? now());
    if ($email === '') {
        $data['email'] = '';
        $data['email_verified'] = 0;
        $data['email_login_verify'] = 0;
    }

    $avatarArchive = trim((string) ($row['avatar_archive'] ?? ''));
    $avatar = trim((string) ($snapshot['avatar'] ?? ''));
    if ($avatarArchive !== '' && is_file(APP_ROOT . '/' . $avatarArchive)) {
        if ($avatar !== '' && strpos($avatar, 'uploads/') === 0) {
            $dest = $avatar;
        } else {
            $ext = strtolower((string) pathinfo($avatarArchive, PATHINFO_EXTENSION));
            $dest = 'uploads/avatars/restored-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . ($ext !== '' ? '.' . $ext : '');
        }
        $destFull = APP_ROOT . '/' . $dest;
        if (!is_dir(dirname($destFull))) { @mkdir(dirname($destFull), 0775, true); }
        if (@copy(APP_ROOT . '/' . $avatarArchive, $destFull)) {
            $data['avatar'] = $dest;
        } else {
            $data['avatar'] = $avatar;
        }
    }

    try {
        DB::$pdo->beginTransaction();
        $newUid = DB::insert('users', $data);
        if ($newUid <= 0) {
            throw new Exception('未能写入账号');
        }
        list($dataOk, $dataMsg) = account_restore_user_data($archiveId, $snapshot, (int) $newUid, $originalUid);
        if (!$dataOk) {
            throw new Exception($dataMsg);
        }
        DB::update('deleted_accounts', [
            'restored_at' => now(),
            'restored_uid' => (int) $newUid,
        ], 'id = ?', [$archiveId]);
        DB::$pdo->commit();
    } catch (Throwable $e) {
        if (DB::$pdo->inTransaction()) { DB::$pdo->rollBack(); }
        return [false, '恢复失败：' . $e->getMessage()];
    }
    audit_log('user_restore', '存档 #' . $archiveId . ' → UID ' . $newUid . ' 操作者 ' . (int) $adminId);
    return [true, '账号及全部数据已恢复为 UID ' . $newUid . '，用户名 @' . $username, (int) $newUid];
}

function user_delete_account($uid, $deletedBy = 0)
{
    $uid = (int) $uid;
    if ($uid <= 0) {
        throw new Exception('账号无效');
    }
    $user = user_by_id($uid);
    if (!$user) {
        throw new Exception('账号不存在');
    }
    if (is_installer_admin($user)) {
        throw new Exception('部署页设置的管理员账号已锁死，不能注销');
    }

    $summaryParts = [];
    foreach ([
        'posts' => '帖子', 'comments' => '评论', 'moments' => '世界圈',
        'netdisk' => '网盘', 'gallery' => '图床', 'messages' => '私信',
    ] as $table => $label) {
        try {
            if ($table === 'messages') {
                $count = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table($table) . ' WHERE from_id = ? OR to_id = ?', [$uid, $uid], 0);
            } else {
                $count = DB::count($table, 'user_id = ?', [$uid]);
            }
            if ($count > 0) { $summaryParts[] = $label . ' ' . $count; }
        } catch (Throwable $e) {
            // 表不存在时跳过计入
        }
    }
    account_delete_archive($user, (int) $deletedBy, $summaryParts ? ('删除前含 ' . implode(' · ', $summaryParts)) : '无内容');

    // 帖子及其附件、评论、点赞、收藏、举报记录
    $posts = DB::all('SELECT id FROM ' . DB::table('posts') . ' WHERE user_id = ?', [$uid]);
    foreach ($posts as $p) {
        post_delete((int) $p['id']);
    }

    // 用户在其他帖子下留下的互动
    DB::delete('comments', 'user_id = ?', [$uid]);
    DB::delete('likes', 'user_id = ?', [$uid]);
    DB::delete('favorites', 'user_id = ?', [$uid]);
    DB::delete('post_views', 'user_id = ?', [$uid]);

    // 未挂在本人帖子下的附件
    $atts = DB::all('SELECT path FROM ' . DB::table('attachments') . ' WHERE user_id = ?', [$uid]);
    foreach ($atts as $att) {
        if (!empty($att['path'])) {
            delete_upload($att['path']);
        }
    }
    DB::delete('attachments', 'user_id = ?', [$uid]);

    // 网盘文件与实体文件
    $driveFiles = DB::all('SELECT path FROM ' . DB::table('netdisk') . ' WHERE user_id = ?', [$uid]);
    foreach ($driveFiles as $f) {
        if (strpos((string) $f['path'], 'storage/drive/') === 0) {
            $full = APP_ROOT . '/' . $f['path'];
            if (is_file($full)) {
                @unlink($full);
            }
        }
    }
    DB::delete('netdisk', 'user_id = ?', [$uid]);

    // 图床图片
    $gallery = DB::all('SELECT path FROM ' . DB::table('gallery') . ' WHERE user_id = ?', [$uid]);
    foreach ($gallery as $g) {
        if (!empty($g['path'])) {
            delete_upload($g['path']);
        }
    }
    DB::delete('gallery', 'user_id = ?', [$uid]);

    // 聊天记录 / 上传文件 / 禁言 / 通话
    $chats = DB::all('SELECT path FROM ' . DB::table('chat') . ' WHERE user_id = ?', [$uid]);
    foreach ($chats as $c) {
        if (!empty($c['path'])) {
            delete_upload($c['path']);
        }
    }
    DB::delete('chat', 'user_id = ?', [$uid]);
    DB::delete('chat_mutes', 'user_id = ?', [$uid]);

    $calls = DB::all('SELECT id FROM ' . DB::table('chat_calls') . ' WHERE host_id = ?', [$uid]);
    foreach ($calls as $call) {
        DB::delete('chat_call_members', 'call_id = ?', [(int) $call['id']]);
        DB::delete('chat_signals', 'call_id = ?', [(int) $call['id']]);
    }
    DB::delete('chat_calls', 'host_id = ?', [$uid]);
    DB::delete('chat_call_members', 'user_id = ?', [$uid]);
    DB::run('DELETE FROM ' . DB::table('chat_signals') . ' WHERE from_id = ? OR to_id = ?', [$uid, $uid]);

    // 世界圈动态、点赞与评论
    $moments = DB::all('SELECT id, media_path FROM ' . DB::table('moments') . ' WHERE user_id = ?', [$uid]);
    foreach ($moments as $m) {
        if (!empty($m['media_path'])) {
            delete_upload($m['media_path']);
        }
        DB::delete('moment_comments', 'moment_id = ?', [(int) $m['id']]);
        DB::delete('moment_likes', 'moment_id = ?', [(int) $m['id']]);
    }
    DB::delete('moments', 'user_id = ?', [$uid]);
    DB::delete('moment_likes', 'user_id = ?', [$uid]);
    DB::delete('moment_comments', 'user_id = ?', [$uid]);

    // 私信、通知、举报
    DB::run('DELETE FROM ' . DB::table('messages') . ' WHERE from_id = ? OR to_id = ?', [$uid, $uid]);
    DB::run('DELETE FROM ' . DB::table('notifications') . ' WHERE user_id = ? OR from_id = ?', [$uid, $uid]);
    DB::delete('reports', 'user_id = ?', [$uid]);

    // 积分、资料修改、转账、红包、邮箱验证码
    DB::delete('point_logs', 'user_id = ?', [$uid]);
    DB::delete('profile_changes', 'user_id = ?', [$uid]);
    DB::run('DELETE FROM ' . DB::table('transfers') . ' WHERE from_id = ? OR to_id = ?', [$uid, $uid]);
    DB::delete('red_packets', 'sender_id = ?', [$uid]);
    DB::delete('email_codes', 'user_id = ?', [$uid]);
    if (trim((string) ($user['email'] ?? '')) !== '') {
        DB::delete('email_codes', 'email = ?', [$user['email']]);
    }

    // 社交关系、草稿、访问记录：归档后可随账号一起恢复
    DB::delete('drafts', 'user_id = ?', [$uid]);
    DB::run('DELETE FROM ' . DB::table('friends') . ' WHERE user_id = ? OR friend_id = ?', [$uid, $uid]);
    DB::run('DELETE FROM ' . DB::table('friend_requests') . ' WHERE from_id = ? OR to_id = ?', [$uid, $uid]);
    DB::run('DELETE FROM ' . DB::table('blocked_users') . ' WHERE blocker_id = ? OR blocked_id = ?', [$uid, $uid]);
    DB::run('DELETE FROM ' . DB::table('profile_visits') . ' WHERE profile_user_id = ? OR visitor_id = ?', [$uid, $uid]);
    DB::run('DELETE FROM ' . DB::table('follows') . " WHERE follower_id = ? OR (target_type = 'user' AND target_id = ?)", [$uid, $uid]);

    // 头像和账号本身
    if (strpos((string) ($user['avatar'] ?? ''), 'uploads/') === 0) {
        delete_upload($user['avatar']);
    }
    DB::delete('users', 'id = ?', [$uid]);
}

function audio_make_compatible($relPath)
{
    $relPath = str_replace('\\', '/', (string) $relPath);
    if (strpos($relPath, 'uploads/') !== 0 || strpos($relPath, '..') !== false) {
        return null;
    }
    $full = APP_ROOT . '/' . $relPath;
    if (!is_file($full)) {
        return null;
    }
    $ext = strtolower((string) pathinfo($full, PATHINFO_EXTENSION));
    // MP3 在 iOS、安卓、电脑浏览器上兼容性最好，无需转换
    if (in_array($ext, ['mp3', 'm4a'], true)) {
        return $relPath;
    }
    $ffmpeg = '';
    foreach (['/usr/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/opt/homebrew/bin/ffmpeg'] as $bin) {
        if (is_executable($bin)) {
            $ffmpeg = $bin;
            break;
        }
    }
    if ($ffmpeg === '' && function_exists('shell_exec')) {
        $found = trim((string) @shell_exec('command -v ffmpeg 2>/dev/null'));
        if ($found !== '' && strpos($found, '/') !== false) {
            $ffmpeg = $found;
        }
    }
    if ($ffmpeg === '' || !function_exists('exec')) {
        // 转换器不可用时不拒绝上传，保留原文件，由浏览器自行尝试播放
        return $relPath;
    }

    $targetRel = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '.mp3', $relPath);
    $targetFull = APP_ROOT . '/' . $targetRel;
    $cmd = escapeshellarg($ffmpeg) . ' -nostdin -y -i ' . escapeshellarg($full)
        . ' -vn -c:a libmp3lame -b:a 128k -ac 2 -ar 44100 '
        . escapeshellarg($targetFull) . ' 2>&1';
    $out = [];
    $code = 1;
    @exec($cmd, $out, $code);
    if ($code !== 0 || !is_file($targetFull) || filesize($targetFull) <= 0) {
        @unlink($targetFull);
        // 服务器未编译 libmp3lame 时退回 AAC(m4a)，iOS 也能播放
        $targetRel = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '.m4a', $relPath);
        $targetFull = APP_ROOT . '/' . $targetRel;
        $cmd = escapeshellarg($ffmpeg) . ' -nostdin -y -i ' . escapeshellarg($full)
            . ' -vn -c:a aac -b:a 128k -ac 2 -ar 44100 -movflags +faststart '
            . escapeshellarg($targetFull) . ' 2>&1';
        $out = [];
        $code = 1;
        @exec($cmd, $out, $code);
        if ($code !== 0 || !is_file($targetFull) || filesize($targetFull) <= 0) {
            @unlink($targetFull);
            // 转换失败也保留原始音频，保证任何格式都能上传
            return $relPath;
        }
    }
    @unlink($full);
    return $targetRel;
}

function delete_upload($relPath)
{
    $relPath = str_replace('\\', '/', (string) $relPath);
    if (strpos($relPath, 'uploads/') !== 0 || strpos($relPath, '..') !== false) {
        return false;
    }
    $full = APP_ROOT . '/' . $relPath;
    return is_file($full) ? @unlink($full) : false;
}

function audio_meta_clean_text($text)
{
    $text = (string) $text;
    $text = preg_replace('/\x00.*$/s', '', $text);
    $text = str_replace(["\r", "\n", "\t"], ' ', $text);
    $text = trim(preg_replace('/\s+/u', ' ', $text));
    return mb_substr($text, 0, 80, 'UTF-8');
}

function audio_meta_decode_text($text)
{
    $text = (string) $text;
    $text = trim($text);
    if ($text === '') {
        return '';
    }
    if (function_exists('mb_convert_encoding')) {
        $text = @mb_convert_encoding($text, 'UTF-8', 'UTF-8');
    }
    return audio_meta_clean_text($text);
}

function audio_meta_decode_encoded($text, $encoding)
{
    $text = (string) $text;
    if ($text === '') {
        return '';
    }
    if (in_array($encoding, ['UTF-16', 'UTF-16LE', 'UTF-16BE'], true)) {
        if (substr($text, 0, 2) === "\xFF\xFE") {
            $text = substr($text, 2);
            $encoding = 'UTF-16LE';
        } elseif (substr($text, 0, 2) === "\xFE\xFF") {
            $text = substr($text, 2);
            $encoding = 'UTF-16BE';
        } elseif ($encoding === 'UTF-16') {
            $encoding = 'UTF-16LE';
        }
    }
    if (function_exists('mb_convert_encoding')) {
        $converted = @mb_convert_encoding($text, 'UTF-8', $encoding);
        if (is_string($converted) && $converted !== '') {
            return audio_meta_clean_text($converted);
        }
    }
    return audio_meta_clean_text($text);
}

function audio_meta_from_name($name)
{
    $name = (string) $name;
    $name = preg_replace('/\?.*$/', '', $name);
    $name = basename($name);
    $name = rawurldecode($name);
    $name = preg_replace('/\.(mp3|m4a|mp4|aac|wav|flac|ogg|oga|opus|weba|webm|amr|wma|mid|midi)$/i', '', $name);
    $name = trim(preg_replace('/[_+]+/u', ' ', $name));
    if ($name === '') {
        $name = '未命名音频';
    }
    if (preg_match('/^(.*?)\s*-\s*(.*)$/u', $name, $m)) {
        $artist = audio_meta_clean_text($m[1]);
        $title = audio_meta_clean_text($m[2]);
        if ($artist !== '' && $title !== '') {
            return ['title' => $title, 'artist' => $artist, 'cover' => '', 'lyrics' => ''];
        }
    }
    return ['title' => audio_meta_clean_text($name), 'artist' => '未知歌手', 'cover' => '', 'lyrics' => ''];
}

function audio_meta_local_path($src)
{
    $src = html_entity_decode((string) $src, ENT_QUOTES, 'UTF-8');
    $path = parse_url($src, PHP_URL_PATH);
    if (!is_string($path) || $path === '') {
        $path = $src;
    }
    $path = rawurldecode($path);
    $pos = strpos($path, 'uploads/');
    if ($pos === false) {
        $pos = strpos($path, 'storage/drive/');
    }
    if ($pos === false) {
        return '';
    }
    $rel = ltrim(substr($path, $pos), '/');
    if ($rel === '' || strpos($rel, '..') !== false) {
        return '';
    }
    $full = APP_ROOT . '/' . $rel;
    if (is_file($full)) {
        return $rel;
    }
    // 音频格式转换后原文件会被删除，优先读取同目录同名的 mp3 / m4a 产物
    $ext = strtolower((string) pathinfo($rel, PATHINFO_EXTENSION));
    if (in_array($ext, ['webm', 'ogg', 'oga', 'opus', 'wav', 'amr', 'aac', 'flac', 'wma', 'mid', 'midi', 'weba'], true)) {
        foreach (['mp3', 'm4a'] as $targetExt) {
            $candidate = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '.' . $targetExt, $rel);
            if ($candidate !== $rel && is_file(APP_ROOT . '/' . $candidate)) {
                return $candidate;
            }
        }
    }
    return '';
}

function audio_id3_syncsafe($bytes)
{
    $n = 0;
    foreach (str_split((string) $bytes) as $ch) {
        $n = ($n * 128) + ord($ch);
    }
    return $n;
}

function audio_id3_text_frame($frame)
{
    if (!is_string($frame) || $frame === '') {
        return '';
    }
    $encoding = ord($frame[0]);
    $text = substr($frame, 1);
    if ($encoding === 1) {
        return audio_meta_decode_encoded($text, 'UTF-16');
    }
    if ($encoding === 2) {
        return audio_meta_decode_encoded($text, 'UTF-16BE');
    }
    if ($encoding === 3) {
        return audio_meta_decode_text($text);
    }
    return audio_meta_decode_encoded($text, 'ISO-8859-1');
}

function audio_cover_info($data)
{
    if (!is_string($data) || strlen($data) < 64 || strlen($data) > 8 * 1024 * 1024) {
        return null;
    }
    $info = @getimagesizefromstring($data);
    if (!$info || empty($info[0]) || empty($info[1]) || $info[0] > 6000 || $info[1] > 6000) {
        return null;
    }
    $mime = (string) ($info['mime'] ?? '');
    $extMap = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp'];
    if (!isset($extMap[$mime])) {
        return null;
    }
    return ['data' => $data, 'ext' => $extMap[$mime]];
}

function audio_image_from_frame($frame)
{
    foreach ([["\xFF\xD8\xFF", 'jpg'], ["\x89PNG\r\n\x1a\n", 'png'], ["GIF87a", 'gif'], ["GIF89a", 'gif']] as $sig) {
        $pos = strpos($frame, $sig[0]);
        if ($pos !== false) {
            $data = substr($frame, $pos);
            $info = audio_cover_info($data);
            if ($info) { return $info['data']; }
        }
    }
    $pos = strpos($frame, 'RIFF');
    if ($pos !== false && substr($frame, $pos + 8, 4) === 'WEBP') {
        $data = substr($frame, $pos);
        $info = audio_cover_info($data);
        if ($info) { return $info['data']; }
    }
    return '';
}

function audio_cover_cache_store($rel, $data)
{
    $info = audio_cover_info($data);
    if (!$info) { return ''; }
    // 以封面二进制内容做键：同一首音频重新匹配到新封面时也会生成新文件，避免沿用旧封面。
    $key = sha1((string) $info['data']);
    $dir = APP_ROOT . '/uploads/audio-covers';
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        return '';
    }
    $targetRel = 'uploads/audio-covers/' . $key . '.' . $info['ext'];
    $target = APP_ROOT . '/' . $targetRel;
    if (!is_file($target)) {
        if (@file_put_contents($target, $info['data'], LOCK_EX) === false) {
            return '';
        }
        @chmod($target, 0644);
    }
    return $targetRel;
}

function audio_mp4_cover_data($fh, $start, $end)
{
    $pos = $start;
    while ($pos + 8 <= $end) {
        fseek($fh, $pos);
        $head = fread($fh, 8);
        if (strlen($head) < 8) { break; }
        $size = (int) unpack('N', substr($head, 0, 4))[1];
        $type = substr($head, 4, 4);
        if ($size < 8 || $pos + $size > $end) { break; }
        if ($type === 'data') {
            fseek($fh, $pos + 8);
            $body = fread($fh, max(0, $size - 8));
            if (strlen($body) >= 9) {
                $img = substr($body, 8);
                $info = audio_cover_info($img);
                if ($info) { return $info['data']; }
            }
        }
        $pos += $size;
    }
    return '';
}

function audio_flac_picture($data)
{
    $len = strlen($data);
    $pos = 4;
    if ($pos + 4 > $len) { return ''; }
    $mimeLen = (int) unpack('N', substr($data, $pos, 4))[1]; $pos += 4;
    $pos += max(0, $mimeLen);
    if ($pos + 4 > $len) { return ''; }
    $descLen = (int) unpack('N', substr($data, $pos, 4))[1]; $pos += 4 + max(0, $descLen);
    $pos += 16;
    if ($pos + 4 > $len) { return ''; }
    $dataLen = (int) unpack('N', substr($data, $pos, 4))[1]; $pos += 4;
    if ($dataLen < 64 || $pos + $dataLen > $len) { return ''; }
    $img = substr($data, $pos, $dataLen);
    $info = audio_cover_info($img);
    return $info ? $info['data'] : '';
}

function audio_lyrics_clean($text)
{
    $text = (string) $text;
    $text = str_replace(["\r\n", "\r"], "\n", $text);
    $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', $text);
    $text = trim($text);
    return mb_substr($text, 0, 4000, 'UTF-8');
}

function audio_id3_raw_text($frame)
{
    if (!is_string($frame) || $frame === '') { return ''; }
    $encoding = ord($frame[0]);
    $text = substr($frame, 1);
    if ($encoding === 1 || $encoding === 2) {
        if (substr($text, 0, 2) === "\xFF\xFE") { $text = substr($text, 2); $encoding = 1; }
        elseif (substr($text, 0, 2) === "\xFE\xFF") { $text = substr($text, 2); $encoding = 2; }
        $src = $encoding === 2 ? 'UTF-16BE' : 'UTF-16LE';
        $converted = function_exists('mb_convert_encoding') ? @mb_convert_encoding($text, 'UTF-8', $src) : $text;
        return audio_lyrics_clean($converted);
    }
    if ($encoding === 3) { return audio_lyrics_clean($text); }
    return audio_lyrics_clean(function_exists('mb_convert_encoding') ? @mb_convert_encoding($text, 'UTF-8', 'ISO-8859-1') : $text);
}

function audio_id3_txxx_frame($frame)
{
    if (!is_string($frame) || strlen($frame) < 2) { return ['', '']; }
    $encoding = ord($frame[0]);
    $body = substr($frame, 1);
    $pos = false;
    if ($encoding === 1 || $encoding === 2) {
        $pos = 0;
        while (($pos = strpos($body, "\x00\x00", $pos)) !== false) {
            if ($pos % 2 === 0) { break; }
            $pos++;
        }
        if ($pos === false) { return ['', '']; }
        $desc = substr($body, 0, $pos);
        $value = substr($body, $pos + 2);
    } else {
        $pos = strpos($body, "\x00");
        if ($pos === false) { return ['', '']; }
        $desc = substr($body, 0, $pos);
        $value = substr($body, $pos + 1);
    }
    return [
        strtolower(trim(audio_id3_text_frame(chr($encoding) . $desc))),
        audio_id3_raw_text(chr($encoding) . $value),
    ];
}

function audio_id3_lyrics_frame($frame)
{
    if (!is_string($frame) || strlen($frame) < 4) { return ''; }
    $encoding = ord($frame[0]);
    $body = substr($frame, 4);
    $pos = false;
    if ($encoding === 1 || $encoding === 2) {
        $pos = 0;
        while (($pos = strpos($body, "\x00\x00", $pos)) !== false) {
            if ($pos % 2 === 0) { break; }
            $pos++;
        }
        if ($pos !== false) { $body = substr($body, $pos + 2); }
    } else {
        $pos = strpos($body, "\x00");
        if ($pos !== false) { $body = substr($body, $pos + 1); }
    }
    return audio_id3_raw_text(chr($encoding) . $body);
}

function audio_read_id3v2($full, &$title, &$artist, &$cover = null, &$lyrics = null)
{
    $fh = @fopen($full, 'rb');
    if (!$fh) {
        return;
    }
    $header = fread($fh, 10);
    if (strlen($header) < 10 || substr($header, 0, 3) !== 'ID3') {
        fclose($fh);
        return;
    }
    $version = ord($header[3]);
    $flags = ord($header[5]);
    $size = audio_id3_syncsafe(substr($header, 6, 4));
    if ($size <= 0 || $size > 10 * 1024 * 1024) {
        fclose($fh);
        return;
    }
    $tag = fread($fh, $size);
    fclose($fh);
    if (!is_string($tag) || $tag === '') {
        return;
    }
    $pos = 0;
    if ($version >= 3 && ($flags & 0x40)) {
        $extSize = $version === 4
            ? audio_id3_syncsafe(substr($tag, 0, 4))
            : (int) unpack('N', substr($tag, 0, 4))[1];
        $pos += max(4, $extSize);
    }
    $frameHeader = $version === 2 ? 6 : 10;
    while ($pos + $frameHeader <= strlen($tag)) {
        $id = substr($tag, $pos, $version === 2 ? 3 : 4);
        if ($id === '' || strpos($id, "\x00") !== false) {
            break;
        }
        if ($version === 2) {
            $frameSize = (ord($tag[$pos + 3]) << 16) | (ord($tag[$pos + 4]) << 8) | ord($tag[$pos + 5]);
        } elseif ($version === 4) {
            $frameSize = audio_id3_syncsafe(substr($tag, $pos + 4, 4));
        } else {
            $frameSize = (int) unpack('N', substr($tag, $pos + 4, 4))[1];
        }
        if ($frameSize <= 0 || $pos + $frameHeader + $frameSize > strlen($tag)) {
            break;
        }
        $frame = substr($tag, $pos + $frameHeader, $frameSize);
        if ($id === 'TIT2' || $id === 'TT2') {
            $value = audio_id3_text_frame($frame);
            if ($value !== '') {
                $title = $value;
            }
        } elseif ($id === 'TPE1' || $id === 'TP1') {
            $value = audio_id3_text_frame($frame);
            if ($value !== '') {
                $artist = $value;
            }
        } elseif ($cover !== null && $cover === '' && ($id === 'APIC' || $id === 'PIC')) {
            $img = audio_image_from_frame($frame);
            if ($img !== '') { $cover = $img; }
        } elseif ($lyrics !== null && $lyrics === '' && ($id === 'USLT' || $id === 'ULT')) {
            $value = audio_id3_lyrics_frame($frame);
            if ($value !== '') { $lyrics = $value; }
        } elseif ($lyrics !== null && $lyrics === '' && $id === 'TXXX') {
            list($desc, $value) = audio_id3_txxx_frame($frame);
            if (in_array($desc, ['lyrics', 'unsyncedlyrics', 'lrc', 'lyric', 'uslt'], true) && $value !== '') {
                $lyrics = $value;
            }
        }
        $pos += $frameHeader + $frameSize;
    }
}

function audio_read_id3v1($full, &$title, &$artist)
{
    $size = @filesize($full);
    if ($size < 128) {
        return;
    }
    $fh = @fopen($full, 'rb');
    if (!$fh) {
        return;
    }
    fseek($fh, $size - 128);
    $tag = fread($fh, 128);
    fclose($fh);
    if (strlen($tag) < 128 || substr($tag, 0, 3) !== 'TAG') {
        return;
    }
    $titleValue = audio_meta_decode_encoded(trim(substr($tag, 3, 30), "\x00 "), 'ISO-8859-1');
    $artistValue = audio_meta_decode_encoded(trim(substr($tag, 33, 30), "\x00 "), 'ISO-8859-1');
    if ($title === '' && $titleValue !== '') {
        $title = $titleValue;
    }
    if ($artist === '' && $artistValue !== '') {
        $artist = $artistValue;
    }
}

function audio_mp4_data_text($fh, $start, $end)
{
    $pos = $start;
    while ($pos + 8 <= $end) {
        fseek($fh, $pos);
        $head = fread($fh, 8);
        if (strlen($head) < 8) {
            break;
        }
        $size = (int) unpack('N', substr($head, 0, 4))[1];
        $type = substr($head, 4, 4);
        if ($size < 8 || $pos + $size > $end) {
            break;
        }
        if ($type === 'data') {
            $body = fread($fh, max(0, $size - 8));
            if (strlen($body) >= 8) {
                $dataType = (int) unpack('N', substr($body, 0, 4))[1];
                $text = substr($body, 8);
                return $dataType === 2
                    ? audio_meta_decode_encoded($text, 'UTF-16')
                    : audio_meta_decode_text($text);
            }
        }
        $pos += $size;
    }
    return '';
}

function audio_mp4_boxes($fh, $start, $end, $depth, &$title, &$artist, &$cover = null, &$lyrics = null)
{
    if ($depth > 7) {
        return;
    }
    $pos = $start;
    while ($pos + 8 <= $end) {
        fseek($fh, $pos);
        $head = fread($fh, 8);
        if (strlen($head) < 8) {
            break;
        }
        $size = (int) unpack('N', substr($head, 0, 4))[1];
        $type = substr($head, 4, 4);
        $header = 8;
        if ($size === 1) {
            $large = fread($fh, 8);
            if (strlen($large) < 8) {
                break;
            }
            $size = (int) unpack('J', $large)[1];
            $header = 16;
        }
        if ($size === 0) {
            $size = $end - $pos;
        }
        if ($size < 8 || $pos + $size > $end) {
            break;
        }
        $payloadStart = $pos + $header;
        $payloadEnd = $pos + $size;
        if (in_array($type, ['moov', 'udta', 'ilst'], true)) {
            audio_mp4_boxes($fh, $payloadStart, $payloadEnd, $depth + 1, $title, $artist, $cover, $lyrics);
        } elseif ($type === 'meta') {
            audio_mp4_boxes($fh, min($payloadEnd, $payloadStart + 4), $payloadEnd, $depth + 1, $title, $artist, $cover, $lyrics);
        } elseif ($type === "\xA9nam" || $type === "\xA9ART") {
            $value = audio_mp4_data_text($fh, $payloadStart, $payloadEnd);
            if ($value !== '') {
                if ($type === "\xA9nam") {
                    $title = $value;
                } else {
                    $artist = $value;
                }
            }
        } elseif ($type === 'covr' && $cover !== null && $cover === '') {
            $img = audio_mp4_cover_data($fh, $payloadStart, $payloadEnd);
            if ($img !== '') { $cover = $img; }
        } elseif ($type === "\xA9lyr" && $lyrics !== null && $lyrics === '') {
            $value = audio_mp4_data_text($fh, $payloadStart, $payloadEnd);
            if ($value !== '') { $lyrics = audio_lyrics_clean($value); }
        }
        $pos += $size;
    }
}

function audio_read_mp4($full, &$title, &$artist, &$cover = null, &$lyrics = null)
{
    $size = @filesize($full);
    if ($size <= 0) {
        return;
    }
    $fh = @fopen($full, 'rb');
    if (!$fh) {
        return;
    }
    audio_mp4_boxes($fh, 0, $size, 0, $title, $artist, $cover, $lyrics);
    fclose($fh);
}

function audio_vorbis_comments($data, $offset, &$title, &$artist, &$lyrics = null)
{
    $length = strlen($data);
    if ($offset + 8 > $length) {
        return;
    }
    $vendorLength = (int) unpack('V', substr($data, $offset, 4))[1];
    $offset += 4 + $vendorLength;
    if ($offset + 4 > $length) {
        return;
    }
    $count = (int) unpack('V', substr($data, $offset, 4))[1];
    $offset += 4;
    $count = min($count, 1000);
    for ($i = 0; $i < $count && $offset + 4 <= $length; $i++) {
        $commentLength = (int) unpack('V', substr($data, $offset, 4))[1];
        $offset += 4;
        if ($commentLength < 1 || $offset + $commentLength > $length) {
            break;
        }
        $comment = substr($data, $offset, $commentLength);
        $offset += $commentLength;
        $eq = strpos($comment, '=');
        if ($eq === false) {
            continue;
        }
        $key = strtoupper(substr($comment, 0, $eq));
        $value = audio_meta_clean_text(substr($comment, $eq + 1));
        if ($key === 'TITLE' && $value !== '') {
            $title = $value;
        } elseif ($key === 'ARTIST' && $value !== '') {
            $artist = $value;
        } elseif (($key === 'LYRICS' || $key === 'UNSYNCEDLYRICS') && $lyrics !== null && $lyrics === '') {
            $lyrics = audio_lyrics_clean(substr($comment, $eq + 1));
        }
    }
}

function audio_read_flac($full, &$title, &$artist, &$cover = null, &$lyrics = null)
{
    $fh = @fopen($full, 'rb');
    if (!$fh) {
        return;
    }
    $magic = fread($fh, 4);
    if ($magic !== 'fLaC') {
        fclose($fh);
        return;
    }
    $pos = 4;
    $size = @filesize($full);
    for ($guard = 0; $guard < 128; $guard++) {
        fseek($fh, $pos);
        $header = fread($fh, 4);
        if (strlen($header) < 4) {
            break;
        }
        $last = (ord($header[0]) & 0x80) !== 0;
        $type = ord($header[0]) & 0x7f;
        $length = (ord($header[1]) << 16) | (ord($header[2]) << 8) | ord($header[3]);
        if ($length < 0 || $pos + 4 + $length > $size) {
            break;
        }
        if ($type === 4) {
            $data = fread($fh, $length);
            if (is_string($data) && $data !== '') {
                audio_vorbis_comments($data, 0, $title, $artist, $lyrics);
            }
        } elseif ($type === 6 && $cover !== null && $cover === '') {
            $data = fread($fh, $length);
            if (is_string($data) && $data !== '') {
                $img = audio_flac_picture($data);
                if ($img !== '') { $cover = $img; }
            }
        }
        $pos += 4 + $length;
        if ($last) {
            break;
        }
    }
    fclose($fh);
}

function audio_read_ogg($full, &$title, &$artist, &$lyrics = null)
{
    $data = @file_get_contents($full, false, null, 0, 2 * 1024 * 1024);
    if (!is_string($data) || $data === '') {
        return;
    }
    $offset = strpos($data, "\x03vorbis");
    if ($offset === false) {
        $offset = strpos($data, 'OpusTags');
        if ($offset !== false) {
            $offset += strlen('OpusTags');
        }
    } else {
        $offset += strlen("\x03vorbis");
    }
    if ($offset !== false) {
        audio_vorbis_comments($data, $offset, $title, $artist, $lyrics);
    }
}

function audio_track_meta($src, $fallbackName = '')
{
    static $cache = [];
    $fallbackName = (string) $fallbackName;
    if ($fallbackName === '') {
        $fallbackName = (string) parse_url((string) $src, PHP_URL_PATH);
    }
    $fallback = audio_meta_from_name($fallbackName);
    $rel = audio_meta_local_path($src);
    if ($rel === '') {
        return $fallback;
    }
    $full = APP_ROOT . '/' . $rel;
    $mtime = @filemtime($full);
    $key = $rel . '|' . $mtime;
    if (isset($cache[$key])) {
        return $cache[$key];
    }
    $ext = strtolower((string) pathinfo($full, PATHINFO_EXTENSION));
    $title = '';
    $artist = '';
    $coverData = '';
    $lyricsData = '';
    if ($ext === 'mp3') {
        audio_read_id3v2($full, $title, $artist, $coverData, $lyricsData);
        if ($title === '' || $artist === '') {
            audio_read_id3v1($full, $title, $artist);
        }
    } elseif (in_array($ext, ['m4a', 'mp4', 'm4b'], true)) {
        audio_read_mp4($full, $title, $artist, $coverData, $lyricsData);
    } elseif ($ext === 'flac') {
        audio_read_flac($full, $title, $artist, $coverData, $lyricsData);
    } elseif (in_array($ext, ['ogg', 'oga', 'opus'], true)) {
        audio_read_ogg($full, $title, $artist, $lyricsData);
    }
    $title = audio_meta_clean_text($title);
    $artist = audio_meta_clean_text($artist);
    if ($title === '') {
        $title = $fallback['title'];
    }
    if ($artist === '') {
        $artist = $fallback['artist'];
    }
    $coverRel = $coverData !== '' ? audio_cover_cache_store($rel, $coverData) : '';
    $result = ['title' => $title, 'artist' => $artist, 'cover' => $coverRel !== '' ? full_url($coverRel) : '', 'lyrics' => $lyricsData];
    $cache[$key] = $result;
    return $result;
}


/** 帖子附件 / 世界圈音频：优先使用手动匹配保存的标题、歌词与封面。 */
function audio_track_meta_stored($row)
{
    $path = (string) ($row['path'] ?? $row['media_path'] ?? '');
    $name = (string) ($row['name'] ?? $row['media_name'] ?? '');
    $meta = audio_track_meta($path, $name);
    $title = trim((string) ($row['matched_title'] ?? ''));
    $artist = trim((string) ($row['matched_artist'] ?? ''));
    if ($title !== '') { $meta['title'] = $title; }
    if ($artist !== '') { $meta['artist'] = $artist; }
    $lyrics = trim((string) ($row['lyrics'] ?? ''));
    if ($lyrics !== '') { $meta['lyrics'] = $lyrics; }
    $coverRel = trim((string) ($row['cover_path'] ?? ''));
    if ($coverRel !== '' && is_file(APP_ROOT . '/' . $coverRel)) {
        $meta['cover'] = full_url($coverRel);
        $meta['cover_path'] = $coverRel;
    }
    return $meta;
}

/** 把匹配好的标题、歌手、封面和歌词写入 MP3 的 ID3v2.3 标签，用于下载文件。 */
function audio_id3_utf16($text)
{
    $text = (string) $text;
    if (function_exists('mb_convert_encoding')) {
        $bin = @mb_convert_encoding($text, 'UTF-16LE', 'UTF-8');
    } elseif (function_exists('iconv')) {
        $bin = @iconv('UTF-8', 'UTF-16LE', $text);
    } else {
        $bin = '';
    }
    return "\xFF\xFE" . (is_string($bin) ? $bin : '');
}

function audio_id3_make_text_frame($id, $text)
{
    $payload = "\x01" . audio_id3_utf16($text) . "\x00\x00";
    return $id . pack('N', strlen($payload)) . "\x00\x00" . $payload;
}

function audio_mp3_tag_prefix(array $meta)
{
    $title = trim((string) ($meta['title'] ?? ''));
    $artist = trim((string) ($meta['artist'] ?? ''));
    $lyrics = trim((string) ($meta['lyrics'] ?? ''));
    $coverRel = trim((string) ($meta['cover_path'] ?? ''));
    $frames = '';
    if ($title !== '') { $frames .= audio_id3_make_text_frame('TIT2', $title); $frames .= audio_id3_make_text_frame('TALB', $title); }
    if ($artist !== '') { $frames .= audio_id3_make_text_frame('TPE1', $artist); }
    if ($lyrics !== '') {
        $payload = "\x01" . 'und' . "\xFF\xFE\x00\x00" . audio_id3_utf16($lyrics) . "\x00\x00";
        $frames .= 'USLT' . pack('N', strlen($payload)) . "\x00\x00" . $payload;
    }
    if ($coverRel !== '' && strpos($coverRel, '..') === false) {
        $coverFile = APP_ROOT . '/' . ltrim($coverRel, '/');
        if (is_file($coverFile) && filesize($coverFile) <= 4 * 1024 * 1024) {
            $mime = 'image/jpeg';
            $info = @getimagesize($coverFile);
            if ($info && !empty($info['mime']) && in_array($info['mime'], ['image/jpeg', 'image/png'], true)) {
                $mime = $info['mime'];
            }
            $data = @file_get_contents($coverFile);
            if (is_string($data) && $data !== '') {
                $payload = "\x00" . $mime . "\x00" . "\x03" . "\x00" . $data;
                $frames .= 'APIC' . pack('N', strlen($payload)) . "\x00\x00" . $payload;
            }
        }
    }
    if ($frames === '') { return ''; }
    $size = strlen($frames);
    $sync = '';
    for ($i = 3; $i >= 0; $i--) { $sync .= chr(($size >> ($i * 7)) & 0x7F); }
    return "ID3\x03\x00\x00" . $sync . $frames;
}

function audio_mp3_tag_end($full)
{
    $fh = @fopen($full, 'rb');
    if (!$fh) { return 0; }
    $head = fread($fh, 10);
    fclose($fh);
    if (strlen($head) < 10 || substr($head, 0, 3) !== 'ID3') { return 0; }
    $size = audio_id3_syncsafe(substr($head, 6, 4));
    $flags = ord($head[5]);
    $offset = 10 + $size;
    if ($flags & 0x10) { $offset += 10; }
    return $offset;
}

/** 网盘歌曲匹配：在线歌词优先取 LRCLIB，封面优先取 iTunes，失败则保留内嵌信息。 */
function audio_match_http_json($url, $timeout = 8, array $headers = [])
{
    if (!preg_match('#^https?://#i', (string) $url)) {
        return [0, null];
    }
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => 'Komorebi-Audio-Match/1.0',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_HTTPHEADER => array_merge(['Accept: application/json'], $headers),
        ]);
        $body = curl_exec($ch);
        $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return [$code, is_string($body) ? json_decode($body, true) : null];
    }
    $ctx = stream_context_create(['http' => [
        'method' => 'GET',
        'timeout' => $timeout,
        'header' => "Accept: application/json\r\nUser-Agent: Komorebi-Audio-Match/1.0\r\n" . implode("\r\n", $headers) . "\r\n",
    ]]);
    $body = @file_get_contents($url, false, $ctx);
    return [$body === false ? 0 : 200, is_string($body) ? json_decode($body, true) : null];
}

function audio_match_http_binary($url, $timeout = 8, $maxBytes = 3145728)
{
    if (!preg_match('#^https?://#i', (string) $url)) {
        return '';
    }
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => 'Komorebi-Audio-Match/1.0',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
        ]);
        $body = curl_exec($ch);
        curl_close($ch);
    } else {
        $ctx = stream_context_create(['http' => ['method' => 'GET', 'timeout' => $timeout, 'header' => "User-Agent: Komorebi-Audio-Match/1.0\r\n"]]);
        $body = @file_get_contents($url, false, $ctx);
    }
    if (!is_string($body) || strlen($body) > $maxBytes) {
        return '';
    }
    return $body;
}

function audio_match_http_raw($url, $timeout = 8, $maxBytes = 3145728)
{
    if (!preg_match('#^https?://#i', (string) $url)) {
        return '';
    }
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => 'Komorebi-Audio-Match/1.0',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_HTTPHEADER => ['Accept: application/json, text/plain, */*'],
        ]);
        $body = curl_exec($ch);
        curl_close($ch);
    } else {
        $ctx = stream_context_create(['http' => ['method' => 'GET', 'timeout' => $timeout, 'header' => "User-Agent: Komorebi-Audio-Match/1.0\r\n"]]);
        $body = @file_get_contents($url, false, $ctx);
    }
    if (!is_string($body) || strlen($body) > $maxBytes) {
        return '';
    }
    return $body;
}

function audio_match_clean_query($text)
{
    $text = trim((string) $text);
    $text = preg_replace('/[\[\]\(\)（）【】].*?[\]\)）】]/u', '', $text);
    $text = preg_replace('/\b(official|lyrics?|audio|video|mv|live|remix|cover)\b/i', '', $text);
    return trim(preg_replace('/\s+/u', ' ', $text));
}

function audio_match_norm($text)
{
    $text = mb_strtolower(trim((string) $text), 'UTF-8');
    $text = strtr($text, [
        '雲' => '云', '華' => '华', '張' => '张', '傑' => '杰', '陳' => '陈', '劉' => '刘',
        '黃' => '黄', '鄭' => '郑', '謝' => '谢', '蕭' => '萧', '羅' => '罗', '蘇' => '苏',
        '吳' => '吴', '許' => '许', '葉' => '叶', '楊' => '杨', '趙' => '赵', '錢' => '钱',
        '鄧' => '邓', '馮' => '冯', '韓' => '韩', '鐘' => '钟', '鍾' => '钟', '偉' => '伟',
        '鋒' => '锋', '東' => '东', '倫' => '伦', '穎' => '颖', '潔' => '洁', '靜' => '静',
        '瑩' => '莹', '詩' => '诗', '語' => '语', '愛' => '爱', '戀' => '恋', '夢' => '梦',
        '煙' => '烟', '塵' => '尘', '裡' => '里', '裏' => '里', '為' => '为', '這' => '这',
        '個' => '个', '們' => '们', '臺' => '台', '颱' => '台', '週' => '周',
    ]);
    return preg_replace('/[\s\p{P}\p{S}]+/u', '', $text);
}

function audio_match_lrclib($title, $artist)
{
    $title = audio_match_clean_query($title);
    $artist = audio_match_clean_query($artist);
    if ($title === '') { return ['lyrics' => '', 'title' => '', 'artist' => '']; }
    $attempts = [];
    if ($artist !== '' && $artist !== '未知歌手') {
        $attempts[] = ['get', ['track_name' => $title, 'artist_name' => $artist]];
    }
    $attempts[] = ['search', ['track_name' => $title, 'artist_name' => $artist, 'limit' => 5]];
    $attempts[] = ['search', ['q' => trim($title . ' ' . $artist), 'limit' => 5]];
    $best = null;
    $bestScore = -1;
    foreach ($attempts as $attempt) {
        $endpoint = $attempt[0] === 'get' ? 'https://lrclib.net/api/get' : 'https://lrclib.net/api/search';
        $url = $endpoint . '?' . http_build_query($attempt[1]);
        list($code, $data) = audio_match_http_json($url, 8);
        if (!is_array($data)) { continue; }
        $items = $attempt[0] === 'get' ? [$data] : $data;
        foreach ($items as $item) {
            if (!is_array($item)) { continue; }
            $lyrics = trim((string) ($item['syncedLyrics'] ?? ''));
            if ($lyrics === '') { $lyrics = trim((string) ($item['plainLyrics'] ?? '')); }
            if ($lyrics === '') { continue; }
            $trackName = (string) ($item['trackName'] ?? ($item['name'] ?? ''));
            $artistName = (string) ($item['artistName'] ?? '');
            $score = 0;
            if (audio_match_norm($trackName) === audio_match_norm($title)) { $score += 4; }
            elseif (audio_match_norm($trackName) !== '' && strpos(audio_match_norm($trackName), audio_match_norm($title)) !== false) { $score += 2; }
            if ($artist !== '' && $artist !== '未知歌手' && audio_match_norm($artistName) !== '' && strpos(audio_match_norm($artistName), audio_match_norm($artist)) !== false) { $score += 3; }
            if ($score > $bestScore) {
                $bestScore = $score;
                $best = ['lyrics' => $lyrics, 'title' => $trackName, 'artist' => $artistName];
            }
        }
    }
    return $best ?: ['lyrics' => '', 'title' => '', 'artist' => ''];
}

function audio_match_itunes_cover($title, $artist)
{
    $title = audio_match_clean_query($title);
    $artist = audio_match_clean_query($artist);
    if ($title === '') { return ''; }
    $queries = [];
    if ($artist !== '' && $artist !== '未知歌手') { $queries[] = $title . ' ' . $artist; }
    $queries[] = $title;
    $bestUrl = '';
    $bestScore = 0;
    foreach ($queries as $term) {
        $url = 'https://itunes.apple.com/search?' . http_build_query([
            'term' => $term, 'media' => 'music', 'entity' => 'song', 'limit' => 10,
        ]);
        list($code, $data) = audio_match_http_json($url, 8);
        if (!is_array($data) || empty($data['results']) || !is_array($data['results'])) { continue; }
        foreach ($data['results'] as $item) {
            if (!is_array($item) || empty($item['artworkUrl100'])) { continue; }
            $track = (string) ($item['trackName'] ?? '');
            $singer = (string) ($item['artistName'] ?? '');
            $score = 0;
            if (audio_match_norm($track) === audio_match_norm($title)) { $score += 4; }
            elseif (audio_match_norm($track) !== '' && strpos(audio_match_norm($track), audio_match_norm($title)) !== false) { $score += 2; }
            if ($artist !== '' && $artist !== '未知歌手' && audio_match_norm($singer) !== '' && strpos(audio_match_norm($singer), audio_match_norm($artist)) !== false) { $score += 3; }
            if ($score > $bestScore) {
                $bestScore = $score;
                $bestUrl = (string) $item['artworkUrl100'];
            }
        }
        if ($bestScore >= 4) { break; }
    }
    if ($bestUrl === '') { return ''; }
    $bestUrl = preg_replace('/\/\d+x\d+bb\.(jpg|png)$/i', '/600x600bb.$1', $bestUrl);
    $data = audio_match_http_binary($bestUrl, 8, 3145728);
    return audio_cover_info($data) ? $data : '';
}

function audio_match_online($title, $artist, $platform = 'all', $mode = 'exact')
{
    $platform = audio_match_platform_key($platform);
    $mode = $mode === 'fuzzy' ? 'fuzzy' : 'exact';
    $items = audio_match_search($title, $artist, 30, $platform);
    $pick = null;
    $matched = 'none';
    $nt = audio_match_norm($title);
    $na = audio_match_norm($artist);
    foreach ($items as $item) {
        if ($nt === '' || audio_match_norm((string) ($item['title'] ?? '')) !== $nt) { continue; }
        if ($na !== '' && $na !== '未知歌手' && audio_match_norm((string) ($item['artist'] ?? '')) !== $na) { continue; }
        $pick = $item;
        $matched = 'exact';
        break;
    }
    // 文件名常把「歌手 - 歌曲」解析成相反顺序，首轮没命中时交换歌名和歌手再搜一次。
    if (!$pick && $artist !== '' && $title !== '') {
        $swapItems = audio_match_search($artist, $title, 30, $platform);
        $swapNt = audio_match_norm($artist);
        $swapNa = audio_match_norm($title);
        foreach ($swapItems as $item) {
            if (audio_match_norm((string) ($item['title'] ?? '')) !== $swapNt) { continue; }
            if ($swapNa !== '' && audio_match_norm((string) ($item['artist'] ?? '')) !== $swapNa) { continue; }
            $pick = $item;
            $matched = 'exact';
            break;
        }
    }
    if (!$pick && $mode === 'fuzzy' && $items) {
        $pick = $items[0];
        $matched = 'fuzzy';
    }
    $coverData = '';
    if ($pick) {
        $coverUrl = trim((string) ($pick['cover_url'] ?? ''));
        if ($coverUrl !== '' && audio_match_cover_url_allowed($coverUrl)) {
            $coverData = audio_match_http_binary($coverUrl, 8, 3145728);
        }
    }
    return [
        'lyrics' => (string) ($pick['lyrics'] ?? ''),
        'lyrics_title' => (string) ($pick['title'] ?? ''),
        'lyrics_artist' => (string) ($pick['artist'] ?? ''),
        'cover_data' => (string) $coverData,
        'matched' => $matched,
        'platform' => $platform,
        'platform_label' => audio_match_platforms()[$platform] ?? '全部',
    ];
}

function audio_match_cover_url_allowed($url)
{
    $host = strtolower((string) parse_url((string) $url, PHP_URL_HOST));
    if ($host === '') { return false; }
    return $host === 'itunes.apple.com' || $host === 'mzstatic.com' || substr($host, -13) === '.mzstatic.com'
        || $host === 'music.126.net' || substr($host, -14) === '.music.126.net'
        || $host === 'y.gtimg.cn' || substr($host, -9) === '.gtimg.cn'
        || $host === 'imge.kugou.com' || substr($host, -10) === '.kugou.com'
        || $host === 'img1.kuwo.cn' || substr($host, -8) === '.kuwo.cn';
}

/** 手动搜索候选：合并 LRCLIB 歌词与 iTunes 封面，返回可选择的歌曲条目。 */
function audio_match_http_json_many(array $requests, $timeout = 7)
{
    $out = [];
    if (!$requests) { return $out; }
    if (!function_exists('curl_multi_init')) {
        foreach ($requests as $key => $url) {
            $out[$key] = audio_match_http_json((string) $url, $timeout);
        }
        return $out;
    }
    $mh = curl_multi_init();
    $handles = [];
    foreach ($requests as $key => $url) {
        $url = (string) $url;
        if (!preg_match('#^https?://#i', $url)) {
            $out[$key] = [0, null];
            continue;
        }
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => 'Komorebi-Audio-Match/1.0',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_HTTPHEADER => ['Accept: application/json'],
        ]);
        curl_multi_add_handle($mh, $ch);
        $handles[$key] = $ch;
    }
    $running = null;
    do {
        $status = curl_multi_exec($mh, $running);
        if ($running) {
            if (curl_multi_select($mh, 1.0) === -1) { usleep(100000); }
        }
    } while ($running && $status === CURLM_OK);
    foreach ($handles as $key => $ch) {
        $body = curl_multi_getcontent($ch);
        $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $out[$key] = [$code, is_string($body) ? json_decode($body, true) : null];
        curl_multi_remove_handle($mh, $ch);
        curl_close($ch);
    }
    curl_multi_close($mh);
    return $out;
}

function audio_match_score($title, $artist, $track, $singer)
{
    $nt = audio_match_norm($title);
    $na = audio_match_norm($artist);
    $ntr = audio_match_norm($track);
    $ns = audio_match_norm($singer);
    $score = 0;
    if ($nt !== '' && $ntr !== '') {
        if ($nt === $ntr) { $score += 10; }
        elseif (mb_strlen($nt, 'UTF-8') >= 2 && mb_strpos($ntr, $nt) !== false) { $score += 6; }
        elseif (mb_strlen($ntr, 'UTF-8') >= 2 && mb_strpos($nt, $ntr) !== false) { $score += 5; }
    }
    if ($na !== '' && $na !== '未知歌手' && $ns !== '') {
        if ($na === $ns) { $score += 7; }
        elseif (mb_strlen($na, 'UTF-8') >= 2 && mb_strpos($ns, $na) !== false) { $score += 5; }
        elseif (mb_strlen($ns, 'UTF-8') >= 2 && mb_strpos($na, $ns) !== false) { $score += 3; }
    }
    return $score;
}

function audio_match_label($title, $artist, $track, $singer)
{
    $nt = audio_match_norm($title);
    $na = audio_match_norm($artist);
    $ntr = audio_match_norm($track);
    $ns = audio_match_norm($singer);
    $titleExact = ($nt !== '' && $nt === $ntr);
    $titleNear = (!$titleExact && $nt !== '' && $ntr !== ''
        && (mb_strpos($ntr, $nt) !== false || mb_strpos($nt, $ntr) !== false));
    $artistHit = ($na !== '' && $na !== '未知歌手' && $ns !== '' && mb_strpos($ns, $na) !== false);
    if ($titleExact && $artistHit) { return '精确匹配'; }
    if ($titleExact) { return '同名歌曲'; }
    if ($titleNear && $artistHit) { return '歌名近似'; }
    if ($titleNear) { return '相关歌名'; }
    if ($artistHit) { return '同歌手'; }
    return '相关推荐';
}


function audio_match_platforms()
{
    return [
        'all' => '全部',
        'netease' => '网易云音乐',
        'qq' => 'QQ音乐',
        'kugou' => '酷狗音乐',
        'kuwo' => '酷我音乐',
    ];
}

function audio_match_platform_key($platform)
{
    $platform = strtolower(trim((string) $platform));
    return array_key_exists($platform, audio_match_platforms()) ? $platform : 'all';
}

function audio_match_html_text($text)
{
    $text = html_entity_decode((string) $text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = str_replace(['\\u0026', '&nbsp;', '\\n', '\\r'], [' & ', ' ', ' ', ' '], $text);
    return trim(preg_replace('/\s+/u', ' ', $text));
}

function audio_match_qq_search($title, $artist, $limit = 20)
{
    $term = trim($title . ' ' . ($artist !== '' && $artist !== '未知歌手' ? $artist : ''));
    if ($term === '') { return []; }
    $url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?' . http_build_query([
        'p' => 1, 'n' => max(1, min(30, (int) $limit)), 'w' => $term, 'format' => 'json',
    ]);
    list($code, $data) = audio_match_http_json($url, 8);
    $list = $data['data']['song']['list'] ?? [];
    if (!is_array($list)) { return []; }
    $rows = [];
    foreach ($list as $item) {
        if (!is_array($item) || empty($item['songname'])) { continue; }
        $track = audio_match_html_text($item['songname']);
        $singers = [];
        if (!empty($item['singer']) && is_array($item['singer'])) {
            foreach ($item['singer'] as $singer) {
                if (!empty($singer['name'])) { $singers[] = audio_match_html_text($singer['name']); }
            }
        }
        $singer = implode(' / ', $singers);
        $score = audio_match_score($title, $artist, $track, $singer);
        if ($score <= 0) { continue; }
        $albumMid = preg_replace('/[^0-9A-Za-z]/', '', (string) ($item['albummid'] ?? ''));
        $cover = $albumMid !== '' ? 'https://y.gtimg.cn/music/photo_new/T002R500x500M000' . $albumMid . '.jpg' : '';
        $rows[] = [
            'title' => $track,
            'artist' => $singer,
            'album' => audio_match_html_text($item['albumname'] ?? ''),
            'year' => '',
            'cover_url' => $cover,
            'songmid' => preg_replace('/[^0-9A-Za-z]/', '', (string) ($item['songmid'] ?? '')),
            'score' => $score,
        ];
    }
    usort($rows, function ($a, $b) { return (int) $b['score'] <=> (int) $a['score']; });
    return array_slice($rows, 0, max(1, min(30, (int) $limit)));
}

function audio_match_qq_lyrics($songmid)
{
    $songmid = preg_replace('/[^0-9A-Za-z]/', '', (string) $songmid);
    if ($songmid === '') { return ''; }
    $url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?' . http_build_query([
        'songmid' => $songmid, 'format' => 'json', 'nobase64' => 1,
    ]);
    list($code, $data) = audio_match_http_json($url, 8, ['Referer: https://y.qq.com/']);
    $lyric = (string) ($data['lyric'] ?? '');
    $lyric = html_entity_decode($lyric, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $lyric = str_replace(['\\n', '\\r'], ["\n", ''], $lyric);
    $lyric = trim(str_replace("\r\n", "\n", $lyric));
    return strpos($lyric, '[') !== false ? $lyric : '';
}

function audio_match_qq_items($title, $artist, $limit = 20, $deep = true)
{
    $rows = audio_match_qq_search($title, $artist, $limit);
    if (!$rows) { return []; }
    $lyrics = [];
    if ($deep) {
        foreach (array_slice($rows, 0, 6) as $i => $row) {
            if (empty($row['songmid'])) { continue; }
            $lyric = audio_match_qq_lyrics((string) $row['songmid']);
            if ($lyric !== '') { $lyrics[$i] = $lyric; }
        }
    }
    $items = [];
    foreach ($rows as $i => $row) {
        $cover = $row['cover_url'];
        if ($cover !== '' && !audio_match_cover_url_allowed($cover)) { $cover = ''; }
        $items[] = [
            'title' => $row['title'],
            'artist' => $row['artist'],
            'album' => $row['album'],
            'year' => $row['year'],
            'cover_url' => $cover,
            'cover_label' => $cover !== '' ? '500×500' : '无封面',
            'has_lyrics' => !empty($lyrics[$i]),
            'lyrics' => !empty($lyrics[$i]) ? $lyrics[$i] : '',
            'score' => $row['score'],
            'source' => 'qq',
            'source_label' => 'QQ音乐',
            'match_label' => audio_match_label($title, $artist, $row['title'], $row['artist']),
        ];
    }
    return $items;
}

function audio_match_kugou_search($title, $artist, $limit = 20)
{
    $term = trim($title . ' ' . ($artist !== '' && $artist !== '未知歌手' ? $artist : ''));
    if ($term === '') { return []; }
    $url = 'http://mobilecdn.kugou.com/api/v3/search/song?' . http_build_query([
        'format' => 'json', 'keyword' => $term, 'page' => 1,
        'pagesize' => max(1, min(30, (int) $limit)), 'showtype' => 1,
    ]);
    list($code, $data) = audio_match_http_json($url, 8);
    $list = $data['data']['info'] ?? [];
    if (!is_array($list)) { return []; }
    $rows = [];
    foreach ($list as $item) {
        if (!is_array($item) || empty($item['songname'])) { continue; }
        $track = audio_match_html_text($item['songname']);
        $singer = audio_match_html_text($item['singername'] ?? '');
        $score = audio_match_score($title, $artist, $track, $singer);
        if ($score <= 0) { continue; }
        $rows[] = [
            'title' => $track,
            'artist' => $singer,
            'album' => audio_match_html_text($item['album_name'] ?? ''),
            'year' => '',
            'cover_url' => '',
            'hash' => (string) ($item['hash'] ?? ''),
            'duration' => (int) ($item['duration'] ?? 0),
            'score' => $score,
        ];
    }
    usort($rows, function ($a, $b) { return (int) $b['score'] <=> (int) $a['score']; });
    return array_slice($rows, 0, max(1, min(30, (int) $limit)));
}

function audio_match_kugou_lyrics($hash, $title, $artist, $duration = 0)
{
    $hash = preg_replace('/[^0-9a-f]/i', '', (string) $hash);
    if ($hash === '') { return ''; }
    $term = trim($title . ' ' . $artist);
    $url = 'https://krcs.kugou.com/search?' . http_build_query([
        'ver' => 1, 'man' => 'yes', 'client' => 'mobi', 'keyword' => $term,
        'duration' => $duration ? (string) $duration : '', 'hash' => $hash,
    ]);
    list($code, $data) = audio_match_http_json($url, 8);
    $candidate = $data['candidates'][0] ?? null;
    if (!is_array($candidate) || empty($candidate['id']) || empty($candidate['accesskey'])) { return ''; }
    $download = 'https://krcs.kugou.com/download?' . http_build_query([
        'ver' => 1, 'client' => 'mobi', 'id' => (string) $candidate['id'],
        'accesskey' => (string) $candidate['accesskey'], 'fmt' => 'lrc', 'charset' => 'utf8',
    ]);
    list($code, $data) = audio_match_http_json($download, 8);
    $content = trim((string) ($data['content'] ?? ''));
    if ($content === '') { return ''; }
    $decoded = base64_decode($content, true);
    if (!is_string($decoded) || $decoded === '') { return ''; }
    $decoded = preg_replace('/^\xEF\xBB\xBF/', '', $decoded);
    return strpos($decoded, '[') !== false ? trim($decoded) : '';
}

function audio_match_kuwo_search($title, $artist, $limit = 20)
{
    $term = trim($title . ' ' . ($artist !== '' && $artist !== '未知歌手' ? $artist : ''));
    if ($term === '') { return []; }
    $url = 'https://search.kuwo.cn/r.s?' . http_build_query([
        'all' => $term, 'ft' => 'music', 'itemset' => 'web_2013', 'client' => 'kt',
        'pn' => 0, 'rn' => max(1, min(30, (int) $limit)), 'rformat' => 'json', 'encoding' => 'utf8',
    ]);
    $raw = audio_match_http_raw($url, 8);
    if ($raw === '') { return []; }
    $data = json_decode(str_replace("'", '"', $raw), true);
    if (!is_array($data) || empty($data['abslist']) || !is_array($data['abslist'])) { return []; }
    $rows = [];
    foreach ($data['abslist'] as $item) {
        if (!is_array($item) || empty($item['NAME'])) { continue; }
        $track = audio_match_html_text($item['NAME']);
        $singer = audio_match_html_text($item['ARTIST'] ?? '');
        $score = audio_match_score($title, $artist, $track, $singer);
        if ($score <= 0) { continue; }
        $pic = trim((string) ($item['web_albumpic_short'] ?? ''));
        $cover = $pic !== '' ? 'https://img1.kuwo.cn/star/albumcover/500/' . preg_replace('#^120/#', '', $pic) : '';
        $rows[] = [
            'title' => $track,
            'artist' => $singer,
            'album' => audio_match_html_text($item['ALBUM'] ?? ''),
            'year' => '',
            'cover_url' => $cover,
            'music_id' => (string) ($item['DC_TARGETID'] ?? ''),
            'score' => $score,
        ];
    }
    usort($rows, function ($a, $b) { return (int) $b['score'] <=> (int) $a['score']; });
    return array_slice($rows, 0, max(1, min(30, (int) $limit)));
}

function audio_match_provider_item($title, $artist, $row, $source, $sourceLabel, $lyrics = '', $cover = '')
{
    return [
        'title' => $row['title'], 'artist' => $row['artist'], 'album' => $row['album'] ?? '',
        'year' => $row['year'] ?? '', 'cover_url' => $cover !== '' ? $cover : ($row['cover_url'] ?? ''),
        'cover_label' => ($cover !== '' || !empty($row['cover_url'])) ? '500×500' : '无封面',
        'has_lyrics' => $lyrics !== '', 'lyrics' => $lyrics,
        'score' => $row['score'], 'source' => $source, 'source_label' => $sourceLabel,
        'match_label' => audio_match_label($title, $artist, $row['title'], $row['artist']),
    ];
}

function audio_match_kugou_items($title, $artist, $limit = 20, $deep = true)
{
    $rows = audio_match_kugou_search($title, $artist, $limit);
    if (!$rows) { return []; }
    $qqRows = audio_match_qq_search($title, $artist, 10);
    $lyrics = [];
    if ($deep) {
        foreach (array_slice($rows, 0, 4) as $i => $row) {
            $lyric = audio_match_kugou_lyrics((string) $row['hash'], $row['title'], $row['artist'], (int) $row['duration']);
            if ($lyric === '') {
                foreach ($qqRows as $qq) {
                    if (audio_match_norm($qq['title']) === audio_match_norm($row['title'])) {
                        $lyric = audio_match_qq_lyrics((string) $qq['songmid']); break;
                    }
                }
            }
            if ($lyric !== '') { $lyrics[$i] = $lyric; }
        }
    }
    $items = [];
    foreach ($rows as $i => $row) {
        $cover = '';
        foreach ($qqRows as $qq) {
            if (audio_match_norm($qq['title']) === audio_match_norm($row['title'])) {
                $cover = (string) $qq['cover_url']; break;
            }
        }
        $items[] = audio_match_provider_item($title, $artist, $row, 'kugou', '酷狗音乐', $lyrics[$i] ?? '', $cover);
    }
    return $items;
}

function audio_match_kuwo_items($title, $artist, $limit = 20, $deep = true)
{
    $rows = audio_match_kuwo_search($title, $artist, $limit);
    if (!$rows) { return []; }
    $qqRows = audio_match_qq_search($title, $artist, 10);
    $lyrics = [];
    if ($deep) {
        foreach (array_slice($rows, 0, 4) as $i => $row) {
            foreach ($qqRows as $qq) {
                if (audio_match_norm($qq['title']) === audio_match_norm($row['title'])) {
                    $lyrics[$i] = audio_match_qq_lyrics((string) $qq['songmid']); break;
                }
            }
        }
    }
    $items = [];
    foreach ($rows as $i => $row) {
        $cover = (string) $row['cover_url'];
        if ($cover === '' || !audio_match_cover_url_allowed($cover)) {
            foreach ($qqRows as $qq) {
                if (audio_match_norm($qq['title']) === audio_match_norm($row['title'])) { $cover = (string) $qq['cover_url']; break; }
            }
        }
        $items[] = audio_match_provider_item($title, $artist, $row, 'kuwo', '酷我音乐', $lyrics[$i] ?? '', $cover);
    }
    return $items;
}

function audio_match_netease_items($title, $artist, $limit = 20)
{
    $term = trim($title . ' ' . ($artist !== '' && $artist !== '未知歌手' ? $artist : ''));
    if ($term === '') { return []; }
    $url = 'https://music.163.com/api/search/get/web?' . http_build_query([
        'csrf_token' => '', 's' => $term, 'type' => 1, 'offset' => 0, 'total' => 'true', 'limit' => max(1, min(25, (int) $limit)),
    ]);
    list($code, $data) = audio_match_http_json($url, 8);
    $songs = $data['result']['songs'] ?? [];
    if (!is_array($songs)) { return []; }
    $rows = [];
    foreach ($songs as $item) {
        if (!is_array($item) || empty($item['id']) || empty($item['name'])) { continue; }
        $track = audio_match_html_text($item['name']);
        $names = [];
        foreach (($item['artists'] ?? []) as $a) {
            if (!empty($a['name'])) { $names[] = audio_match_html_text($a['name']); }
        }
        $singer = implode(' / ', $names);
        $score = audio_match_score($title, $artist, $track, $singer);
        if ($score <= 0) { continue; }
        $rows[] = [
            'id' => (int) $item['id'], 'title' => $track, 'artist' => $singer,
            'album' => audio_match_html_text($item['album']['name'] ?? ''),
            'year' => !empty($item['album']['publishTime']) ? date('Y', (int) round(((int) $item['album']['publishTime']) / 1000)) : '',
            'score' => $score,
        ];
    }
    usort($rows, function ($a, $b) { return (int) $b['score'] <=> (int) $a['score']; });
    $rows = array_slice($rows, 0, $limit);
    if (!$rows) { return []; }
    $ids = [];
    foreach (array_slice($rows, 0, 8) as $row) { $ids[] = (int) $row['id']; }
    $fetch = [
        'detail' => 'https://music.163.com/api/song/detail?' . http_build_query(['ids' => '[' . implode(',', $ids) . ']']),
    ];
    foreach ($ids as $id) {
        $fetch['lrc_' . $id] = 'https://music.163.com/api/song/lyric?' . http_build_query(['id' => $id, 'lv' => 1, 'kv' => 1, 'tv' => -1]);
    }
    $responses = audio_match_http_json_many($fetch, 6);
    $covers = [];
    $lyrics = [];
    foreach (($responses['detail'][1]['songs'] ?? []) as $song) {
        if (empty($song['id']) || empty($song['album']['picUrl'])) { continue; }
        $cover = (string) $song['album']['picUrl'];
        if (audio_match_cover_url_allowed($cover)) {
            $covers[(int) $song['id']] = preg_replace('/\/\d+x\d+bb\.(jpg|png)$/i', '/600x600bb.$1', $cover);
        }
    }
    foreach ($responses as $key => $response) {
        if (strpos((string) $key, 'lrc_') !== 0) { continue; }
        $lyric = trim((string) ($response[1]['lrc']['lyric'] ?? ''));
        if ($lyric !== '' && strpos($lyric, '[') !== false) { $lyrics[(int) substr((string) $key, 4)] = $lyric; }
    }
    $items = [];
    foreach ($rows as $row) {
        $cover = $covers[$row['id']] ?? '';
        $items[] = audio_match_provider_item($title, $artist, $row, 'netease', '网易云音乐', $lyrics[$row['id']] ?? '', $cover);
    }
    return $items;
}

function audio_match_provider_items($platform, $title, $artist, $limit = 20, $deep = true)
{
    $platform = audio_match_platform_key($platform);
    if ($platform === 'qq') { return audio_match_qq_items($title, $artist, $limit, $deep); }
    if ($platform === 'kugou') { return audio_match_kugou_items($title, $artist, $limit, $deep); }
    if ($platform === 'kuwo') { return audio_match_kuwo_items($title, $artist, $limit, $deep); }
    if ($platform === 'netease') { return audio_match_netease_items($title, $artist, $limit, $deep); }
    return [];
}

function audio_match_search($title, $artist, $limit = 20, $platform = 'all')
{
    $title = audio_match_clean_query($title);
    $artist = audio_match_clean_query($artist);
    if ($title === '') { return []; }
    $limit = max(1, min(30, (int) $limit));
    $platform = audio_match_platform_key($platform);
    if ($platform !== 'all') {
        return array_slice(audio_match_provider_items($platform, $title, $artist, $limit), 0, $limit);
    }

    $requests = [];
    $lr = 'https://lrclib.net/api/search?';
    $it = 'https://itunes.apple.com/search?';
    if ($artist !== '' && $artist !== '未知歌手') {
        $requests['lr_exact'] = $lr . http_build_query(['track_name' => $title, 'artist_name' => $artist, 'limit' => 25]);
    }
    $requests['lr_title'] = $lr . http_build_query(['track_name' => $title, 'limit' => 25]);
    if ($artist !== '' && $artist !== '未知歌手') {
        $requests['lr_q'] = $lr . http_build_query(['q' => trim($title . ' ' . $artist), 'limit' => 25]);
        $requests['lr_artist'] = $lr . http_build_query(['q' => $artist, 'limit' => 25]);
        $requests['it_ta'] = $it . http_build_query(['term' => $title . ' ' . $artist, 'media' => 'music', 'entity' => 'song', 'limit' => 30]);
        $requests['it_artist'] = $it . http_build_query(['term' => $artist, 'media' => 'music', 'entity' => 'song', 'limit' => 30, 'attribute' => 'artistTerm']);
    }
    $requests['it_title'] = $it . http_build_query(['term' => $title, 'media' => 'music', 'entity' => 'song', 'limit' => 30]);
    $neTerm = trim($title . ' ' . ($artist !== '' && $artist !== '未知歌手' ? $artist : ''));
    $requests['ne_search'] = 'https://music.163.com/api/search/get/web?csrf_token=&s=' . urlencode($neTerm)
        . '&type=1&offset=0&total=true&limit=20';
    $responses = audio_match_http_json_many($requests, 7);

    $lyricsRows = [];
    $neRows = [];
    $coverRows = [];
    foreach ($responses as $key => $response) {
        if (strpos((string) $key, 'lr_') !== 0) { continue; }
        list($code, $data) = $response;
        if (!is_array($data)) { continue; }
        foreach ($data as $item) {
            if (!is_array($item)) { continue; }
            $lyrics = trim((string) ($item['syncedLyrics'] ?? ''));
            if ($lyrics === '') { $lyrics = trim((string) ($item['plainLyrics'] ?? '')); }
            if ($lyrics === '') { continue; }
            $track = trim((string) ($item['trackName'] ?? ''));
            $singer = trim((string) ($item['artistName'] ?? ''));
            if ($track === '') { continue; }
            $score = audio_match_score($title, $artist, $track, $singer);
            if ($score <= 0) { continue; }
            $rowKey = audio_match_norm($track) . '|' . audio_match_norm($singer);
            if (isset($lyricsRows[$rowKey]) && $lyricsRows[$rowKey]['score'] >= $score) { continue; }
            $lyricsRows[$rowKey] = [
                'title' => $track,
                'artist' => $singer,
                'album' => trim((string) ($item['albumName'] ?? '')),
                'year' => substr(trim((string) ($item['releaseDate'] ?? '')), 0, 4),
                'lyrics' => $lyrics,
                'score' => $score,
                'source' => 'lrclib',
            ];
        }
    }

    foreach ($responses as $key => $response) {
        if (strpos((string) $key, 'ne_') !== 0) { continue; }
        list($code, $data) = $response;
        if (!is_array($data) || empty($data['result']['songs']) || !is_array($data['result']['songs'])) { continue; }
        foreach ($data['result']['songs'] as $item) {
            if (!is_array($item) || empty($item['id']) || empty($item['name'])) { continue; }
            $track = trim((string) $item['name']);
            $singer = '';
            if (!empty($item['artists']) && is_array($item['artists'])) {
                $names = [];
                foreach ($item['artists'] as $a) { if (!empty($a['name'])) { $names[] = trim((string) $a['name']); } }
                $singer = implode(' / ', $names);
            }
            $score = audio_match_score($title, $artist, $track, $singer);
            if ($score <= 0) { continue; }
            $neRows[] = [
                'id' => (int) $item['id'],
                'title' => $track,
                'artist' => $singer,
                'album' => trim((string) ($item['album']['name'] ?? '')),
                'year' => !empty($item['album']['publishTime']) ? date('Y', (int) round(((int) $item['album']['publishTime']) / 1000)) : '',
                'score' => $score,
            ];
        }
    }
    $hasExactLyrics = false;
    $ntQuery = audio_match_norm($title);
    $naQuery = audio_match_norm($artist);
    foreach ($lyricsRows as $row) {
        $titleHit = $ntQuery !== '' && audio_match_norm($row['title']) === $ntQuery;
        $artistHit = ($naQuery === '' || $naQuery === '未知歌手')
            ? true : (audio_match_norm($row['artist']) === $naQuery);
        if ($titleHit && $artistHit) { $hasExactLyrics = true; break; }
    }
    if (!$hasExactLyrics && $neRows) {
        usort($neRows, function ($a, $b) { return (int) $b['score'] <=> (int) $a['score']; });
        $topNeRows = array_slice($neRows, 0, 6);
        $neFetch = [];
        $ids = [];
        foreach ($topNeRows as $row) {
            $ids[] = (int) $row['id'];
            $neFetch['ne_lrc_' . $row['id']] = 'https://music.163.com/api/song/lyric?id=' . $row['id'] . '&lv=1&kv=1&tv=-1';
        }
        $neFetch['ne_detail'] = 'https://music.163.com/api/song/detail?'
            . http_build_query(['ids' => '[' . implode(',', $ids) . ']']);
        $neResponses = audio_match_http_json_many($neFetch, 5);
        $neCovers = [];
        list($code, $detail) = $neResponses['ne_detail'] ?? [0, null];
        if (is_array($detail) && !empty($detail['songs']) && is_array($detail['songs'])) {
            foreach ($detail['songs'] as $song) {
                if (empty($song['id']) || empty($song['album']['picUrl'])) { continue; }
                $cover = (string) $song['album']['picUrl'];
                if (audio_match_cover_url_allowed($cover)) {
                    $neCovers[(int) $song['id']] = preg_replace('/\/\d+x\d+bb\.(jpg|png)$/i', '/600x600bb.$1', $cover);
                }
            }
        }
        foreach ($neResponses as $key => $response) {
            if (strpos((string) $key, 'ne_lrc_') !== 0) { continue; }
            list($code, $data) = $response;
            if (!is_array($data) || empty($data['lrc']['lyric'])) { continue; }
            $id = (int) substr((string) $key, 7);
            foreach ($topNeRows as $row) {
                if ($row['id'] !== $id) { continue; }
                $lyric = trim((string) $data['lrc']['lyric']);
                if ($lyric === '' || strpos($lyric, '[') === false) { break; }
                $rowKey = audio_match_norm($row['title']) . '|' . audio_match_norm($row['artist']);
                if (isset($lyricsRows[$rowKey]) && $lyricsRows[$rowKey]['score'] >= $row['score']) { break; }
                $lyricsRows[$rowKey] = [
                    'title' => $row['title'],
                    'artist' => $row['artist'],
                    'album' => $row['album'],
                    'year' => $row['year'],
                    'lyrics' => $lyric,
                    'score' => $row['score'] + 2,
                    'source' => 'netease',
                ];
                break;
            }
        }
        foreach ($topNeRows as $row) {
            if (empty($neCovers[$row['id']])) { continue; }
            $coverRow = [
                'title' => $row['title'],
                'artist' => $row['artist'],
                'album' => $row['album'],
                'year' => $row['year'],
                'cover_url' => $neCovers[$row['id']],
                'score' => $row['score'],
                'source' => 'netease',
            ];
            $rowKey = audio_match_norm($row['title']) . '|' . audio_match_norm($row['artist']);
            if (!isset($coverRows[$rowKey]) || $coverRows[$rowKey]['score'] < $coverRow['score']) {
                $coverRows[$rowKey] = $coverRow;
            }
        }
    }

    foreach ($responses as $key => $response) {
        if (strpos((string) $key, 'it_') !== 0) { continue; }
        list($code, $data) = $response;
        if (!is_array($data) || empty($data['results']) || !is_array($data['results'])) { continue; }
        foreach ($data['results'] as $item) {
            if (!is_array($item) || empty($item['artworkUrl100']) || empty($item['trackName'])) { continue; }
            $track = trim((string) $item['trackName']);
            $singer = trim((string) ($item['artistName'] ?? ''));
            $score = audio_match_score($title, $artist, $track, $singer);
            if ($score <= 0) { continue; }
            $cover = preg_replace('/\/\d+x\d+bb\.(jpg|png)$/i', '/600x600bb.$1', (string) $item['artworkUrl100']);
            if (!audio_match_cover_url_allowed($cover)) { continue; }
            $rowKey = audio_match_norm($track) . '|' . audio_match_norm($singer);
            if (isset($coverRows[$rowKey]) && $coverRows[$rowKey]['score'] >= $score) { continue; }
            $coverRows[$rowKey] = [
                'title' => $track,
                'artist' => $singer,
                'album' => trim((string) ($item['collectionName'] ?? '')),
                'year' => substr(trim((string) ($item['releaseDate'] ?? '')), 0, 4),
                'cover_url' => $cover,
                'score' => $score,
                'source' => 'itunes',
            ];
        }
    }

    $coverByTitle = [];
    foreach ($coverRows as $row) {
        $titleKey = audio_match_norm($row['title']);
        if (!isset($coverByTitle[$titleKey]) || $coverByTitle[$titleKey]['score'] < $row['score']) {
            $coverByTitle[$titleKey] = $row;
        }
    }

    $items = [];
    foreach ($lyricsRows as $key => $row) {
        $cover = $coverRows[$key] ?? ($coverByTitle[audio_match_norm($row['title'])] ?? null);
        $items[] = [
            'title' => $row['title'],
            'artist' => $row['artist'],
            'album' => $row['album'] !== '' ? $row['album'] : (string) ($cover['album'] ?? ''),
            'year' => $row['year'] !== '' ? $row['year'] : (string) ($cover['year'] ?? ''),
            'cover_url' => (string) ($cover['cover_url'] ?? ''),
            'cover_label' => !empty($cover['cover_url']) ? '600×600' : '无封面',
            'has_lyrics' => true,
            'lyrics' => $row['lyrics'],
            'score' => $row['score'] + 10,
            'source' => (string) ($row['source'] ?? 'lrclib'),
            'source_label' => ($row['source'] ?? 'lrclib') === 'netease' ? '网易云音乐' : '歌词库',
            'match_label' => audio_match_label($title, $artist, $row['title'], $row['artist']),
        ];
    }
    foreach ($coverRows as $key => $row) {
        $exists = false;
        foreach ($items as $item) {
            if (audio_match_norm($item['title']) === audio_match_norm($row['title'])
                && audio_match_norm($item['artist']) === audio_match_norm($row['artist'])) { $exists = true; break; }
        }
        if ($exists) { continue; }
        $items[] = [
            'title' => $row['title'],
            'artist' => $row['artist'],
            'album' => $row['album'],
            'year' => $row['year'],
            'cover_url' => $row['cover_url'],
            'cover_label' => '600×600',
            'has_lyrics' => false,
            'lyrics' => '',
            'score' => $row['score'],
            'source' => (string) ($row['source'] ?? 'itunes'),
            'source_label' => ($row['source'] ?? 'itunes') === 'netease' ? '网易云音乐' : 'iTunes封面',
            'match_label' => audio_match_label($title, $artist, $row['title'], $row['artist']),
        ];
    }
    usort($items, function ($a, $b) {
        if ((int) $a['has_lyrics'] !== (int) $b['has_lyrics']) { return (int) $b['has_lyrics'] <=> (int) $a['has_lyrics']; }
        return (int) $b['score'] <=> (int) $a['score'];
    });
    // 全部模式追加 QQ音乐、酷狗、酷我候选；保留原有歌词库与 iTunes 结果。
    foreach (['qq', 'kugou', 'kuwo'] as $provider) {
        $extra = audio_match_provider_items($provider, $title, $artist, 3, false);
        foreach ($extra as $row) {
            $exists = false;
            foreach ($items as $item) {
                if (audio_match_norm($item['title']) === audio_match_norm($row['title'])
                    && audio_match_norm($item['artist']) === audio_match_norm($row['artist'])) { $exists = true; break; }
            }
            if (!$exists) { $items[] = $row; }
        }
    }
    usort($items, function ($a, $b) {
        if ((int) $a['has_lyrics'] !== (int) $b['has_lyrics']) { return (int) $b['has_lyrics'] <=> (int) $a['has_lyrics']; }
        return (int) $b['score'] <=> (int) $a['score'];
    });
    return array_slice($items, 0, $limit);
}


function audio_playable_url($url)
{
    $url = (string) $url;
    $path = (string) parse_url($url, PHP_URL_PATH);
    $pos = strpos($path, 'uploads/');
    if ($pos === false) {
        return $url;
    }
    $rel = ltrim(substr($path, $pos), '/');
    $ext = strtolower((string) pathinfo($rel, PATHINFO_EXTENSION));
    if (!in_array($ext, ['webm', 'ogg', 'oga', 'opus', 'wav', 'amr', 'aac', 'flac', 'wma', 'mid', 'midi', 'weba'], true)) {
        return $url;
    }
    $candidate = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '.mp3', $rel);
    if (is_file(APP_ROOT . '/' . $candidate)) {
        return full_url($candidate);
    }
    $converted = audio_make_compatible($rel);
    if ($converted) {
        return full_url($converted);
    }
    return $url;
}

function audio_card_clean_html($html)
{
    $html = (string) $html;
    if (trim($html) === '' || !class_exists('DOMDocument')) {
        return $html;
    }
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML('<?xml encoding="UTF-8"><div id="km-audio-clean-root">' . $html . '</div>', LIBXML_NOWARNING | LIBXML_NOERROR);
    libxml_clear_errors();
    $root = $doc->getElementById('km-audio-clean-root');
    if (!$root) {
        return $html;
    }
    $cards = [];
    foreach ($root->getElementsByTagName('div') as $div) {
        if (strpos(' ' . $div->getAttribute('class') . ' ', ' cfc-audio ') !== false) {
            $cards[] = $div;
        }
    }
    foreach ($cards as $card) {
        foreach (['cfc-head', 'cfc-audio-tools'] as $cls) {
            $trash = [];
            foreach ($card->getElementsByTagName('*') as $el) {
                if (strpos(' ' . $el->getAttribute('class') . ' ', ' ' . $cls . ' ') !== false) {
                    $trash[] = $el;
                }
            }
            foreach ($trash as $el) {
                if ($el->parentNode) { $el->parentNode->removeChild($el); }
            }
        }
        $audio = null;
        foreach ($card->getElementsByTagName('audio') as $a) {
            $audio = $a;
            break;
        }
        if ($audio && $card->parentNode) {
            $card->parentNode->insertBefore($audio, $card);
        }
        if ($card->parentNode) { $card->parentNode->removeChild($card); }
    }
    $out = '';
    foreach ($root->childNodes as $child) {
        $out .= $doc->saveHTML($child);
    }
    return $out;
}

function audio_rewrite_html($html)
{
    return preg_replace_callback('~(<audio\b[^>]*\bsrc=")([^"]+)("[^>]*>)~i', function ($m) {
        $rawUrl = html_entity_decode($m[2], ENT_QUOTES, 'UTF-8');
        $tag = $m[1] . e(audio_playable_url($rawUrl)) . $m[3];
        if (stripos($tag, 'data-km-audio') === false) {
            $meta = audio_track_meta($rawUrl);
            $tag = rtrim($tag);
            if (substr($tag, -1) === '>') {
                $tag = substr($tag, 0, -1);
            }
            $caption = rawurldecode(basename((string) parse_url($rawUrl, PHP_URL_PATH)));
            $tag .= ' data-km-audio="1" data-audio-title="' . e($meta['title'])
                . '" data-audio-artist="' . e($meta['artist'])
                . '" data-audio-cover="' . e($meta['cover'])
                . '" data-audio-caption="' . e($caption)
                . '" data-audio-lyrics-b64="' . e(base64_encode((string) ($meta['lyrics'] ?? ''))) . '">';
        }
        if (stripos($tag, 'data-km-audio') !== false && stripos($tag, 'data-km-card-style') === false) {
            $tag = preg_replace('~>\s*$~', ' data-km-card-style="panel">', $tag, 1);
        }
        return $tag;
    }, (string) $html);
}

function video_rewrite_html($html)
{
    return preg_replace_callback('~(<video\b[^>]*\bsrc=")([^"]+)("[^>]*>)~i', function ($m) {
        $rawUrl = html_entity_decode($m[2], ENT_QUOTES, 'UTF-8');
        return $m[1] . e(video_playable_url($rawUrl)) . $m[3];
    }, (string) $html);
}

function media_rewrite_html($html)
{
    return video_rewrite_html(audio_rewrite_html(audio_card_clean_html($html)));
}

function json_out(array $data, $status = 200)
{
    if (!headers_sent()) {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        header('X-Content-Type-Options: nosniff');
    }
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// ---------- HTML 清洗 ----------
function sanitize_html($html)
{
    $html = (string) $html;
    if (trim($html) === '') {
        return '';
    }
    if (!class_exists('DOMDocument')) {
        return sanitize_html_regex($html);
    }
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML('<?xml encoding="UTF-8"><div id="__root">' . $html . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();
    $root = $doc->getElementById('__root');
    if (!$root) {
        return sanitize_html_regex($html);
    }

    $allowed = ['p','br','div','span','strong','b','em','i','u','s','strike','sub','sup','h1','h2','h3','h4','h5','h6',
        'ul','ol','li','blockquote','pre','code','a','img','audio','video','source','table','thead','tbody','tr','td','th','hr','figure','figcaption','font','center','del'];
    $drop = ['script','style','iframe','object','embed','form','input','button','textarea','select','meta','link','base','svg','math'];
    $allowedAttr = ['class','style','href','src','alt','title','width','height','target','rel','colspan','rowspan','align','color','size','face',
        'controls','preload','poster','loop','playsinline','type'];

    $walk = function ($node) use (&$walk, $allowed, $drop, $allowedAttr) {
        if (!$node->hasChildNodes()) {
            return;
        }
        $children = [];
        foreach ($node->childNodes as $c) {
            $children[] = $c;
        }
        foreach ($children as $child) {
            if ($child->nodeType === XML_ELEMENT_NODE) {
                $tag = strtolower($child->nodeName);
                if (in_array($tag, $drop, true)) {
                    $node->removeChild($child);
                    continue;
                }
                if (!in_array($tag, $allowed, true)) {
                    // 未知标签：解包，保留文本内容
                    while ($child->firstChild) {
                        $node->insertBefore($child->firstChild, $child);
                    }
                    $node->removeChild($child);
                    continue;
                }
                if ($child->hasAttributes()) {
                    $remove = [];
                    foreach ($child->attributes as $attr) {
                        $name = strtolower($attr->nodeName);
                        $val = $attr->nodeValue;
                        $audioAttr = (strpos($name, 'data-audio-') === 0 || $name === 'data-km-audio');
                        if (strpos($name, 'on') === 0 || (!in_array($name, $allowedAttr, true) && !$audioAttr)) {
                            $remove[] = $name;
                            continue;
                        }
                        if (in_array($name, ['href', 'src'], true)) {
                            $trim = preg_replace('/\s+/', '', strtolower($val));
                            if (preg_match('/^(javascript|vbscript|data):/i', $trim) && strpos($trim, 'data:image/') !== 0) {
                                $remove[] = $name;
                            }
                        }
                        if ($name === 'style') {
                            if (preg_match('/(expression|javascript:|behavior|@import)/i', $val)) {
                                $remove[] = $name;
                            }
                        }
                    }
                    foreach ($remove as $name) {
                        $child->removeAttribute($name);
                    }
                }
                if ($tag === 'a') {
                    $child->setAttribute('rel', 'noopener noreferrer');
                }
                $walk($child);
            }
        }
    };
    $walk($root);

    $out = '';
    foreach ($root->childNodes as $c) {
        $out .= $doc->saveHTML($c);
    }
    return trim($out);
}

function sanitize_html_regex($html)
{
    $html = preg_replace('#<(script|style|iframe|object|embed|form)[^>]*>.*?</\1>#is', '', $html);
    $html = preg_replace('#<(script|style|iframe|object|embed|form)[^>]*/?>#is', '', $html);
    $html = preg_replace('#on[a-z]+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)#is', '', $html);
    $html = preg_replace('#(href|src)\s*=\s*("|\')?(javascript|vbscript):[^"\'> ]*#is', '$1="#"', $html);
    return trim($html);
}

function plain_excerpt($html, $len = 120)
{
    $text = strip_tags((string) $html);
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    $text = preg_replace('/\s+/u', ' ', $text);
    $text = trim($text);
    return mb_strlen($text) > $len ? mb_substr($text, 0, $len) . '…' : $text;
}

/** 帖子是否填写了标题 */
function post_has_title($post)
{
    return trim((string) ($post['title'] ?? '')) !== '';
}

/** 帖子展示标题：无标题时退回正文摘要，避免列表和页面标题出现空白 */
function post_display_title($post, $len = 80)
{
    $title = trim((string) ($post['title'] ?? ''));
    if ($title !== '') {
        return $title;
    }
    $excerpt = plain_excerpt((string) ($post['content'] ?? ''), $len);
    return $excerpt !== '' ? $excerpt : '无标题帖子';
}

/** 群发正文：优先使用已清洗的 HTML payload；旧记录回退为纯文本并按换行显示 */
function broadcast_render_html($content, $payload = '')
{
    $html = trim((string) $payload);
    if ($html !== '') {
        return sanitize_html($html);
    }
    $text = trim((string) $content);
    return $text === '' ? '' : nl2br(e($text));
}

/** 好友页消息列表里的群发摘要：保留行内格式，去掉链接、图片和块级标签，避免与外层链接嵌套 */
function broadcast_preview_html($content, $payload = '')
{
    $html = trim((string) $payload);
    if ($html === '') {
        $text = trim((string) $content);
        return $text === '' ? '' : e(plain_excerpt($text, 38));
    }
    $html = sanitize_html($html);
    $html = preg_replace('#</?(a|img|audio|video|source|table|thead|tbody|tr|td|th|figure|figcaption|iframe|object|embed|form|input|button|textarea|select|meta|link|base|svg|math)\b[^>]*>#i', '', $html);
    $html = preg_replace('#</?(p|div|h[1-6]|ul|ol|li|blockquote|pre)\b[^>]*>#i', ' ', $html);
    $html = preg_replace('/[ \t\r\n]+/', ' ', $html);
    return trim($html);
}

function random_code($len = 6)
{
    $chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
    $code = '';
    for ($i = 0; $i < $len; $i++) {
        $code .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $code;
}

function random_string($len = 10)
{
    $chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $s = '';
    for ($i = 0; $i < $len; $i++) {
        $s .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $s;
}

function safe_next($next, $fallback = 'index.php')
{
    $next = (string) $next;
    if ($next === '' || preg_match('#^(http|https|//|javascript)#i', $next)) {
        return base_url($fallback);
    }
    return $next;
}

// ---------- 帖子密码 ----------
function post_access_granted($postId)
{
    return !empty($_SESSION['post_pw'][(int) $postId]);
}

function grant_post_access($postId)
{
    $_SESSION['post_pw'][(int) $postId] = true;
}

/**
 * 帖子密码免密查看权限。
 * 发布者始终可进入自己的帖子；普通管理员只能免密查看普通用户的密码帖；
 * 管理员不能免密查看其他管理员或超级管理员的密码帖；超级管理员可免密查看管理员和普通用户的帖子。
 */
function can_bypass_post_password($post, $user = null)
{
    $user = $user ?: current_user();
    if (!$user || empty($post['user_id'])) {
        return false;
    }
    if ((int) $post['user_id'] === (int) $user['id']) {
        return true;
    }
    if (!is_admin($user)) {
        return false;
    }
    $author = user_by_id((int) $post['user_id']);
    if (!$author || is_superadmin($author)) {
        return false;
    }
    if (is_admin($author) && !is_superadmin($user)) {
        return false;
    }
    return true;
}

/**
 * 管理权限层级：作者本人、超级管理员始终可见；
 * 普通管理员只能越过普通用户的限制，不能越过其他管理员或超级管理员。
 * 用于“仅作者可见”和附件 / 网盘的无门槛查看、保存。
 */
function post_author_only_filter($alias = 'p', $user = null)
{
    $alias = preg_replace('/[^a-zA-Z0-9_]/', '', (string) $alias) ?: 'p';
    $user = $user ?: current_user();
    if (is_superadmin($user)) {
        return '1=1';
    }
    $uid = $user ? (int) $user['id'] : 0;
    if (is_admin($user)) {
        return '(' . $alias . '.author_only = 0 OR ' . $alias . '.user_id = ' . $uid
            . ' OR ' . $alias . '.user_id IN (SELECT id FROM ' . DB::table('users') . " WHERE role NOT IN ('admin','superadmin')))";
    }
    return '(' . $alias . '.author_only = 0' . ($uid > 0 ? ' OR ' . $alias . '.user_id = ' . $uid : '') . ')';
}

function post_privileged_can_view($post, $user = null)
{
    $user = $user ?: current_user();
    if (!$user || empty($post['user_id'])) {
        return false;
    }
    if ((int) $post['user_id'] === (int) $user['id']) {
        return true;
    }
    if (is_superadmin($user)) {
        return true;
    }
    if (!is_admin($user)) {
        return false;
    }
    $author = user_by_id((int) $post['user_id']);
    if (!$author || is_superadmin($author) || is_admin($author)) {
        return false;
    }
    return true;
}

// ---------- 帖子附件 / 网盘内容权限 ----------
/**
 * 读取帖子某一类内容的查看规则。
 * kind: attach（附件） | netdisk（网盘信息）
 */
function post_content_rule($post, $kind = 'attach')
{
    $prefix = $kind === 'netdisk' ? 'netdisk' : 'attach';
    $vis = (string) ($post[$prefix . '_visibility'] ?? 'public');
    if (!in_array($vis, ['public', 'reply', 'points'], true)) {
        $vis = 'public';
    }
    $points = max(0, (int) ($post[$prefix . '_points'] ?? 0));
    if ($vis === 'points' && $points <= 0) {
        $vis = 'public';
    }
    return ['visibility' => $vis, 'points' => $points];
}

function post_user_replied($postId, $userId)
{
    if (!$userId) {
        return false;
    }
    return (bool) DB::val('SELECT COUNT(*) FROM ' . DB::table('comments') . '
                           WHERE post_id = ? AND user_id = ? AND status = 1', [(int) $postId, (int) $userId], 0);
}

function post_content_unlocked($postId, $userId, $kind = 'attach')
{
    if (!$userId) {
        return false;
    }
    return (bool) DB::val('SELECT COUNT(*) FROM ' . DB::table('post_unlocks') . '
                           WHERE post_id = ? AND user_id = ? AND kind = ?',
                           [(int) $postId, (int) $userId, (string) $kind], 0);
}

/**
 * 判断当前用户能否看到帖子的附件 / 网盘信息。
 * 发布者与管理员始终可见；公开内容所有人可见；
 * 回复可见需要该用户在本帖留过评论；积分可见需要存在对应的解锁记录。
 */
function post_content_visible($post, $kind = 'attach', $user = null)
{
    if (!$user) {
        return post_content_rule($post, $kind)['visibility'] === 'public' && (int) ($post['author_only'] ?? 0) !== 1;
    }
    if ((int) ($post['author_only'] ?? 0) === 1 && !post_privileged_can_view($post, $user)) {
        return false;
    }
    if (post_privileged_can_view($post, $user)) {
        return true;
    }
    $rule = post_content_rule($post, $kind);
    if ($rule['visibility'] === 'public') {
        return true;
    }
    if ($rule['visibility'] === 'reply') {
        return post_user_replied((int) $post['id'], (int) $user['id']);
    }
    return post_content_unlocked((int) $post['id'], (int) $user['id'], $kind);
}

/**
 * 阅读帖子奖励：同一用户同一帖子每天只计一次有效阅读。
 * 支持每日有效次数、每日积分上限、超限后不发积分或扣除积分。
 */
function reward_read_points($userId, $postId)
{
    if (setting('read_points_enable', '1') !== '1') {
        return 0;
    }
    $base = max(0, (int) setting('read_points', 1));
    if ($base <= 0) {
        return 0;
    }
    $today = date('Y-m-d');
    $exists = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('post_read_rewards') . '
                             WHERE post_id = ? AND user_id = ? AND day = ?',
                             [(int) $postId, (int) $userId, $today], 0);
    if ($exists) {
        return 0;
    }
    $limit = max(0, (int) setting('read_points_limit', 10));
    $cap = max(0, (int) setting('read_points_cap', 10));
    $count = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('post_read_rewards') . '
                            WHERE user_id = ? AND day = ? AND reward > 0',
                            [(int) $userId, $today], 0);
    $sum = (int) DB::val('SELECT COALESCE(SUM(reward), 0) FROM ' . DB::table('post_read_rewards') . '
                         WHERE user_id = ? AND day = ? AND reward > 0',
                         [(int) $userId, $today], 0);
    $over = ($limit > 0 && $count >= $limit) || ($cap > 0 && $sum >= $cap);
    $delta = 0;
    $note = '阅读奖励';
    if ($over) {
        $note = '超过每日有效阅读次数或积分上限';
        if (setting('points_over_action', 'none') === 'deduct') {
            $points = (int) DB::val('SELECT points FROM ' . DB::table('users') . ' WHERE id = ?', [(int) $userId], 0);
            $delta = -min($points, $base);
            $note .= '，扣除积分';
        } else {
            $note .= '，本次无积分';
        }
    } else {
        $delta = $base;
        if ($cap > 0) {
            $delta = min($delta, max(0, $cap - $sum));
        }
    }
    try {
        DB::insert('post_read_rewards', [
            'post_id'    => (int) $postId,
            'user_id'    => (int) $userId,
            'day'        => $today,
            'reward'     => (int) $delta,
            'created_at' => now(),
        ]);
    } catch (Exception $e) {
        return 0;
    }
    if ($delta !== 0) {
        add_points($userId, $delta);
        DB::insert('point_logs', [
            'user_id'    => (int) $userId,
            'action'     => 'read',
            'delta'      => (int) $delta,
            'note'       => $note . ' #' . (int) $postId,
            'ref_id'     => (int) $postId,
            'created_at' => now(),
        ]);
    }
    return $delta;
}

// ---------- 扩展开关 ----------
function extension_enabled($slug)
{
    static $cache = null;
    if ($cache === null) {
        $cache = [];
        foreach (DB::all('SELECT slug, status FROM ' . DB::table('extensions')) as $r) {
            $cache[$r['slug']] = (int) $r['status'] === 1;
        }
    }
    return !empty($cache[$slug]);
}

/* ================= 毒鸡汤 / 每日一言（扩展） ================= */

function quote_interval_seconds()
{
    $v = (int) setting('quote_interval', 300);
    return max(5, min(86400, $v));
}

function quote_pool($limit = 100)
{
    return DB::all('SELECT id, content, source FROM ' . DB::table('quotes') . ' WHERE status = 1 ORDER BY sort ASC, id ASC LIMIT ' . (int) $limit);
}

function quote_default_lines()
{
    return [
        '你并不是一无所有，你还有病。',
        '只要我够努力，老板就能过上他想要的生活。',
        '别抱怨自己累，看看别人，别人根本不在意你。',
        '机会总是留给有准备的人，而你有准备也不一定有机会。',
        '有些人出现在你的生命里，就是为了告诉你，你真好骗。',
        '失败并不可怕，可怕的是你还相信这句话。',
        '你以为有钱人很快乐吗？他们的快乐你根本想象不到。',
        '生活不止眼前的苟且，还有读不懂的诗和到不了的远方。',
    ];
}

function quote_fetch_network()
{
    $remote = '';
    $endpoint = 'https://api.vvhan.com/api/ian/dujitang?type=json';
    if (function_exists('curl_init')) {
        $ch = curl_init($endpoint);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_TIMEOUT        => 5,
            CURLOPT_USERAGENT      => 'Komorebi-Forum/1.0',
        ]);
        $res = curl_exec($ch);
        curl_close($ch);
        if (is_string($res) && $res !== '') {
            $json = json_decode($res, true);
            if (is_array($json)) {
                $candidate = '';
                if (isset($json['data']['content'])) {
                    $candidate = $json['data']['content'];
                } elseif (isset($json['content'])) {
                    $candidate = $json['content'];
                } elseif (isset($json['data']) && is_string($json['data'])) {
                    $candidate = $json['data'];
                }
                if (is_string($candidate)) {
                    $remote = trim(strip_tags($candidate));
                }
            }
        }
    }
    if ($remote !== '' && mb_strlen($remote, 'UTF-8') <= 120) {
        return ['content' => $remote, 'source' => 'network'];
    }
    $pool = array_merge(quote_default_lines(), [
        '成年人的崩溃，是从缺钱开始的。',
        '你所谓的迷茫，不过是清醒地看着自己沉沦。',
        '条条大路通罗马，可有人就生在罗马。',
        '不是路不平，而是你不行。',
        '有时候你不努力一下，都不知道什么叫绝望。',
        '谁说你没有毅力？你坚持单身这么多年。',
        '别灰心，人生就是这样起起落落落落落落。',
        '当你觉得自己又丑又穷的时候，不要悲伤，至少你的判断是对的。',
        '胖了心情不好，饿了脾气不好，穷了心态不好，这就是你。',
        '你总说梦想遥不可及，可你从不早睡也不早起。',
        '世上无难事，只要肯放弃。',
        '努力不一定被看见，但休息一定会被看见。',
    ]);
    return ['content' => $pool[array_rand($pool)], 'source' => 'local'];
}

/* ================= 帖子 IP 属地 ================= */

function client_ip()
{
    foreach (['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $key) {
        if (empty($_SERVER[$key])) { continue; }
        $raw = explode(',', (string) $_SERVER[$key])[0];
        $ip = trim($raw);
        if (filter_var($ip, FILTER_VALIDATE_IP)) {
            return $ip;
        }
    }
    return '';
}

function ip_is_private($ip)
{
    return $ip === '' || !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}

function ip_location($ip)
{
    static $memo = [];
    $ip = trim((string) $ip);
    if (isset($memo[$ip])) { return $memo[$ip]; }
    $none = ['region' => '', 'city' => '', 'district' => '', 'street' => '', 'addr' => ''];
    if (ip_is_private($ip)) {
        return $memo[$ip] = ['region' => '本地', 'city' => '', 'district' => '', 'street' => '', 'addr' => '本地'];
    }
    $table = DB::table('ip_locations');
    try {
        $cached = DB::one('SELECT * FROM ' . $table . ' WHERE ip = ? LIMIT 1', [$ip]);
        if ($cached && strtotime($cached['updated_at']) > time() - 30 * 86400 && trim((string) ($cached['addr'] ?? '')) !== '') {
            return $memo[$ip] = [
                'region' => $cached['region'],
                'city'   => $cached['city'],
                'district' => (string) ($cached['district'] ?? ''),
                'street'   => (string) ($cached['street'] ?? ''),
                'addr'   => $cached['addr'],
            ];
        }
    } catch (Exception $e) {
        $cached = null;
    }

    $found = null;
    $fetch = function ($url) {
        if (!function_exists('curl_init')) { return ''; }
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_TIMEOUT        => 4,
            CURLOPT_USERAGENT      => 'Komorebi-Forum/1.0',
        ]);
        $res = curl_exec($ch);
        curl_close($ch);
        return is_string($res) ? $res : '';
    };

    $body = $fetch('https://whois.pconline.com.cn/ipJson.jsp?ip=' . rawurlencode($ip) . '&json=true');
    if ($body !== '') {
        if (!mb_check_encoding($body, 'UTF-8')) {
            $body = @mb_convert_encoding($body, 'UTF-8', 'GBK');
        }
        $json = json_decode($body, true);
        if (is_array($json) && (!empty($json['pro']) || !empty($json['city']))) {
            $pro = trim((string) ($json['pro'] ?? ''));
            $cityRaw = trim((string) ($json['city'] ?? ''));
            $district = trim((string) ($json['region'] ?? ''));
            $street = trim((string) ($json['street'] ?? ''));
            $addr = trim((string) ($json['addr'] ?? ''));
            if ($addr === '') {
                $addr = trim($pro . $cityRaw . $district . $street);
            }
            $found = [
                'region' => $pro,
                'city'   => $cityRaw,
                'district' => $district,
                'street'   => $street,
                'addr'   => $addr,
            ];
        }
    }
    if (!$found) {
        $body = $fetch('http://ip-api.com/json/' . rawurlencode($ip) . '?lang=zh-CN&fields=status,country,regionName,city');
        $json = json_decode($body, true);
        if (is_array($json) && ($json['status'] ?? '') === 'success') {
            $region = trim((string) ($json['regionName'] ?? $json['country'] ?? ''));
            $city = trim((string) ($json['city'] ?? ''));
            $found = [
                'region' => $region,
                'city'   => $city,
                'district' => '',
                'street'   => '',
                'addr'   => trim($region . $city),
            ];
        }
    }
    if (!$found) {
        $found = $none;
    }
    $found['region'] = preg_replace('/省$/u', '', $found['region']);
    $found['city'] = trim((string) $found['city']);
    $found['district'] = trim((string) ($found['district'] ?? ''));
    $found['street'] = trim((string) ($found['street'] ?? ''));
    $found['addr'] = trim((string) $found['addr']);
    try {
        DB::run('DELETE FROM ' . $table . ' WHERE ip = ?', [$ip]);
        DB::insert('ip_locations', [
            'ip'         => $ip,
            'region'     => $found['region'],
            'city'       => $found['city'],
            'district'   => $found['district'],
            'street'     => $found['street'],
            'addr'       => $found['addr'],
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    } catch (Exception $e) {
        // 缓存写失败不影响显示
    }
    return $memo[$ip] = $found;
}

function ip_location_detail_text($ip)
{
    $loc = ip_location($ip);
    $addr = trim((string) ($loc['addr'] ?? ''));
    if ($addr !== '') { return $addr; }
    return ip_location_text($ip);
}

function ip_location_text($ip)
{
    $loc = ip_location($ip);
    if ($loc['region'] === '') { return '未知属地'; }
    $region = trim((string) $loc['region']);
    $city = trim((string) $loc['city']);
    $municipalities = ['北京', '上海', '天津', '重庆'];
    if (!preg_match('/省$|市$|自治区$|特别行政区$/u', $region)) {
        $region .= in_array($region, $municipalities, true) ? '市' : '省';
    }
    if ($city === '') {
        return $region;
    }
    if ($city === $region || $city === preg_replace('/省$/u', '', $region) || $city === $region . '市') {
        return $region;
    }
    if (!preg_match('/市$|区$|县$|旗$|州$|盟$/u', $city)) {
        $city .= '市';
    }
    return $region . $city;
}

function mask_ip($ip)
{
    if (setting('post_ip_mask', '1') !== '1') { return $ip; }
    $head = max(0, min(20, (int) setting('post_ip_head', 4)));
    $tail = max(0, min(20, (int) setting('post_ip_tail', 2)));
    $stars = max(1, min(32, (int) setting('post_ip_stars', 4)));
    $len = strlen($ip);
    if ($len <= $head + $tail) {
        $head = (int) floor($len / 2);
        $tail = $len - $head;
    }
    return substr($ip, 0, $head) . str_repeat('*', $stars) . ($tail > 0 ? substr($ip, -$tail) : '');
}

/* ================= 个人资料：省 / 市 / IP ================= */

function location_addr_pick(array $address, array $keys)
{
    foreach ($keys as $key) {
        $value = trim((string) ($address[$key] ?? ''));
        if ($value !== '') { return $value; }
    }
    return '';
}

/**
 * 把“城东街道XX社区 / XX镇YY村”拆成乡镇街道与村社区。
 * IP 接口通常只返回一个 street 字符串，GPS 逆地理编码则可能直接给出 village。
 */
function location_split_street_village($street)
{
    $street = trim((string) $street);
    if ($street === '') { return ['', '']; }
    if (preg_match('/^(.+?(?:街道|镇|乡|苏木))(.{1,64})$/u', $street, $m)) {
        return [trim($m[1]), trim($m[2])];
    }
    if (preg_match('/(?:社区|村委会|居委会|村|嘎查)$/u', $street)) {
        return ['', $street];
    }
    return [$street, ''];
}

function normalize_province_text($province)
{
    $province = trim((string) $province);
    if ($province === '') { return ''; }
    if (preg_match('/省$|市$|自治区$|特别行政区$/u', $province)) { return $province; }
    $autonomous = ['内蒙古', '广西', '西藏', '宁夏', '新疆'];
    if (in_array($province, $autonomous, true)) { return $province . '自治区'; }
    if (in_array($province, ['北京', '上海', '天津', '重庆'], true)) { return $province . '市'; }
    if (in_array($province, ['香港', '澳门'], true)) { return $province . '特别行政区'; }
    return $province . '省';
}

function normalize_city_text($city)
{
    $city = trim((string) $city);
    if ($city === '') { return ''; }
    if (preg_match('/市$|区$|县$|旗$|州$|盟$/u', $city)) { return $city; }
    return $city . '市';
}

function profile_location_mode($user)
{
    $mode = (int) ($user['show_location'] ?? 1);
    return in_array($mode, [0, 1, 2], true) ? $mode : 1;
}

function profile_location_public_text($user, $forceFull = false)
{
    $mode = profile_location_mode($user);
    if ($mode === 0) {
        return '';
    }
    return profile_location_text($user, $forceFull || $mode === 2);
}

function profile_location_text($user, $full = false)
{
    $province = normalize_province_text($user['province'] ?? '');
    $city = normalize_city_text($user['city'] ?? '');
    $district = trim((string) ($user['district'] ?? ''));
    $town = trim((string) ($user['town'] ?? ''));
    $village = trim((string) ($user['village'] ?? ''));
    $has = $province !== '' || $city !== '' || $district !== '' || $town !== '' || $village !== '';
    if (!$has) {
        $ip = trim((string) ($user['last_ip'] ?? ''));
        return $ip !== '' ? ip_location_text($ip) : '未设置所在地';
    }
    $text = '';
    if ($province !== '') { $text .= $province; }
    if ($city !== '' && $city !== $province && $city !== $province . '市') { $text .= $city; }
    if ($full) {
        if ($town !== '' && $district !== '' && mb_strpos($town, $district) === 0) {
            $town = trim(mb_substr($town, mb_strlen($district)));
        }
        if ($village !== '' && $town !== '' && mb_strpos($village, $town) === 0) {
            $village = trim(mb_substr($village, mb_strlen($town)));
        }
        if ($village !== '' && $district !== '' && mb_strpos($village, $district) === 0) {
            $village = trim(mb_substr($village, mb_strlen($district)));
        }
        foreach ([$district, $town, $village] as $part) {
            if ($part !== '' && mb_strpos($text, $part) === false) { $text .= $part; }
        }
    }
    return $text !== '' ? $text : $province;
}

function mask_ip_profile($ip)
{
    $ip = (string) $ip;
    $len = strlen($ip);
    if ($len === 0) { return ''; }
    $head = min(4, (int) floor($len / 2));
    $tail = min(4, $len - $head);
    return substr($ip, 0, $head) . str_repeat('*', 5) . ($tail > 0 ? substr($ip, -$tail) : '');
}

/* ================= 聊天室媒体格式 ================= */

function chat_video_extensions()
{
    return [
        'mp4','m4v','webm','mov','qt','avi','mkv','flv','f4v','wmv','asf',
        'mpg','mpeg','mpe','mpv','m2v','m2p','m2ts','mts','ts','ps',
        '3gp','3g2','ogv','vob','rm','rmvb','divx','mxf','dv','nut','y4m',
        'h264','264','h265','265','hevc','mjpeg','mjpg','mpeg2','mpeg4',
    ];
}

function chat_audio_extensions()
{
    return [
        'mp3','mp2','wav','m4a','m4b','m4p','aac','ogg','oga','opus','flac','weba',
        'amr','wma','aiff','aif','aifc','au','snd','ac3','eac3','dts','ape','mka',
        'ra','ram','wv','caf','mpc','tta','spx','3ga','mid','midi',
        'm4r','alac','dsf','dff','mogg','voc','sln','awb','xmf','tak',
    ];
}

function chat_media_extensions()
{
    return array_merge(chat_video_extensions(), chat_audio_extensions());
}

function media_kind_by_ext($ext)
{
    $ext = strtolower((string) $ext);
    if (in_array($ext, chat_video_extensions(), true)) { return 'video'; }
    if (in_array($ext, chat_audio_extensions(), true)) { return 'audio'; }
    return '';
}

/**
 * 用 ffprobe 识别音视频容器、编码、时长和标签。
 * 返回 ['kind'=>'video|audio', 'video_codec'=>'', 'audio_codec'=>'', 'tags'=>[]]
 */
function media_probe_file($full)
{
    static $cache = [];
    $full = (string) $full;
    if (!is_file($full)) {
        return null;
    }
    $key = $full . '|' . (string) @filemtime($full) . '|' . (string) @filesize($full);
    if (array_key_exists($key, $cache)) {
        return $cache[$key];
    }
    $ffprobe = '';
    foreach (['/usr/bin/ffprobe', '/usr/local/bin/ffprobe', '/opt/homebrew/bin/ffprobe'] as $bin) {
        if (is_executable($bin)) { $ffprobe = $bin; break; }
    }
    if ($ffprobe === '' && function_exists('shell_exec')) {
        $found = trim((string) @shell_exec('command -v ffprobe 2>/dev/null'));
        if ($found !== '' && strpos($found, '/') !== false) { $ffprobe = $found; }
    }
    if ($ffprobe === '' || !function_exists('exec')) {
        $cache[$key] = null;
        return null;
    }
    $cmd = escapeshellarg($ffprobe) . ' -v error -show_entries '
        . 'format=format_name,duration:format_tags=title,artist,album_artist:'
        . 'stream=codec_type,codec_name,width,height:stream_tags=title,artist:stream_disposition=attached_pic '
        . '-of json ' . escapeshellarg($full) . ' 2>/dev/null';
    $lines = [];
    $code = 1;
    @exec($cmd, $lines, $code);
    if ($code !== 0 || !$lines) {
        $cache[$key] = null;
        return null;
    }
    $json = json_decode(implode("\n", $lines), true);
    if (!is_array($json)) {
        $cache[$key] = null;
        return null;
    }
    $hasVideo = false;
    $hasAudio = false;
    $videoCodec = '';
    $audioCodec = '';
    foreach (($json['streams'] ?? []) as $stream) {
        $type = strtolower((string) ($stream['codec_type'] ?? ''));
        $codec = strtolower((string) ($stream['codec_name'] ?? ''));
        $attached = (int) ($stream['disposition']['attached_pic'] ?? 0);
        if ($type === 'video' && $attached === 0) {
            $hasVideo = true;
            if ($videoCodec === '') { $videoCodec = $codec; }
        } elseif ($type === 'audio') {
            $hasAudio = true;
            if ($audioCodec === '') { $audioCodec = $codec; }
        }
    }
    $tags = [];
    foreach (['format', 'streams'] as $scope) {
        $items = $scope === 'format' ? [($json['format'] ?? [])] : ($json['streams'] ?? []);
        foreach ($items as $item) {
            if (!is_array($item)) { continue; }
            foreach ((array) ($item['tags'] ?? []) as $tk => $tv) {
                $lk = strtolower((string) $tk);
                if (!isset($tags[$lk]) && is_scalar($tv) && trim((string) $tv) !== '') {
                    $tags[$lk] = trim((string) $tv);
                }
            }
        }
    }
    $result = [
        'kind' => $hasVideo ? 'video' : ($hasAudio ? 'audio' : ''),
        'video_codec' => $videoCodec,
        'audio_codec' => $audioCodec,
        'format' => strtolower((string) ($json['format']['format_name'] ?? '')),
        'duration' => (float) ($json['format']['duration'] ?? 0),
        'tags' => $tags,
    ];
    $cache[$key] = $result;
    return $result;
}

/**
 * 浏览器能否直接播放这个视频；不能播放时转成 H.264/AAC MP4。
 */
function video_make_compatible($relPath)
{
    $relPath = str_replace('\\', '/', (string) $relPath);
    if (strpos($relPath, 'uploads/') !== 0 || strpos($relPath, '..') !== false) {
        return null;
    }
    $full = APP_ROOT . '/' . $relPath;
    if (!is_file($full)) {
        return null;
    }
    $ext = strtolower((string) pathinfo($full, PATHINFO_EXTENSION));
    $probe = media_probe_file($full);
    $browserFriendly = false;
    if ($probe && $probe['kind'] === 'video') {
        $v = $probe['video_codec'];
        $a = $probe['audio_codec'];
        if (in_array($ext, ['mp4', 'm4v'], true) && $v === 'h264' && ($a === '' || in_array($a, ['aac', 'mp3'], true))) {
            $browserFriendly = true;
        } elseif ($ext === 'webm' && in_array($v, ['vp8', 'vp9', 'av1'], true) && ($a === '' || in_array($a, ['opus', 'vorbis'], true))) {
            $browserFriendly = true;
        }
    } elseif (!$probe && in_array($ext, ['mp4', 'm4v', 'webm'], true)) {
        $browserFriendly = true;
    }
    if ($browserFriendly) {
        return $relPath;
    }

    $ffmpeg = '';
    foreach (['/usr/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/opt/homebrew/bin/ffmpeg'] as $bin) {
        if (is_executable($bin)) { $ffmpeg = $bin; break; }
    }
    if ($ffmpeg === '' && function_exists('shell_exec')) {
        $found = trim((string) @shell_exec('command -v ffmpeg 2>/dev/null'));
        if ($found !== '' && strpos($found, '/') !== false) { $ffmpeg = $found; }
    }
    if ($ffmpeg === '' || !function_exists('exec')) {
        // 无转码器时保留原视频，保证所有格式都能上传
        return $relPath;
    }

    $base = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '', $relPath);
    $targetRel = $base . '_web.mp4';
    $targetFull = APP_ROOT . '/' . $targetRel;
    if (is_file($targetFull) && filesize($targetFull) > 0 && @filemtime($targetFull) >= @filemtime($full)) {
        return $targetRel;
    }
    $timeout = is_executable('/usr/bin/timeout') ? '/usr/bin/timeout 180 ' : '';
    $cmd = $timeout . escapeshellarg($ffmpeg) . ' -nostdin -y -i ' . escapeshellarg($full)
        . ' -map 0:v:0 -map 0:a? -vf ' . escapeshellarg('scale=trunc(iw/2)*2:trunc(ih/2)*2') . ' '
        . '-c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p '
        . '-c:a aac -b:a 128k -ac 2 -movflags +faststart '
        . escapeshellarg($targetFull) . ' 2>&1';
    $out = [];
    $code = 1;
    @exec($cmd, $out, $code);
    if ($code !== 0 || !is_file($targetFull) || filesize($targetFull) <= 0) {
        @unlink($targetFull);
        // 转码失败时保留原视频
        return $relPath;
    }
    if ($full !== $targetFull) {
        @unlink($full);
    }
    @chmod($targetFull, 0644);
    return $targetRel;
}

function video_playable_url($url)
{
    $url = (string) $url;
    $path = (string) parse_url($url, PHP_URL_PATH);
    $pos = strpos($path, 'uploads/');
    if ($pos === false) {
        return $url;
    }
    $rel = ltrim(substr($path, $pos), '/');
    $ext = strtolower((string) pathinfo($rel, PATHINFO_EXTENSION));
    if ($ext === '') {
        return $url;
    }
    $candidate = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '_web.mp4', $rel);
    if (is_file(APP_ROOT . '/' . $candidate)) {
        return full_url($candidate);
    }
    $converted = video_make_compatible($rel);
    if ($converted) {
        return full_url($converted);
    }
    return $url;
}

/**
 * 上传后立即把聊天音视频处理成浏览器可播放格式；失败则删除原文件并报错。
 */
function chat_prepare_media($relPath, $kind)
{
    $relPath = (string) $relPath;
    if ($kind === 'image') {
        $out = image_make_compatible($relPath);
        return $out ?: $relPath;
    }
    if ($kind === 'video') {
        $out = video_make_compatible($relPath);
        return $out ?: $relPath;
    }
    if ($kind === 'audio') {
        $out = audio_make_compatible($relPath);
        return $out ?: $relPath;
    }
    return $relPath;
}

function media_ffmpeg_binary()
{
    foreach (['/usr/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/opt/homebrew/bin/ffmpeg'] as $bin) {
        if (is_executable($bin)) { return $bin; }
    }
    if (function_exists('shell_exec')) {
        $found = trim((string) @shell_exec('command -v ffmpeg 2>/dev/null'));
        if ($found !== '' && strpos($found, '/') !== false) { return $found; }
    }
    return '';
}

/**
 * 为已有文件生成浏览器兼容的播放副本，保留原文件（网盘 / 帖子附件用）。
 * 返回相对路径；已经兼容时直接返回原路径。
 */
function media_playable_copy($relPath, $kind = '')
{
    $relPath = str_replace('\\', '/', (string) $relPath);
    if ((strpos($relPath, 'uploads/') !== 0 && strpos($relPath, 'storage/drive/') !== 0)
        || strpos($relPath, '..') !== false) {
        return null;
    }
    $full = APP_ROOT . '/' . $relPath;
    if (!is_file($full)) {
        return null;
    }
    $ext = strtolower((string) pathinfo($full, PATHINFO_EXTENSION));
    if ($kind === '') { $kind = media_kind_by_name($full); }

    if ($kind === 'video') {
        $friendly = false;
        $probe = media_probe_file($full);
        if ($probe && $probe['kind'] === 'video') {
            $v = $probe['video_codec'];
            $a = $probe['audio_codec'];
            if (in_array($ext, ['mp4', 'm4v'], true) && $v === 'h264' && ($a === '' || in_array($a, ['aac', 'mp3'], true))) {
                $friendly = true;
            } elseif ($ext === 'webm' && in_array($v, ['vp8', 'vp9', 'av1'], true)
                && ($a === '' || in_array($a, ['opus', 'vorbis'], true))) {
                $friendly = true;
            }
        } elseif (!$probe && in_array($ext, ['mp4', 'm4v', 'webm'], true)) {
            $friendly = true;
        }
        if ($friendly) { return $relPath; }

        $targetRel = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '_play.mp4', $relPath);
        $targetFull = APP_ROOT . '/' . $targetRel;
        if (is_file($targetFull) && filesize($targetFull) > 0 && @filemtime($targetFull) >= @filemtime($full)) {
            return $targetRel;
        }
        $ffmpeg = media_ffmpeg_binary();
        if ($ffmpeg === '' || !function_exists('exec')) { return null; }
        $timeout = is_executable('/usr/bin/timeout') ? '/usr/bin/timeout 180 ' : '';
        $cmd = $timeout . escapeshellarg($ffmpeg) . ' -nostdin -y -i ' . escapeshellarg($full)
            . ' -map 0:v:0 -map 0:a? -vf ' . escapeshellarg('scale=trunc(iw/2)*2:trunc(ih/2)*2') . ' '
            . '-c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p '
            . '-c:a aac -b:a 128k -ac 2 -movflags +faststart '
            . escapeshellarg($targetFull) . ' 2>&1';
        $out = [];
        $code = 1;
        @exec($cmd, $out, $code);
        if ($code !== 0 || !is_file($targetFull) || filesize($targetFull) <= 0) {
            @unlink($targetFull);
            return null;
        }
        @chmod($targetFull, 0644);
        return $targetRel;
    }

    if ($kind === 'audio') {
        if (in_array($ext, ['mp3', 'm4a', 'wav'], true)) { return $relPath; }
        $targetRel = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '_play.mp3', $relPath);
        $targetFull = APP_ROOT . '/' . $targetRel;
        if (is_file($targetFull) && filesize($targetFull) > 0 && @filemtime($targetFull) >= @filemtime($full)) {
            return $targetRel;
        }
        $ffmpeg = media_ffmpeg_binary();
        if ($ffmpeg === '' || !function_exists('exec')) { return null; }
        $timeout = is_executable('/usr/bin/timeout') ? '/usr/bin/timeout 180 ' : '';
        $cmd = $timeout . escapeshellarg($ffmpeg) . ' -nostdin -y -i ' . escapeshellarg($full)
            . ' -vn -c:a libmp3lame -b:a 128k -ac 2 -ar 44100 '
            . escapeshellarg($targetFull) . ' 2>&1';
        $out = [];
        $code = 1;
        @exec($cmd, $out, $code);
        if ($code !== 0 || !is_file($targetFull) || filesize($targetFull) <= 0) {
            @unlink($targetFull);
            $targetRel = preg_replace('/\.' . preg_quote($ext, '/') . '$/i', '_play.m4a', $relPath);
            $targetFull = APP_ROOT . '/' . $targetRel;
            $cmd = $timeout . escapeshellarg($ffmpeg) . ' -nostdin -y -i ' . escapeshellarg($full)
                . ' -vn -c:a aac -b:a 96k -ac 2 -ar 44100 -movflags +faststart '
                . escapeshellarg($targetFull) . ' 2>&1';
            $out = [];
            $code = 1;
            @exec($cmd, $out, $code);
            if ($code !== 0 || !is_file($targetFull) || filesize($targetFull) <= 0) {
                @unlink($targetFull);
                return null;
            }
        }
        @chmod($targetFull, 0644);
        return $targetRel;
    }

    return $relPath;
}

function profile_change_remaining_display($limitKey)
{
    $limit = (int) setting($limitKey, 3);
    if ($limit <= 0) { return '不限'; }
    $uid = (int) (current_user()['id'] ?? 0);
    if ($uid <= 0) { return $limit; }
    $weekAgo = date('Y-m-d H:i:s', strtotime('-7 days'));
    $used = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('profile_changes') . ' WHERE user_id = ? AND kind = ? AND created_at >= ?', [$uid, $limitKey === 'name_change_limit' ? 'nickname' : 'avatar', $weekAgo], 0);
    return max(0, $limit - $used);
}

function user_is_muted($user)
{
    if (!$user) { return false; }
    $until = trim((string) ($user['mute_until'] ?? ''));
    if ($until === '') { return false; }
    return strtotime($until) > time();
}

function user_ban_remaining($user)
{
    if (!$user || (int) $user['status'] === 1) { return ''; }
    $until = trim((string) ($user['ban_until'] ?? ''));
    if ($until === '' || strtotime($until) <= time()) { return ''; }
    if (strtotime($until) >= strtotime('9999-01-01')) { return '永久'; }
    $left = strtotime($until) - time();
    if ($left >= 86400) { return max(1, (int) ceil($left / 86400)) . '天'; }
    if ($left >= 3600) { return max(1, (int) ceil($left / 3600)) . '小时'; }
    return max(1, (int) ceil($left / 60)) . '分钟';
}

function user_mute_remaining($user)
{
    if (!user_is_muted($user)) { return ''; }
    $until = (string) $user['mute_until'];
    if (strtotime($until) >= strtotime('9999-01-01')) { return '永久'; }
    $left = strtotime($until) - time();
    if ($left >= 86400) { return max(1, (int) ceil($left / 86400)) . '天'; }
    if ($left >= 3600) { return max(1, (int) ceil($left / 3600)) . '小时'; }
    return max(1, (int) ceil($left / 60)) . '分钟';
}

function user_status_meta($user)
{
    if ((int) ($user['status'] ?? 1) !== 1) {
        return ['key' => 'ban', 'label' => '封禁', 'cls' => 'bad', 'extra' => user_ban_remaining($user)];
    }
    if (user_is_muted($user)) {
        return ['key' => 'mute', 'label' => '禁言', 'cls' => 'mute', 'extra' => user_mute_remaining($user)];
    }
    return ['key' => 'ok', 'label' => '正常', 'cls' => 'ok', 'extra' => ''];
}

/* ================= v6.03+ 公共能力 ================= */

/** 记录一条安全事件（登录失败、注册、找回密码等） */
function security_event($kind, $identifier = '')
{
    try {
        DB::insert('security_events', [
            'kind' => mb_substr((string) $kind, 0, 32),
            'ip' => client_ip(),
            'identifier' => mb_substr((string) $identifier, 0, 128),
            'created_at' => now(),
        ]);
    } catch (Exception $e) {
    }
}

/** 当前浏览器 UA，用于登录记录/设备识别，不参与权限判断。 */
function client_ua()
{
    return mb_substr(trim((string) ($_SERVER['HTTP_USER_AGENT'] ?? '')), 0, 255);
}

/** 当前浏览器设备 ID：本地生成的 24 位稳定标识，写入长期 Cookie。 */
function client_device_id()
{
    static $resolved = null;
    if ($resolved !== null) { return $resolved; }
    $cookie = strtolower(trim((string) ($_COOKIE['km_device_id'] ?? '')));
    if (preg_match('/^[a-f0-9]{24}$/', $cookie)) {
        return $resolved = $cookie;
    }
    try {
        $id = bin2hex(random_bytes(12));
    } catch (Throwable $e) {
        $id = substr(md5(uniqid('komorebi-device', true)), 0, 24);
    }
    if (!headers_sent()) {
        setcookie('km_device_id', $id, csrf_cookie_options(time() + 365 * 86400));
    }
    return $resolved = $id;
}

/** 设备码：由设备 ID 稳定派生，便于用户抄写和客服核对。 */
function device_code_from_id($deviceId)
{
    $id = trim((string) $deviceId);
    if ($id === '') { return ''; }
    $hash = strtoupper(substr(hash('sha256', 'komorebi-device|' . $id), 0, 12));
    return 'KM-' . substr($hash, 0, 4) . '-' . substr($hash, 4, 4) . '-' . substr($hash, 8, 4);
}

function client_device_code($deviceId = null)
{
    return device_code_from_id($deviceId !== null ? $deviceId : client_device_id());
}

/** 设备类型摘要：系统 · 浏览器。 */
function client_device_label($ua = '')
{
    $ua = $ua !== '' ? (string) $ua : client_ua();
    $browser = '未知浏览器';
    $system = '未知设备';
    foreach ([
        ['MicroMessenger/', '微信'], ['QQBrowser/', 'QQ 浏览器'], ['Edg/', 'Edge'], ['Chrome/', 'Chrome'],
        ['Firefox/', 'Firefox'], ['Safari/', 'Safari'], ['curl/', 'curl'],
    ] as $m) {
        if (stripos($ua, $m[0]) !== false) { $browser = $m[1]; break; }
    }
    foreach ([
        ['iPhone', 'iPhone'], ['iPad', 'iPad'], ['Android', 'Android'], ['Windows', 'Windows'],
        ['Mac OS', 'macOS'], ['Linux', 'Linux'],
    ] as $m) {
        if (stripos($ua, $m[0]) !== false) { $system = $m[1]; break; }
    }
    return $system . ' · ' . $browser;
}

/**
 * 记录一次登录尝试。只记录账号、IP、UA、结果和失败原因，绝不记录密码。
 * $user 可为用户数组或 null；$identifier 用于失败时记录输入的用户名。
 */
function login_log_record($user, $result, $identifier = '', $reason = '')
{
    try {
        $uid = is_array($user) ? (int) ($user['id'] ?? 0) : 0;
        $username = is_array($user) ? (string) ($user['username'] ?? '') : (string) $identifier;
        $nickname = is_array($user) ? (string) ($user['nickname'] ?? '') : '';
        DB::insert('login_logs', [
            'user_id' => $uid,
            'username' => mb_substr($username, 0, 64),
            'nickname' => mb_substr($nickname, 0, 64),
            'ip' => mb_substr((string) client_ip(), 0, 64),
            'ua' => client_ua(),
            'result' => in_array($result, ['success', 'fail', 'blocked'], true) ? $result : 'fail',
            'reason' => mb_substr((string) $reason, 0, 255),
            'device_id' => client_device_id(),
            'device_code' => client_device_code(),
            'created_at' => now(),
        ]);
    } catch (Throwable $e) {
        // 登录记录失败不能阻断登录本身
    }
}

/** 登录结果的中文标签 */
function login_log_result_label($result)
{
    return ['success' => '登录成功', 'fail' => '登录失败', 'blocked' => '被拦截'][$result] ?? '登录失败';
}

/** 指定窗口内当前 IP / 标识的安全事件数量 */
function security_recent_count($kind, $identifier = '', $window = 600)
{
    $since = date('Y-m-d H:i:s', time() - max(1, (int) $window));
    return (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('security_events') . '
                          WHERE kind = ? AND ip = ? AND identifier = ? AND created_at >= ?',
        [$kind, client_ip(), (string) $identifier, $since], 0);
}

/** 是否已触发限流（>= 上限） */
function security_rate_limited($kind, $limit, $window = 600, $identifier = '')
{
    return security_recent_count($kind, $identifier, $window) >= max(1, (int) $limit);
}

/** 成功后清理该标识的失败记录 */
function security_clear($kind, $identifier = '')
{
    try {
        DB::run('DELETE FROM ' . DB::table('security_events') . ' WHERE kind = ? AND ip = ? AND identifier = ?',
            [$kind, client_ip(), (string) $identifier]);
    } catch (Exception $e) {
    }
}

/** 生成算术验证码问题（会话保存答案） */
function captcha_question()
{
    $a = random_int(2, 9);
    $b = random_int(1, 9);
    $op = random_int(0, 1) ? '+' : '-';
    if ($op === '-' && $a < $b) { list($a, $b) = [$b, $a]; }
    $_SESSION['km_captcha_answer'] = $op === '+' ? $a + $b : $a - $b;
    $_SESSION['km_captcha_at'] = time();
    return $a . ' ' . $op . ' ' . $b . ' = ?';
}

/** 校验验证码；无论对错都会作废本次答案 */
function captcha_check($value)
{
    $answer = $_SESSION['km_captcha_answer'] ?? null;
    $at = (int) ($_SESSION['km_captcha_at'] ?? 0);
    unset($_SESSION['km_captcha_answer'], $_SESSION['km_captcha_at']);
    if ($answer === null || $at <= 0 || time() - $at > 1800) { return false; }
    return trim((string) $value) === (string) (int) $answer;
}

/** 敏感词列表 */
function sensitive_words()
{
    $raw = (string) setting('sensitive_words', '');
    $parts = preg_split('/[\r\n,，、]+/u', $raw) ?: [];
    $out = [];
    foreach ($parts as $w) {
        $w = trim((string) $w);
        if ($w !== '' && mb_strlen($w) <= 40) { $out[] = $w; }
    }
    return array_values(array_unique($out));
}

/** 命中敏感词；返回命中的词或空字符串 */
function sensitive_word_find($text)
{
    $words = sensitive_words();
    if (!$words) { return ''; }
    $plain = strip_tags((string) $text);
    foreach ($words as $w) {
        if ($w !== '' && mb_stripos($plain, $w) !== false) { return $w; }
    }
    return '';
}

/**
 * 处理敏感词：replace 替换、review 标记待审、block 拒绝。
 * 返回 ['text'=>处理后的文本,'hit'=>命中词,'action'=>动作]
 */
function sensitive_filter($text, $action = '')
{
    $hit = sensitive_word_find($text);
    $action = $action ?: (string) setting('sensitive_action', 'replace');
    if ($hit === '') { return ['text' => (string) $text, 'hit' => '', 'action' => '']; }
    if ($action === 'replace') {
        return ['text' => str_ireplace($hit, str_repeat('*', max(1, mb_strlen($hit))), (string) $text), 'hit' => $hit, 'action' => 'replace'];
    }
    return ['text' => (string) $text, 'hit' => $hit, 'action' => in_array($action, ['review', 'block'], true) ? $action : 'review'];
}

/** 后台操作日志 */
function audit_log($action, $detail = '')
{
    try {
        $me = current_user();
        DB::insert('audit_logs', [
            'actor_id' => (int) ($me['id'] ?? 0),
            'action' => mb_substr((string) $action, 0, 64),
            'detail' => mb_substr((string) $detail, 0, 255),
            'ip' => function_exists('client_ip') ? client_ip() : '',
            'created_at' => now(),
        ]);
    } catch (Exception $e) {
    }
}

/** 全站禁言（区别于聊天室禁言） */
function user_is_site_muted($user)
{
    if (!$user) { return false; }
    if (is_admin($user)) { return false; }
    if (setting('site_global_mute', '0') === '1') {
        $globalUntil = trim((string) setting('site_global_mute_until', ''));
        if ($globalUntil === '' || strtotime($globalUntil) > time()) {
            return true;
        }
    }
    $until = trim((string) ($user['site_mute_until'] ?? ''));
    return $until !== '' && strtotime($until) > time();
}

function user_site_mute_remaining($user)
{
    if (!user_is_site_muted($user)) { return ''; }
    if (setting('site_global_mute', '0') === '1') {
        $globalUntil = trim((string) setting('site_global_mute_until', ''));
        if ($globalUntil === '' || strtotime($globalUntil) > time()) {
            $until = $globalUntil;
        }
    }
    if (empty($until)) {
        $until = (string) ($user['site_mute_until'] ?? '');
    }
    if ($until === '' || strtotime($until) >= strtotime('9999-01-01')) { return '永久'; }
    $left = strtotime($until) - time();
    if ($left >= 86400) { return max(1, (int) ceil($left / 86400)) . '天'; }
    if ($left >= 3600) { return max(1, (int) ceil($left / 3600)) . '小时'; }
    return max(1, (int) ceil($left / 60)) . '分钟';
}

/** 用户是否被对方拉黑或已拉黑对方（任一方向都视为不可互动） */
function users_blocked_between($a, $b)
{
    $a = (int) $a;
    $b = (int) $b;
    if ($a <= 0 || $b <= 0 || $a === $b) { return false; }
    return (bool) DB::val('SELECT COUNT(*) FROM ' . DB::table('blocked_users') . '
                           WHERE (blocker_id = ? AND blocked_id = ?) OR (blocker_id = ? AND blocked_id = ?)',
        [$a, $b, $b, $a], 0);
}

function user_blocked_by($blockerId, $blockedId)
{
    return (bool) DB::val('SELECT COUNT(*) FROM ' . DB::table('blocked_users') . ' WHERE blocker_id = ? AND blocked_id = ?',
        [(int) $blockerId, (int) $blockedId], 0);
}

/** 当前用户屏蔽的用户 ID 列表 */
function blocked_user_ids($userId)
{
    $ids = [];
    foreach (DB::all('SELECT blocked_id FROM ' . DB::table('blocked_users') . ' WHERE blocker_id = ?', [(int) $userId]) as $row) {
        $ids[] = (int) $row['blocked_id'];
    }
    return $ids;
}

/** 关注关系 */
function follow_is($followerId, $type, $targetId)
{
    $type = $type === 'category' ? 'category' : 'user';
    return (bool) DB::val('SELECT COUNT(*) FROM ' . DB::table('follows') . '
                           WHERE follower_id = ? AND target_type = ? AND target_id = ?',
        [(int) $followerId, $type, (int) $targetId], 0);
}

function follow_toggle($followerId, $type, $targetId)
{
    $followerId = (int) $followerId;
    $targetId = (int) $targetId;
    $type = $type === 'category' ? 'category' : 'user';
    if ($followerId <= 0 || $targetId <= 0 || ($type === 'user' && $followerId === $targetId)) {
        return ['ok' => false, 'following' => false, 'msg' => '不能关注这个对象'];
    }
    if (follow_is($followerId, $type, $targetId)) {
        DB::delete('follows', 'follower_id = ? AND target_type = ? AND target_id = ?', [$followerId, $type, $targetId]);
        return ['ok' => true, 'following' => false, 'msg' => '已取消关注'];
    }
    DB::insert('follows', [
        'follower_id' => $followerId,
        'target_type' => $type,
        'target_id' => $targetId,
        'created_at' => now(),
    ]);
    return ['ok' => true, 'following' => true, 'msg' => '已关注'];
}

function follow_count($type, $targetId)
{
    $type = $type === 'category' ? 'category' : 'user';
    return (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('follows') . ' WHERE target_type = ? AND target_id = ?',
        [$type, (int) $targetId], 0);
}

/** 标签解析：最多 5 个，每个 20 字以内 */
function parse_tags($raw)
{
    $parts = preg_split('/[\s,，、#]+/u', (string) $raw) ?: [];
    $tags = [];
    foreach ($parts as $t) {
        $t = trim((string) $t);
        $t = trim($t, '#');
        if ($t === '' || mb_strlen($t) > 20) { continue; }
        $tags[] = $t;
        if (count($tags) >= 5) { break; }
    }
    return array_values(array_unique($tags));
}

function tags_to_string(array $tags)
{
    return implode(',', array_slice($tags, 0, 5));
}

function tags_of_post($post)
{
    return parse_tags((string) ($post['tags'] ?? ''));
}

function tag_url($tag)
{
    return page_url('tag', ['t' => $tag]);
}

/** 热门标签（扫描最近帖子，避免额外维护标签表） */
function hot_tags($limit = 20)
{
    $rows = DB::all('SELECT tags FROM ' . DB::table('posts') . " WHERE status = 1 AND tags <> '' ORDER BY id DESC LIMIT 500");
    $counts = [];
    foreach ($rows as $row) {
        foreach (parse_tags((string) $row['tags']) as $t) {
            $counts[$t] = ($counts[$t] ?? 0) + 1;
        }
    }
    arsort($counts);
    return array_slice($counts, 0, max(1, (int) $limit), true);
}

/** 草稿 */
function draft_save($userId, $title, $content, $catId, $kind = 'post', $media = [])
{
    $userId = (int) $userId;
    if ($userId <= 0) { return; }
    $kind = preg_replace('/[^a-z0-9_]/', '', (string) $kind);
    if ($kind === '') { $kind = 'post'; }
    $row = DB::one('SELECT id FROM ' . DB::table('drafts') . ' WHERE user_id = ? AND kind = ? ORDER BY updated_at DESC, id DESC LIMIT 1', [$userId, $kind]);
    $data = [
        'kind' => $kind,
        'title' => mb_substr((string) $title, 0, 120),
        'content' => (string) $content,
        'cat_id' => (int) $catId,
        'updated_at' => now(),
    ];
    if (isset($media['media_type'])) { $data['media_type'] = (string) $media['media_type']; }
    if (isset($media['media_path'])) { $data['media_path'] = (string) $media['media_path']; }
    if (isset($media['media_name'])) { $data['media_name'] = (string) $media['media_name']; }
    if (array_key_exists('extra', $media)) {
        $data['extra'] = is_string($media['extra']) ? $media['extra'] : json_encode($media['extra'], JSON_UNESCAPED_UNICODE);
    }
    if ($row) {
        DB::update('drafts', $data, 'id = ?', [(int) $row['id']]);
    } else {
        $data['user_id'] = $userId;
        DB::insert('drafts', $data);
    }
}

/** 删除指定类型的草稿，避免发帖时误删世界圈草稿 */
function draft_clear($userId, $kind = 'post')
{
    $userId = (int) $userId;
    $kind = preg_replace('/[^a-z0-9_]/', '', (string) $kind);
    if ($userId <= 0 || $kind === '') { return; }
    DB::delete('drafts', 'user_id = ? AND kind = ?', [$userId, $kind]);
}

/** @提及通知；返回提及到的用户数 */
function notify_mentions($content, $fromId, $postId, $link = '')
{
    $plain = strip_tags((string) $content);
    if (!preg_match_all('/@([\p{L}\p{N}_\-]{2,20})/u', $plain, $m)) { return 0; }
    $sent = 0;
    foreach (array_unique($m[1]) as $name) {
        $u = user_by_username($name);
        if (!$u) {
            $u = DB::one('SELECT * FROM ' . DB::table('users') . ' WHERE nickname = ? AND status = 1 ORDER BY id ASC LIMIT 1', [$name]);
        }
        if (!$u || (int) $u['id'] === (int) $fromId || (int) $u['status'] !== 1) { continue; }
        $me = current_user();
        $contentText = ($me ? display_name($me) : '有人') . ' 在帖子里提到了你';
        notification_insert((int) $u['id'], (int) $fromId, 'mention', (int) $postId, $contentText, $link);
        $sent++;
    }
    return $sent;
}

/** 带跳转链接的通知 */
function notification_insert($toUserId, $fromId, $type, $targetId, $content, $link = '')
{
    if (!$toUserId || $toUserId == $fromId) { return; }
    DB::insert('notifications', [
        'user_id' => (int) $toUserId,
        'from_id' => (int) $fromId,
        'type' => (string) $type,
        'target_id' => (int) $targetId,
        'content' => mb_substr((string) $content, 0, 200),
        'link' => mb_substr((string) $link, 0, 255),
        'is_read' => 0,
        'created_at' => now(),
    ]);
}

/** 存储配额：0 表示不限 */
function user_storage_used($userId, $kind = 'all')
{
    $userId = (int) $userId;
    $sum = 0;
    if ($kind === 'all' || $kind === 'netdisk') {
        $sum += (int) DB::val('SELECT COALESCE(SUM(size),0) FROM ' . DB::table('netdisk') . ' WHERE user_id = ?', [$userId], 0);
    }
    if ($kind === 'all' || $kind === 'gallery') {
        $sum += (int) DB::val('SELECT COALESCE(SUM(size),0) FROM ' . DB::table('gallery') . ' WHERE user_id = ?', [$userId], 0);
    }
    if ($kind === 'all' || $kind === 'attachment') {
        $sum += (int) DB::val('SELECT COALESCE(SUM(size),0) FROM ' . DB::table('attachments') . ' WHERE user_id = ?', [$userId], 0);
    }
    return $sum;
}

function user_storage_quota_bytes($userId, $kind = 'all')
{
    $key = $kind === 'netdisk' ? 'quota_netdisk_mb' : ($kind === 'gallery' ? 'quota_gallery_mb' : 'quota_attachment_mb');
    $mb = (int) setting($key, 0);
    if ($mb <= 0) {
        $userQuota = (int) DB::val('SELECT storage_quota_mb FROM ' . DB::table('users') . ' WHERE id = ?', [(int) $userId], 0);
        $mb = max(0, $userQuota);
    }
    return $mb > 0 ? $mb * 1024 * 1024 : 0;
}

function storage_quota_check($userId, $kind, $addBytes)
{
    $quota = user_storage_quota_bytes($userId, $kind);
    $addBytes = max(0, (int) $addBytes);
    if ($quota <= 0) { return [true, $quota, 0]; }
    if ($addBytes > 0) {
        $used = $kind === 'all' ? user_storage_used($userId, 'all') : user_storage_used($userId, $kind);
    } else {
        $used = $kind === 'all' ? user_storage_used($userId, 'all') : user_storage_used($userId, $kind);
    }
    return [$used + $addBytes <= $quota, $quota, $used];
}

/** 每日访问统计：PV / UV（UV 按会话每天一次） */
function analytics_track_view()
{
    if ((string) setting('analytics_enable', '1') !== '1') { return; }
    $page = (string) ($GLOBALS['PAGE'] ?? '');
    if ($page === 'admin' || $page === 'api') { return; }
    $day = date('Y-m-d');
    $uvKey = 'km_uv_' . $day;
    $isNewUv = empty($_SESSION[$uvKey]);
    try {
        $row = DB::one('SELECT * FROM ' . DB::table('analytics_daily') . ' WHERE day = ?', [$day]);
        if ($row) {
            DB::run('UPDATE ' . DB::table('analytics_daily') . ' SET pv = pv + 1, uv = uv + ? WHERE day = ?',
                [$isNewUv ? 1 : 0, $day]);
        } else {
            DB::insert('analytics_daily', ['day' => $day, 'pv' => 1, 'uv' => $isNewUv ? 1 : 0, 'posts' => 0, 'comments' => 0]);
        }
        if ($isNewUv) { $_SESSION[$uvKey] = 1; }
    } catch (Exception $e) {
    }
}

function analytics_bump($field)
{
    if (!in_array($field, ['posts', 'comments'], true)) { return; }
    $day = date('Y-m-d');
    try {
        $row = DB::one('SELECT day FROM ' . DB::table('analytics_daily') . ' WHERE day = ?', [$day]);
        if ($row) {
            DB::run('UPDATE ' . DB::table('analytics_daily') . ' SET ' . $field . ' = ' . $field . ' + 1 WHERE day = ?', [$day]);
        } else {
            DB::insert('analytics_daily', [
                'day' => $day, 'pv' => 0, 'uv' => 0,
                'posts' => $field === 'posts' ? 1 : 0,
                'comments' => $field === 'comments' ? 1 : 0,
            ]);
        }
    } catch (Exception $e) {
    }
}

/** 到点自动发布定时帖子 */
function post_publish_due()
{
    $last = (int) setting('post_publish_last_run', 0);
    if (time() - $last < 30) { return; }
    set_setting('post_publish_last_run', (string) time());
    try {
        $rows = DB::all('SELECT * FROM ' . DB::table('posts') . " WHERE status = 4 AND publish_at <> '' AND publish_at <= ? ORDER BY id ASC LIMIT 20", [now()]);
        foreach ($rows as $p) {
            DB::update('posts', ['status' => 1, 'updated_at' => now()], 'id = ?', [(int) $p['id']]);
            reward_points((int) $p['user_id'], 'post', (int) $p['id']);
            notify((int) $p['user_id'], 0, 'post_published', (int) $p['id'], '你的定时帖子《' . $p['title'] . '》已自动发布', page_url('post', ['id' => (int) $p['id']]));
        }
    } catch (Exception $e) {
    }
}

/** 主机指标：内存、磁盘、CPU */
function host_metrics($withSiteSize = true)
{
    $out = [
        'memory_total' => 0, 'memory_free' => 0, 'memory_used' => 0,
        'disk_total' => 0, 'disk_free' => 0, 'disk_used' => 0,
        'cpu_percent' => null, 'cpu_load' => null, 'cpu_cores' => 0,
        'site_size' => 0, 'os' => PHP_OS_FAMILY, 'php' => PHP_VERSION,
        'uptime' => '',
    ];
    $meminfo = @file_get_contents('/proc/meminfo');
    if ($meminfo && preg_match('/MemTotal:\s*(\d+)/i', $meminfo, $m)) {
        $out['memory_total'] = (int) $m[1] * 1024;
        if (preg_match('/MemAvailable:\s*(\d+)/i', $meminfo, $a)) {
            $out['memory_free'] = (int) $a[1] * 1024;
        } elseif (preg_match('/MemFree:\s*(\d+)/i', $meminfo, $f)) {
            $out['memory_free'] = (int) $f[1] * 1024;
        }
        $out['memory_used'] = max(0, $out['memory_total'] - $out['memory_free']);
    }
    $out['disk_total'] = @disk_total_space(APP_ROOT) ?: 0;
    $out['disk_free'] = @disk_free_space(APP_ROOT) ?: 0;
    $out['disk_used'] = max(0, $out['disk_total'] - $out['disk_free']);
    $cpuinfo = @file_get_contents('/proc/cpuinfo');
    if ($cpuinfo) { $out['cpu_cores'] = preg_match_all('/^processor\s*:/mi', $cpuinfo, $tmp); }
    if (function_exists('sys_getloadavg')) {
        $load = @sys_getloadavg();
        if (is_array($load) && isset($load[0])) { $out['cpu_load'] = (float) $load[0]; }
    }
    $uptime = @file_get_contents('/proc/uptime');
    if ($uptime) { $out['uptime'] = (int) floatval(explode(' ', trim($uptime))[0]); }
    if ($withSiteSize) { $out['site_size'] = host_dir_size(APP_ROOT, 20000); }
    return $out;
}

function host_dir_size($path, $limit = 20000)
{
    $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
    if (function_exists('exec') && !in_array('exec', $disabled, true)) {
        $out = [];
        $code = 0;
        @exec('du -sb ' . escapeshellarg($path) . ' 2>/dev/null', $out, $code);
        if ($code === 0 && isset($out[0])) {
            $first = trim((string) $out[0]);
            $bytes = (int) strtok($first, "\t ");
            if ($bytes > 0) { return $bytes; }
        }
    }
    $size = 0;
    $count = 0;
    try {
        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY);
        foreach ($it as $f) {
            if ($count++ > $limit) { break; }
            try {
                if ($f->isFile()) { $size += (int) $f->getSize(); }
            } catch (Throwable $e) {
            }
        }
    } catch (Throwable $e) {
    }
    return $size;
}
/** 采样一次 /proc/stat 的 CPU 忙闲计数 */
function host_cpu_sample()
{
    $line = @file_get_contents('/proc/stat');
    if (!$line || !preg_match('/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/m', $line, $m)) {
        return null;
    }
    $idle = (int) $m[4] + (int) $m[5];
    $total = 0;
    for ($i = 1; $i <= 7; $i++) { $total += (int) $m[$i]; }
    return ['idle' => $idle, 'total' => $total];
}

function host_cpu_percent($sampleMs = 300)
{
    $a = host_cpu_sample();
    if (!$a) { return null; }
    usleep(max(100, (int) $sampleMs) * 1000); // 至少采样 100ms，避免 100 秒级阻塞
    $b = host_cpu_sample();
    if (!$b) { return null; }
    $total = $b['total'] - $a['total'];
    $idle = $b['idle'] - $a['idle'];
    if ($total <= 0) { return null; }
    return round(max(0, min(100, (1 - $idle / $total) * 100)), 1);
}

/** 生成并发送邮箱验证码，供注册验证 / 邮箱验证使用 */
function issue_email_code($userId, $email, $purpose = 'verify_email')
{
    $email = trim((string) $email);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return [false, '邮箱格式不正确'];
    }
    $code = sprintf('%06d', random_int(0, 999999));
    DB::insert('email_codes', [
        'user_id' => (int) $userId,
        'email' => $email,
        'code' => $code,
        'purpose' => (string) $purpose,
        'expires_at' => time() + 600,
        'used' => 0,
    ]);
    $siteName = setting('site_name', '木漏茶室');
    $isLogin = in_array((string) $purpose, ['login_2fa', 'login_email_code'], true);
    $isDelete = in_array((string) $purpose, ['delete_account', 'admin_delete_account'], true);
    $isAdminDelete = (string) $purpose === 'admin_delete_account';
    $isBan = (string) $purpose === 'admin_ban_account';
    $isGuardUnban = (string) $purpose === 'admin_guard_unban';
    $mailTitle = $isLogin ? '登录验证码' : ($isDelete ? '删除账号验证码' : ($isBan ? '永久封禁验证码' : ($isGuardUnban ? '解除封禁验证码' : '邮箱验证码')));
    $mailIntro = $isLogin
        ? '你正在登录「' . $siteName . '」账号。请在登录页输入下面的验证码。'
        : ($isDelete
            ? ($isAdminDelete
                ? '你正在以管理员身份删除「' . $siteName . '」的一个账号。请在后台删除确认框输入下面的验证码。'
                : '你正在注销「' . $siteName . '」账号。请在注销确认框输入下面的验证码。')
            : ($isBan
                ? '你正在以管理员身份永久封禁「' . $siteName . '」的一个账号。请在用户主页或后台封禁确认框输入下面的验证码。'
                : ($isGuardUnban
                    ? '你正在以管理员身份解除「' . $siteName . '」木卫守护中的一条永久封禁记录。请在木卫守护解禁确认框输入下面的验证码。'
                    : '你正在验证「' . $siteName . '」账号的邮箱。请在验证页输入下面的验证码。')));
    $mailNote = $isDelete
        ? '验证码 10 分钟内有效。账号删除后可在后台“被删除账号恢复”中尝试恢复账号资料；若非本人操作，请立即修改密码并检查账号安全。'
        : ($isBan
            ? '验证码 10 分钟内有效。永久封禁会同时封禁该账号最近使用的 IP 与设备；若非本人操作，请立即修改密码并检查账号安全。'
            : ($isGuardUnban
                ? '验证码 10 分钟内有效。解禁后该 IP 或设备可以重新访问站点；若非本人操作，请立即修改密码并检查账号安全。'
                : '验证码 10 分钟内有效。若非本人操作，请忽略本邮件。'));
    $html = mail_verification_card([
        'site' => $siteName,
        'title' => $mailTitle,
        'intro' => $mailIntro,
        'code' => $code,
        'note' => $mailNote,
        'badge' => $isDelete ? 'DELETE ACCOUNT' : ($isLogin ? 'LOGIN CODE' : ($isBan ? 'PERMANENT BAN' : ($isGuardUnban ? 'UNBAN' : 'EMAIL CODE'))),
        'link' => full_url('index.php'),
        'link_label' => '打开木漏茶室',
    ]);
    list($ok, $msg) = send_mail($email, $siteName . ' ' . $mailTitle, $html);
    return [$ok, $ok ? '验证码已发送' : $msg];
}

/** 发送管理员操作验证码：验证码只发送到操作者当前绑定的邮箱 */
function account_delete_code_send($user, $purpose = 'delete_account')
{
    if (!$user) {
        return [false, '请先登录'];
    }
    $email = trim((string) ($user['email'] ?? ''));
    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return [false, '当前账号未绑定有效邮箱，无法发送验证码'];
    }
    if ((int) ($user['email_verified'] ?? 0) !== 1) {
        return [false, '当前绑定邮箱尚未验证，请先到认证中心完成邮箱验证'];
    }
    return issue_email_code((int) $user['id'], $email, (string) $purpose);
}

/** 校验管理员操作验证码，失败时给出明确提示 */
function account_delete_code_check($user, $code, $purpose = 'delete_account')
{
    $code = trim((string) $code);
    if (!preg_match('/^\d{6}$/', $code)) {
        return [false, '请输入 6 位数字邮箱验证码'];
    }
    if (!consume_email_code((int) ($user['id'] ?? 0), $code, (string) $purpose)) {
        return [false, '邮箱验证码错误或已过期，请重新获取'];
    }
    return [true, '验证码校验通过'];
}

/** 校验邮箱验证码并标记已使用 */
function consume_email_code($userId, $code, $purpose = 'verify_email')
{
    $row = DB::one('SELECT * FROM ' . DB::table('email_codes') . ' WHERE user_id = ? AND code = ? AND purpose = ? AND used = 0 AND expires_at > ? ORDER BY id DESC LIMIT 1',
        [(int) $userId, trim((string) $code), (string) $purpose, time()]);
    if (!$row) { return false; }
    DB::run('UPDATE ' . DB::table('email_codes') . ' SET used = 1 WHERE id = ?', [(int) $row['id']]);
    return true;
}

/** 用户担任版主的板块 ID 列表 */
function user_category_moderator_categories($userId)
{
    $rows = DB::all('SELECT id, moderators FROM ' . DB::table('categories') . " WHERE moderators <> ''");
    $ids = [];
    foreach ($rows as $r) {
        $list = array_filter(array_map('intval', preg_split('/[,，\s]+/u', (string) $r['moderators'])));
        if (in_array((int) $userId, $list, true)) { $ids[] = (int) $r['id']; }
    }
    return $ids;
}

function user_is_category_moderator($userId, $catId)
{
    $cat = DB::one('SELECT moderators FROM ' . DB::table('categories') . ' WHERE id = ?', [(int) $catId]);
    if (!$cat) { return false; }
    $list = array_filter(array_map('intval', preg_split('/[,，\s]+/u', (string) $cat['moderators'])));
    return in_array((int) $userId, $list, true);
}

/** 音频匹配临时令牌：自包含路径与上传者，刷新页面或会话变化后仍然可用。 */
function compose_audio_token_make($path, $uid, $ttl = 21600, $name = '')
{
    $payload = json_encode(['uid' => (int) $uid, 'exp' => time() + (int) $ttl,
        'path' => (string) $path, 'name' => (string) $name], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($payload === false) { $payload = '{}'; }
    $sig = hash_hmac('sha256', $payload, (string) cfg('key', 'komorebi-compose-audio'));
    return rtrim(strtr(base64_encode($payload), '+/', '-_'), '=') . '.' . substr($sig, 0, 32);
}

function compose_audio_token_parse($token)
{
    $token = trim((string) $token);
    $dot = strrpos($token, '.');
    if ($dot === false || $dot <= 0) { return null; }
    $encoded = substr($token, 0, $dot);
    $sig = substr($token, $dot + 1);
    $payload = base64_decode(strtr($encoded, '-_', '+/'), true);
    if ($payload === false || $payload === '') { return null; }
    $expect = substr(hash_hmac('sha256', $payload, (string) cfg('key', 'komorebi-compose-audio')), 0, 32);
    if (!hash_equals($expect, $sig)) { return null; }
    $data = json_decode($payload, true);
    if (!is_array($data)) { return null; }
    $uid = (int) ($data['uid'] ?? 0);
    $exp = (int) ($data['exp'] ?? 0);
    $path = (string) ($data['path'] ?? '');
    $name = (string) ($data['name'] ?? '');
    if ($uid <= 0 || $exp < time() || strpos($path, 'uploads/') !== 0 || strpos($path, '..') !== false) {
        return null;
    }
    return ['uid' => $uid, 'path' => $path, 'name' => ($name !== '' ? $name : basename($path))];
}

