SOURCE DOWNLOAD

木漏茶室源码下载中心

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

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

已经跑起来的木漏茶室

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

实时检测
2 个站点已部署

已展示全部 2 个站点。

api.php 73.2 KB · 发布包 v6.25.231
下载
<?php
/**
 * 轻量 API:上传、附件下载、网盘下载、聊天/私信轮询、图片代理、源码下载
 */
require __DIR__ . '/inc/bootstrap.php';

$contentLength = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
if ($contentLength > 0 && empty($_POST) && empty($_FILES)) {
    json_out(['ok' => false, 'msg' => '上传内容超过服务器允许的大小(post_max_size),请让主机调高限制后重试'], 413);
}

$action = strtolower((string) input('action', ''));

// 公开部署信息:源码下载中心实时读取站外站点名称、版本和 Logo,不需要共享令牌。
if ($action === 'deploy_public') {
    $origin = function_exists('source_deploy_origin') ? source_deploy_origin() : null;
    if (!$origin) {
        json_out(['ok' => false, 'msg' => '当前站点没有源码部署标识'], 404);
    }
    json_out(source_deploy_public_payload());
}

// 源码部署探针:只有从下载中心源码包安装的站点才会带 inc/deploy_origin.php。
if ($action === 'deploy_verify') {
    $origin = function_exists('source_deploy_origin') ? source_deploy_origin() : null;
    if (!$origin) {
        json_out(['ok' => false, 'msg' => '当前站点没有源码部署标识'], 404);
    }
    $token = trim((string) input('token', ''));
    if ($token === '' || !hash_equals((string) $origin['token'], $token)) {
        json_out(['ok' => false, 'msg' => '部署标识不匹配'], 403);
    }
    json_out([
        'ok' => true,
        'installed' => true,
        'token' => (string) $origin['token'],
        'site_name' => (string) setting('site_name', '木漏茶室'),
        'version' => defined('APP_VERSION') ? APP_VERSION : (string) ($origin['version'] ?? ''),
        'superadmin_email' => function_exists('source_deploy_superadmin_email') ? source_deploy_superadmin_email() : '',
        'logo_url' => function_exists('source_deploy_public_logo_url') ? source_deploy_public_logo_url() : '',
        'logo_type' => function_exists('source_deploy_public_logo_info') ? (string) (source_deploy_public_logo_info()['type'] ?? 'image') : 'image',
    ]);
}

if ($action === 'guard_refresh_report') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_out(['ok' => false, 'msg' => '请求方式不正确'], 405);
    }
    check_csrf();
    if (!realtime_guard_refresh_enabled()) {
        json_out(['ok' => true, 'enabled' => false]);
    }
    $trigger = preg_replace('/[^a-z_]/', '', strtolower((string) input('trigger', 'f12')));
    $labels = ['f12' => 'F12', 'shortcut' => '开发者工具快捷键', 'contextmenu' => '右键菜单'];
    if (!isset($labels[$trigger])) { $trigger = 'f12'; }
    $detail = trim((string) input('detail', ''));
    realtime_guard_event('rt_debug_refresh', '触发:' . $labels[$trigger] . ($detail !== '' ? ' · ' . mb_substr($detail, 0, 80) : ''));
    json_out(['ok' => true, 'enabled' => true, 'ip' => realtime_guard_ip(), 'trigger' => $trigger]);
}

if ($action === 'guard_report') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_out(['ok' => false, 'msg' => '请求方式不正确'], 405);
    }
    check_csrf();
    if (!realtime_guard_enabled()) {
        json_out(['ok' => true, 'enabled' => false]);
    }
    if (security_recent_count('rt_devtools', '', 60) >= 5) {
        json_out(['ok' => true, 'throttled' => true]);
    }
    $kind = preg_replace('/[^a-z_]/', '', strtolower((string) input('kind', 'devtools')));
    if (!in_array($kind, ['devtools', 'devtools_shortcut', 'devtools_resize'], true)) {
        $kind = 'devtools';
    }
    $detail = trim((string) input('detail', ''));
    realtime_guard_event('rt_devtools', $kind . ($detail !== '' ? ' · ' . mb_substr($detail, 0, 80) : ''));
    json_out(['ok' => true, 'enabled' => true]);
}

function api_require_login()
{
    if (!current_user()) {
        json_out(['ok' => false, 'msg' => '请先登录'], 401);
    }
    return current_user();
}

function api_csrf()
{
    check_csrf();
}

function api_stream_file($full)
{
    if (!is_file($full)) {
        http_response_code(404);
        exit;
    }
    $mime = 'application/octet-stream';
    if (function_exists('finfo_open')) {
        $fi = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($fi, $full) ?: $mime;
        finfo_close($fi);
    }
    $size = filesize($full);
    header('Content-Type: ' . $mime);
    header('Accept-Ranges: bytes');
    header('Content-Length: ' . $size);
    header('Cache-Control: private, max-age=3600');
    $start = 0;
    $end = $size - 1;
    if (isset($_SERVER['HTTP_RANGE']) && preg_match('/bytes=(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $m)) {
        if ($m[1] !== '') { $start = (int) $m[1]; }
        if ($m[2] !== '') { $end = (int) $m[2]; }
        if ($start > $end || $start >= $size) {
            http_response_code(416);
            header('Content-Range: bytes */' . $size);
            exit;
        }
        $end = min($end, $size - 1);
        http_response_code(206);
        header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
        header('Content-Length: ' . ($end - $start + 1));
    }
    if ($start > 0 || $end < $size - 1) {
        $fp = fopen($full, 'rb');
        fseek($fp, $start);
        $remain = $end - $start + 1;
        while ($remain > 0 && !feof($fp)) {
            $chunk = fread($fp, min(8192, $remain));
            echo $chunk;
            $remain -= strlen($chunk);
        }
        fclose($fp);
    } else {
        readfile($full);
    }
    exit;
}

// ---------- 后台删除账号:向当前操作管理员发送邮箱验证码 ----------
if ($action === 'admin_delete_send_code') {
    api_csrf();
    $admin = current_user();
    if (!$admin || !is_admin($admin)) {
        json_out(['ok' => false, 'msg' => '只有管理员可以发送删除验证码'], 403);
    }
    $uid = (int) input('uid');
    $target = user_by_id($uid);
    if (!$target) {
        json_out(['ok' => false, 'msg' => '账号不存在'], 404);
    }
    if ($uid === (int) $admin['id'] || is_superadmin($target) || (!is_superadmin($admin) && is_admin($target))) {
        json_out(['ok' => false, 'msg' => '当前账号不能执行删除操作']);
    }
    list($ok, $msg) = account_delete_code_send($admin, 'admin_delete_account');
    json_out([
        'ok' => (bool) $ok,
        'msg' => (string) $msg,
        'email_mask' => $ok ? email_mask((string) ($admin['email'] ?? '')) : '',
    ]);
}

// ---------- 永久封禁账号:向当前操作管理员发送邮箱验证码 ----------
if ($action === 'admin_ban_send_code') {
    api_csrf();
    $admin = current_user();
    if (!$admin || !is_admin($admin)) {
        json_out(['ok' => false, 'msg' => '只有管理员可以发送永久封禁验证码'], 403);
    }
    $uid = (int) input('uid');
    $target = user_by_id($uid);
    if (!$target) {
        json_out(['ok' => false, 'msg' => '账号不存在'], 404);
    }
    if ($uid === (int) $admin['id'] || !admin_can_delete_owner($target)) {
        json_out(['ok' => false, 'msg' => '当前账号不能对该用户执行永久封禁']);
    }
    list($ok, $msg) = account_delete_code_send($admin, 'admin_ban_account');
    json_out([
        'ok' => (bool) $ok,
        'msg' => (string) $msg,
        'email_mask' => $ok ? email_mask((string) ($admin['email'] ?? '')) : '',
    ]);
}

// ---------- 昵称即时检测(注册 / 个人资料输入框) ----------
if ($action === 'nickname_check') {
    api_csrf();
    $nickname = trim((string) input('nickname', ''));
    list($ok, $reason) = nickname_check($nickname, current_user());
    json_out([
        'ok' => (bool) $ok,
        'available' => (bool) $ok,
        'reason' => (string) $reason,
        'nickname' => $nickname,
    ]);
}

// ---------- 头像即时上传并自动检测 ----------
if ($action === 'avatar_check') {
    api_csrf();
    $scope = input('scope', 'register') === 'profile' ? 'profile' : 'register';
    if ($scope === 'profile') {
        api_require_login();
    }
    try {
        $path = '';
        $avatarData = (string) ($_POST['avatar_data'] ?? '');
        if ($avatarData !== '') {
            $path = save_avatar_data_url($avatarData);
        } elseif (!empty($_FILES['avatar_file']['name'])) {
            $stored = avatar_store_upload('avatar_file');
            $path = (string) ($stored['path'] ?? '');
        }
        if ($path === '') {
            json_out(['ok' => false, 'msg' => '没有选择头像文件'], 400);
        }
        $actor = current_user();
        $isAdminActor = $actor && is_admin($actor);
        $autoChecked = avatar_auto_check_enabled() && !$isAdminActor;
        if ($autoChecked) {
            list($autoBad, $autoReason, $autoScore) = avatar_auto_check($path);
        } else {
            $autoBad = false;
            $autoReason = '';
            $autoScore = 0;
        }
        if ($autoBad) {
            if (strpos($path, 'uploads/') === 0) {
                delete_upload($path);
            }
            json_out([
                'ok' => false,
                'auto_bad' => true,
                'reason' => (string) $autoReason,
                'score' => (int) $autoScore,
            ], 400);
        }
        avatar_stage_set($scope, $path);
        $ext = strtolower(pathinfo((string) parse_url($path, PHP_URL_PATH), PATHINFO_EXTENSION));
        json_out([
            'ok' => true,
            'path' => $path,
            'preview' => upload_url($path),
            'kind' => in_array($ext, avatar_video_extensions(), true) ? 'video' : 'image',
            'auto_checked' => $autoChecked,
            'bypass' => (bool) $isAdminActor,
            'reason' => '',
            'score' => (int) $autoScore,
            'limits' => ['image_mb' => avatar_max_mb('image'), 'video_mb' => avatar_max_mb('video')],
        ]);
    } catch (Exception $e) {
        json_out(['ok' => false, 'msg' => $e->getMessage()], 400);
    }
}

// ---------- 取消头像暂存 ----------
if ($action === 'avatar_clear') {
    api_csrf();
    $scope = input('scope', 'register') === 'profile' ? 'profile' : 'register';
    if ($scope === 'profile') {
        api_require_login();
    }
    avatar_stage_clear($scope);
    json_out(['ok' => true]);
}

if ($action === 'announcement_view') {
    api_csrf();
    $noticeId = (int) input('announcement_id');
    $notice = $noticeId > 0 ? announcement_by_id($noticeId) : null;
    $user = current_user();
    if (!$notice || (int) $notice['status'] !== 1 || !$user) {
        json_out(['ok' => true, 'count' => 0]);
    }
    $count = announcement_view_increment($noticeId, (int) $user['id']);
    json_out(['ok' => true, 'count' => $count]);
}

if ($action === 'location_suggest') {
    $me = api_require_login();
    $ip = client_ip();
    $loc = ip_location($ip);
    if (($loc['region'] ?? '') === '' || ($loc['region'] ?? '') === '本地') {
        json_out(['ok' => false, 'msg' => '当前网络无法自动定位,请手动填写']);
    }
    [$town, $village] = location_split_street_village($loc['street'] ?? '');
    json_out([
        'ok' => true,
        'province' => normalize_province_text($loc['region'] ?? ''),
        'city' => normalize_city_text($loc['city'] ?? ''),
        'district' => trim((string) ($loc['district'] ?? '')),
        'town' => $town,
        'village' => $village,
        'detail' => ip_location_detail_text($ip),
    ]);
}

// ---------- 公屏音乐下载(仅登录用户,按聊天消息 ID 取文件) ----------
if ($action === 'audio_download') {
    $me = api_require_login();
    if (feature_denied($me, 'download')) {
        http_response_code(403);
        exit('附件下载功能已被管理员关闭');
    }
    $id = (int) input('id');
    $row = DB::one('SELECT * FROM ' . DB::table('chat') . ' WHERE id = ? AND is_deleted = 0', [$id]);
    if (!$row || $row['type'] !== 'audio') {
        http_response_code(404);
        exit('音乐不存在或已删除');
    }
    $rel = audio_meta_local_path(audio_playable_url(upload_url($row['path'])));
    if ($rel === '') {
        http_response_code(404);
        exit('音乐文件已丢失');
    }
    $full = APP_ROOT . '/' . $rel;
    $meta = audio_track_meta($rel);
    $ext = strtolower((string) pathinfo($rel, PATHINFO_EXTENSION));
    if ($ext === '') {
        $ext = 'mp3';
    }
    $title = str_replace(['\\', '/', ':', '*', '?', '"', '<', '>', '|', "\r", "\n"], '_', (string) $meta['title']);
    $downloadName = ($title !== '' ? $title : '公屏音乐') . '.' . $ext;
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . filesize($full));
    header('Content-Disposition: attachment; filename="' . rawurlencode('audio.' . $ext) . '"; filename*=UTF-8\'\'' . rawurlencode($downloadName));
    header('X-Content-Type-Options: nosniff');
    readfile($full);
    exit;
}

// ---------- 音频信息(聊天大厅动态消息按需读取歌曲名 / 歌手) ----------
if ($action === 'audio_meta') {
    api_require_login();
    $src = trim((string) input('src', ''));
    if ($src === '') {
        json_out(['ok' => false, 'msg' => '缺少音频地址'], 400);
    }
    $meta = audio_track_meta($src);
    json_out(['ok' => true, 'title' => $meta['title'], 'artist' => $meta['artist'], 'cover' => $meta['cover'] ?? '', 'lyrics' => $meta['lyrics'] ?? '']);
}

// ---------- 网盘分享链接识别 ----------
if ($action === 'netdisk_parse') {
    api_require_login();
    api_csrf();
    try {
        $parsed = netdisk_parse_link((string) input('url', ''), (string) input('pwd', ''));
        json_out(array_merge(['ok' => true], $parsed));
    } catch (Exception $e) {
        json_out(['ok' => false, 'msg' => $e->getMessage()], 400);
    }
}

// ---------- 上传(编辑器 / 聊天 / 图床) ----------
if ($action === 'upload') {
    $me = api_require_login();
    api_csrf();
    $kind = (string) input('kind', 'image');
    if (!in_array($kind, ['image', 'file', 'audio', 'media', 'any'], true)) {
        $kind = 'image';
    }
    $mediaType = '';
    // 帖子文件统一上限:发帖编辑器插入正文的图片、视频、音频、任意文件共用此后台设置。
    $maxPost = upload_limit_bytes('upload_post_mb', 1000);
    try {
        if ($kind === 'image') {
            $stored = upload_store('file', 'images', ['image' => true, 'max' => $maxPost, 'max_label' => '帖子文件', 'allow' => image_upload_extensions()]);
            $view = image_make_compatible($stored['path']);
            if ($view && $view !== $stored['path']) {
                $stored['path'] = $view;
                $stored['name'] = preg_replace('/\.\w+$/', '.jpg', (string) $stored['name']);
                $stored['size'] = (int) @filesize(APP_ROOT . '/' . $view);
            }
        } elseif ($kind === 'audio') {
            $stored = upload_store('file', 'audio', [
                'max'   => $maxPost,
                'max_label' => '帖子文件',
                'allow' => chat_audio_extensions(),
                'mime_audio' => true,
            ]);
            $compatible = audio_make_compatible($stored['path']);
            if (!$compatible) {
                throw new Exception('音乐格式转换失败,请联系管理员确认服务器已安装 ffmpeg');
            }
            if ($compatible !== $stored['path']) {
                $stored['path'] = $compatible;
                $stored['name'] = preg_replace('/\.\w+$/', '.' . pathinfo($compatible, PATHINFO_EXTENSION), (string) $stored['name']);
                $stored['size'] = (int) @filesize(APP_ROOT . '/' . $compatible);
            }
        } elseif ($kind === 'media') {
            $stored = upload_store('file', 'files', [
                'max'   => $maxPost,
                'max_label' => '帖子文件',
                'allow' => chat_media_extensions(),
                'mime_media' => true,
            ]);
            $ext = strtolower(pathinfo($stored['name'], PATHINFO_EXTENSION));
            $mime = (string) (new finfo(FILEINFO_MIME_TYPE))->file(APP_ROOT . '/' . $stored['path']);
            $mediaType = media_kind_by_ext($ext);
            if ($mediaType === '') {
                if (strpos($mime, 'audio/') === 0) { $mediaType = 'audio'; }
                elseif (strpos($mime, 'video/') === 0) { $mediaType = 'video'; }
            } elseif ($mediaType === 'video' && strpos($mime, 'audio/') === 0) {
                $mediaType = 'audio';
            }
            if ($mediaType === '') {
                throw new Exception('不是可播放的视频或音乐文件');
            }
            $stored['path'] = chat_prepare_media($stored['path'], $mediaType);
            $stored['name'] = preg_replace('/\.\w+$/', '.' . pathinfo($stored['path'], PATHINFO_EXTENSION), (string) $stored['name']);
            $stored['size'] = (int) @filesize(APP_ROOT . '/' . $stored['path']);
        } elseif ($kind === 'any') {
            // 发帖编辑器统一拖拽框:所有格式都允许,危险扩展名由 upload_store 自动落盘为 .dat。
            $stored = upload_store('file', 'files', [
                'max'       => $maxPost,
                'max_label' => '帖子文件',
                'allow_all' => true,
            ]);
            $ext = strtolower(pathinfo($stored['name'], PATHINFO_EXTENSION));
            $mediaType = media_kind_by_ext($ext);
            if ($mediaType === '') {
                $mime = (string) (new finfo(FILEINFO_MIME_TYPE))->file(APP_ROOT . '/' . $stored['path']);
                if (strpos($mime, 'image/') === 0) { $mediaType = 'image'; }
                elseif (strpos($mime, 'audio/') === 0) { $mediaType = 'audio'; }
                elseif (strpos($mime, 'video/') === 0) { $mediaType = 'video'; }
            }
        } else {
            $stored = upload_store('file', 'files', [
                'max'   => $maxPost,
                'max_label' => '帖子文件',
                'allow' => array_merge(chat_media_extensions(),
                    ['zip','rar','7z','pdf','txt','md','doc','docx','xls','xlsx','ppt','pptx','apk']),
            ]);
            $ext = strtolower(pathinfo($stored['name'], PATHINFO_EXTENSION));
            $mediaType = media_kind_by_ext($ext);
            if ($mediaType !== '') {
                $stored['path'] = chat_prepare_media($stored['path'], $mediaType);
                $stored['name'] = preg_replace('/\.\w+$/', '.' . pathinfo($stored['path'], PATHINFO_EXTENSION), (string) $stored['name']);
                $stored['size'] = (int) @filesize(APP_ROOT . '/' . $stored['path']);
            }
        }
        if ($maxPost > 0) {
            $finalSize = (int) @filesize(APP_ROOT . '/' . $stored['path']);
            if ($finalSize > $maxPost) {
                if (strpos((string) $stored['path'], 'uploads/') === 0) { @unlink(APP_ROOT . '/' . $stored['path']); }
                throw new Exception('帖子文件超过上传上限,最大允许 ' . format_size($maxPost) . ',已驳回');
            }
            $stored['size'] = $finalSize > 0 ? $finalSize : (int) $stored['size'];
        }
        $audioToken = '';
        $audioTitle = '';
        $audioArtist = '';
        if ((string) input('compose', '') === '1'
            && ($mediaType === 'audio' || media_kind_by_name((string) $stored['name']) === 'audio')) {
            $audioToken = compose_audio_token_make((string) $stored['path'], (int) $me['id'], 21600, (string) $stored['name']);
            $trackMeta = audio_track_meta((string) $stored['path'], (string) $stored['name']);
            $audioTitle = (string) ($trackMeta['title'] ?? '');
            $audioArtist = (string) ($trackMeta['artist'] ?? '');
        }
        json_out([
            'ok'   => true,
            'url'  => full_url($stored['path']),
            'path' => $stored['path'],
            'name' => $stored['name'],
            'size' => $stored['size'],
            'type' => $mediaType,
            'audio_token' => $audioToken,
            'audio_title' => $audioTitle,
            'audio_artist' => $audioArtist,
        ]);
    } catch (Exception $e) {
        json_out(['ok' => false, 'msg' => $e->getMessage()], 400);
    }
}

// ---------- 帖子附件在线播放(自动转码副本) ----------
if ($action === 'attachment_media') {
    $me = api_require_login();
    if (feature_denied($me, 'download')) {
        http_response_code(403);
        exit('附件下载功能已被管理员关闭');
    }
    $id = (int) input('id');
    $att = DB::one('SELECT a.*, p.password, p.user_id, p.author_only, p.attach_visibility, p.attach_points,
                           p.id AS pid, p.status AS post_status
                     FROM ' . DB::table('attachments') . ' a
                     LEFT JOIN ' . DB::table('posts') . ' p ON p.id = a.post_id
                     WHERE a.id = ?', [$id]);
    if (!$att || (int) $att['post_status'] !== 1) {
        http_response_code(404);
        exit('附件不存在');
    }
    $postCtx = [
        'id' => (int) $att['pid'], 'user_id' => (int) $att['user_id'],
        'author_only' => (int) $att['author_only'],
        'attach_visibility' => (string) $att['attach_visibility'],
        'attach_points' => (int) $att['attach_points'],
    ];
    if (!post_content_visible($postCtx, 'attach', current_user())) {
        http_response_code(403);
        exit((int) ($postCtx['author_only'] ?? 0) === 1 && !post_privileged_can_view($postCtx, current_user())
            ? '此帖仅作者本人可见' : '请先回复本帖或支付积分解锁附件后再查看');
    }
    $hasPw = trim((string) $att['password']) !== '';
    if ($hasPw && !post_access_granted((int) $att['pid']) && !can_bypass_post_password($att, current_user())) {
        http_response_code(403);
        exit('请先在帖子页输入访问密码');
    }
    $kind = media_kind_by_name($att['name']);
    if (!in_array($kind, ['video', 'audio'], true)) {
        http_response_code(404);
        exit('不是音视频附件');
    }
    $play = media_playable_copy($att['path'], $kind);
    if (!$play) {
        http_response_code(404);
        exit('暂时无法播放该格式,请确认服务器已安装 ffmpeg');
    }
    api_stream_file(APP_ROOT . '/' . $play);
}

// ---------- 帖子附件下载 ----------
if ($action === 'attachment') {
    $me = api_require_login();
    if (feature_denied($me, 'download')) {
        http_response_code(403);
        exit('附件下载功能已被管理员关闭');
    }
    $id = (int) input('id');
    $att = DB::one('SELECT a.*, p.password, p.user_id, p.author_only, p.attach_visibility, p.attach_points,
                           p.id AS pid, p.status AS post_status
                     FROM ' . DB::table('attachments') . ' a
                     LEFT JOIN ' . DB::table('posts') . ' p ON p.id = a.post_id
                     WHERE a.id = ?', [$id]);
    if (!$att || (int) $att['post_status'] !== 1) {
        http_response_code(404);
        exit('附件不存在');
    }
    $postCtx = [
        'id' => (int) $att['pid'], 'user_id' => (int) $att['user_id'],
        'author_only' => (int) $att['author_only'],
        'attach_visibility' => (string) $att['attach_visibility'],
        'attach_points' => (int) $att['attach_points'],
    ];
    if (!post_content_visible($postCtx, 'attach', current_user())) {
        http_response_code(403);
        exit((int) ($postCtx['author_only'] ?? 0) === 1 && !post_privileged_can_view($postCtx, current_user())
            ? '此帖仅作者本人可见' : '请先回复本帖或支付积分解锁附件后再下载');
    }
    $hasPw = trim((string) $att['password']) !== '';
    if ($hasPw && !post_access_granted($att['pid']) && !can_bypass_post_password($att, current_user())) {
        http_response_code(403);
        exit('请先在帖子页输入访问密码');
    }
    $full = APP_ROOT . '/' . $att['path'];
    if (strpos($att['path'], 'uploads/') !== 0 || !is_file($full)) {
        http_response_code(404);
        exit('文件已丢失');
    }
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . rawurlencode($att['name']) . '"');
    header('Content-Length: ' . filesize($full));
    readfile($full);
    exit;
}

// ---------- 保存帖子图片 / 视频到自己的网盘 ----------
if ($action === 'save_world_media') {
    $me = api_require_login();
    if (feature_denied($me, 'netdisk')) {
        json_out(['ok' => false, 'msg' => '网盘功能已被管理员关闭'], 403);
    }
    api_csrf();
    $mid = (int) input('mid');
    try {
        $moment = DB::one('SELECT * FROM ' . DB::table('moments') . ' WHERE id = ?', [$mid]);
        if (!$moment || (int) ($moment['status'] ?? 0) !== 1) {
            throw new Exception('动态不存在或已删除');
        }
        if ((string) ($moment['media_type'] ?? '') !== 'voice' || trim((string) ($moment['media_path'] ?? '')) === '') {
            throw new Exception('这条动态没有可保存的音频');
        }
        $sourceRel = trim((string) $moment['media_path']);
        if (media_kind_by_name($sourceRel) !== 'audio') {
            throw new Exception('这个文件不是音频');
        }
        $meta = audio_track_meta_stored($moment);
        $title = trim((string) ($meta['title'] ?? ''));
        $artist = trim((string) ($meta['artist'] ?? ''));
        $ext = strtolower((string) pathinfo($sourceRel, PATHINFO_EXTENSION));
        $base = ($artist !== '' && $title !== '') ? ($artist . ' - ' . $title) : ($title !== '' ? $title : (string) ($moment['media_name'] ?? '世界圈音频'));
        $displayName = mb_substr($base, 0, 100, 'UTF-8') . ($ext !== '' ? '.' . $ext : '.mp3');
        $saved = netdisk_save_from_path((int) $me['id'], $sourceRel, $displayName);
        json_out([
            'ok' => true,
            'msg' => '已保存到我的网盘',
            'code' => $saved['code'],
            'name' => $saved['name'],
            'url' => full_url(page_url('netdisk', ['code' => $saved['code']])),
        ]);
    } catch (Exception $e) {
        json_out(['ok' => false, 'msg' => $e->getMessage()], 400);
    }
}

if ($action === 'save_post_media') {
    $me = api_require_login();
    if (feature_denied($me, 'netdisk')) {
        json_out(['ok' => false, 'msg' => '网盘功能已被管理员关闭'], 403);
    }
    api_csrf();
    $postId = (int) input('post_id');
    $attId = (int) input('attachment_id');
    $mediaUrl = trim((string) input('media_url'));
    try {
        $post = DB::one('SELECT * FROM ' . DB::table('posts') . ' WHERE id = ?', [$postId]);
        if (!$post || (int) $post['status'] !== 1) {
            throw new Exception('帖子不存在或已删除');
        }
        if (trim((string) $post['password']) !== '' && !post_access_granted($postId) && !can_bypass_post_password($post, $me)) {
            throw new Exception('请先在帖子页输入访问密码');
        }
        $isOwner = (int) $post['user_id'] === (int) $me['id'];
        $canPrivilegedSave = post_privileged_can_view($post, $me);
        if (!$isOwner && (int) ($post['author_only'] ?? 0) === 1 && !$canPrivilegedSave) {
            throw new Exception('此帖仅作者本人可见,无法保存内容');
        }
        if (!$isOwner && !$canPrivilegedSave && (int) ($post['allow_save_media'] ?? 1) !== 1) {
            throw new Exception('发布者未允许保存本帖的附件和图片、视频');
        }
        $sourceRel = '';
        $displayName = '';
        if ($attId > 0) {
            if (!$isOwner && !post_content_visible($post, 'attach', $me)) {
                throw new Exception('请先回复本帖或支付积分解锁附件后再保存');
            }
            $att = DB::one('SELECT * FROM ' . DB::table('attachments') . ' WHERE id = ? AND post_id = ?', [$attId, $postId]);
            if (!$att) {
                throw new Exception('附件不存在');
            }
            $sourceRel = (string) $att['path'];
            $displayName = (string) $att['name'];
            $saved = netdisk_save_from_path((int) $me['id'], $sourceRel, $displayName);
        } else {
            $sourceRel = local_upload_rel_from_url($mediaUrl);
            if ($sourceRel !== '') {
                $kind = media_kind_by_name($sourceRel);
                if ($kind === '') {
                    throw new Exception('这个文件不是可保存的媒体文件');
                }
                $ext = strtolower(pathinfo($sourceRel, PATHINFO_EXTENSION));
                $displayName = mb_substr((string) $post['title'] . ' - ' . ($kind === 'image' ? '图片' : ($kind === 'audio' ? '音频' : '视频')), 0, 90) . '.' . $ext;
                $saved = netdisk_save_from_path((int) $me['id'], $sourceRel, $displayName);
            } else {
                if (!preg_match('#^https?://#i', $mediaUrl)) {
                    throw new Exception('图片或视频地址无效');
                }
                $contentPlain = html_entity_decode((string) $post['content'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                if (strpos($contentPlain, $mediaUrl) === false) {
                    throw new Exception('这个媒体不在该帖正文中');
                }
                $kind = media_kind_by_name((string) parse_url($mediaUrl, PHP_URL_PATH));
                if ($kind === '') {
                    $kind = input('media_kind') === 'video' ? 'video' : 'image';
                }
                $displayName = mb_substr((string) $post['title'] . ' - ' . ($kind === 'video' ? '视频' : ($kind === 'audio' ? '音频' : '图片')), 0, 90);
                $saved = netdisk_save_from_url((int) $me['id'], $mediaUrl, $displayName);
            }
        }
        json_out([
            'ok' => true,
            'msg' => '已保存到我的网盘',
            'code' => $saved['code'],
            'name' => $saved['name'],
            'url' => full_url(page_url('netdisk', ['code' => $saved['code']])),
        ]);
    } catch (Exception $e) {
        json_out(['ok' => false, 'msg' => $e->getMessage()], 400);
    }
}


/** 音频匹配目标:网盘文件、帖子附件、世界圈音频。 */
function media_match_target_config($target)
{
    $target = (string) $target;
    if ($target === 'attachment') {
        return ['target' => 'attachment', 'table' => 'attachments', 'name_col' => 'name', 'rename' => false, 'label' => '帖子附件'];
    }
    if ($target === 'moment') {
        return ['target' => 'moment', 'table' => 'moments', 'name_col' => 'media_name', 'rename' => false, 'label' => '世界圈'];
    }
    if ($target === 'compose') {
        return ['target' => 'compose', 'table' => '', 'name_col' => 'name', 'rename' => false, 'label' => '发帖音频'];
    }
    return ['target' => 'netdisk', 'table' => 'netdisk', 'name_col' => 'name', 'rename' => true, 'label' => '网盘'];
}

/** 音频匹配:校验登录、归属权限、文件存在且为音频,返回记录与目标配置。 */
function media_match_require_audio($target, $id, $u)
{
    $cfg = media_match_target_config($target);
    if ($cfg['target'] === 'netdisk' && feature_denied($u, 'netdisk')) {
        json_out(['ok' => false, 'msg' => '网盘功能已被管理员关闭'], 403);
    }
    if ($cfg['target'] === 'compose') {
        $token = trim((string) $id);
        $rec = compose_audio_token_parse($token);
        if (!is_array($rec) || (int) $rec['uid'] !== (int) $u['id']) {
            json_out(['ok' => false, 'msg' => '上传记录已失效,请重新拖入音频'], 404);
        }
        $path = (string) $rec['path'];
        $name = (string) ($rec['name'] ?? basename($path));
        if (!is_file(APP_ROOT . '/' . $path) || media_kind_by_name($name) !== 'audio') {
            json_out(['ok' => false, 'msg' => '音频文件已丢失或不是音频'], 404);
        }
        $row = ['id' => $token, 'user_id' => (int) $u['id'], 'name' => $name, 'path' => $path,
            'lyrics' => '', 'cover_path' => '', 'matched_title' => '', 'matched_artist' => ''];
        $cfg['row'] = $row;
        $cfg['path'] = $path;
        $cfg['token'] = $token;
        return $cfg;
    }
    $row = DB::one('SELECT * FROM ' . DB::table($cfg['table']) . ' WHERE id = ?', [(int) $id]);
    if (!$row || ((int) $row['user_id'] !== (int) $u['id'] && !is_superadmin($u))) {
        json_out(['ok' => false, 'msg' => $cfg['label'] . '文件不存在,或你没有匹配权限'], 404);
    }
    $name = (string) ($row[$cfg['name_col']] ?? '');
    if (media_kind_by_name($name) !== 'audio') {
        json_out(['ok' => false, 'msg' => '只有歌曲/音频文件可以匹配歌词封面'], 400);
    }
    $path = (string) ($row['path'] ?? $row['media_path'] ?? '');
    $allowed = strpos($path, 'storage/drive/') === 0 || strpos($path, 'uploads/') === 0;
    if (!$allowed || !is_file(APP_ROOT . '/' . $path)) {
        json_out(['ok' => false, 'msg' => '音频文件已丢失'], 404);
    }
    $cfg['row'] = $row;
    $cfg['path'] = $path;
    return $cfg;
}

/** 兼容旧调用:网盘音频校验。 */
function drive_match_require_audio($id, $u)
{
    $cfg = media_match_require_audio('netdisk', $id, $u);
    return $cfg['row'];
}

function drive_match_clean_name_part($text, $max = 80)
{
    $text = trim((string) $text);
    $text = str_replace(["\0", "\r", "\n", '/', '\\'], '', $text);
    $text = preg_replace('/[\x00-\x1F\x7F]/u', '', $text);
    return mb_substr(trim($text), 0, $max, 'UTF-8');
}

// ---------- 网盘歌曲:手动搜索歌词与封面 ----------
if ($action === 'drive_match_search') {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        json_out(['ok' => false, 'msg' => '请用 POST 发起搜索'], 405);
    }
    check_csrf();
    $u = current_user();
    if (!$u) { json_out(['ok' => false, 'msg' => '请先登录'], 401); }
    $id = trim((string) input('id', ''));
    $target = (string) input('target', 'netdisk');
    $cfg = media_match_require_audio($target, $id, $u);
    $row = $cfg['row'];
    $fileName = (string) ($row[$cfg['name_col']] ?? '');
    $meta = audio_track_meta_stored($row);
    $title = trim((string) input('title', ''));
    $artist = trim((string) input('artist', ''));
    if ($title === '') { $title = trim((string) ($meta['title'] ?? '')); }
    if ($artist === '') { $artist = trim((string) ($meta['artist'] ?? '')); }
    if ($title === '') { $title = (string) pathinfo($fileName, PATHINFO_FILENAME); }
    $platform = audio_match_platform_key(input('platform', 'all'));
    $platformLabel = audio_match_platforms()[$platform] ?? '全部';
    $items = audio_match_search($title, $artist, 20, $platform);
    // 文件名常见「歌曲 - 歌手」和「歌手 - 歌曲」两种顺序;首次没有精确匹配时,自动按相反顺序再搜一次。
    $hasExact = false;
    foreach ($items as $item) {
        if (audio_match_norm((string) ($item['title'] ?? '')) === audio_match_norm($title)
            && audio_match_norm((string) ($item['artist'] ?? '')) === audio_match_norm($artist)) {
            $hasExact = true; break;
        }
    }
    if (!$hasExact && $artist !== '' && $title !== '') {
        $swapItems = audio_match_search($artist, $title, 20, $platform);
        $swapExact = false;
        foreach ($swapItems as $item) {
            if (audio_match_norm((string) ($item['title'] ?? '')) === audio_match_norm($artist)
                && audio_match_norm((string) ($item['artist'] ?? '')) === audio_match_norm($title)) {
                $swapExact = true; break;
            }
        }
        if ($swapExact || !$items) {
            $items = $swapItems;
            if ($items) { $swap = $title; $title = $artist; $artist = $swap; }
        }
    }
    if (!$items) {
        json_out(['ok' => false, 'msg' => '「' . $platformLabel . '」没有找到相关歌曲,换个搜索源或只填歌名再试', 'items' => [], 'platform' => $platform], 404);
    }
    if (!isset($_SESSION['media_match_searches']) || !is_array($_SESSION['media_match_searches'])) {
        $_SESSION['media_match_searches'] = [];
    }
    foreach ($_SESSION['media_match_searches'] as $oldKey => $old) {
        if (!is_array($old) || (int) ($old['at'] ?? 0) < time() - 600) { unset($_SESSION['media_match_searches'][$oldKey]); }
    }
    $matchKey = bin2hex(random_bytes(10));
    $_SESSION['media_match_searches'][$matchKey] = [
        'at' => time(),
        'uid' => (int) $u['id'],
        'target' => $cfg['target'],
        'file_id' => $id,
        'items' => $items,
    ];
    $publicItems = [];
    foreach ($items as $index => $item) {
        $publicItems[] = [
            'index' => $index,
            'title' => (string) ($item['title'] ?? ''),
            'artist' => (string) ($item['artist'] ?? ''),
            'album' => (string) ($item['album'] ?? ''),
            'year' => (string) ($item['year'] ?? ''),
            'cover_url' => (string) ($item['cover_url'] ?? ''),
            'cover_label' => (string) ($item['cover_label'] ?? ''),
            'has_lyrics' => !empty($item['has_lyrics']),
            'source' => (string) ($item['source'] ?? ''),
            'source_label' => (string) ($item['source_label'] ?? ''),
            'match_label' => (string) ($item['match_label'] ?? '相关推荐'),
        ];
    }
    json_out(['ok' => true, 'match_token' => $matchKey, 'items' => $publicItems, 'platform' => $platform,
        'platform_label' => $platformLabel, 'target' => $cfg['target'], 'query' => ['title' => $title, 'artist' => $artist]]);
}

// ---------- 网盘歌曲:应用手动选择的歌词封面 ----------
if ($action === 'drive_match_apply') {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        json_out(['ok' => false, 'msg' => '请用 POST 应用匹配'], 405);
    }
    check_csrf();
    $u = current_user();
    if (!$u) { json_out(['ok' => false, 'msg' => '请先登录'], 401); }
    $id = trim((string) input('id', ''));
    $target = (string) input('target', 'netdisk');
    $cfg = media_match_require_audio($target, $id, $u);
    $row = $cfg['row'];
    $fileName = (string) ($row[$cfg['name_col']] ?? '');
    $matchKey = trim((string) input('match_token', ''));
    $index = (int) input('candidate', -1);
    $ctx = $_SESSION['media_match_searches'][$matchKey] ?? null;
    if (!is_array($ctx) || (int) ($ctx['uid'] ?? 0) !== (int) $u['id'] || (string) ($ctx['file_id'] ?? '') !== (string) $id
        || (string) ($ctx['target'] ?? '') !== $cfg['target']
        || (int) ($ctx['at'] ?? 0) < time() - 600) {
        json_out(['ok' => false, 'msg' => '匹配结果已过期,请重新搜索'], 409);
    }
    $items = is_array($ctx['items'] ?? null) ? $ctx['items'] : [];
    if (!isset($items[$index]) || !is_array($items[$index])) {
        json_out(['ok' => false, 'msg' => '请选择一条搜索结果'], 422);
    }
    $candidate = $items[$index];
    $title = drive_match_clean_name_part((string) ($candidate['title'] ?? ''), 100);
    $artist = drive_match_clean_name_part((string) ($candidate['artist'] ?? ''), 80);
    if ($title === '') { json_out(['ok' => false, 'msg' => '搜索结果缺少歌曲名'], 422); }
    // 手动选择结果时,歌词和封面以选中结果为准;结果没有歌词/封面时清空旧值,避免旧信息残留。
    $lyrics = trim((string) ($candidate['lyrics'] ?? ''));
    $lyricsActive = $lyrics !== '';
    $coverRel = '';
    $coverActive = false;
    $coverUrl = trim((string) ($candidate['cover_url'] ?? ''));
    if ($coverUrl !== '' && audio_match_cover_url_allowed($coverUrl)) {
        $coverData = audio_match_http_binary($coverUrl, 8, 3145728);
        if ($coverData !== '' && audio_cover_info($coverData)) {
            $coverRel = audio_cover_cache_store($cfg['path'], $coverData);
            $coverActive = $coverRel !== '';
        }
    }
    if ($cfg['target'] === 'compose') {
        $msg = '已更新歌曲信息';
        if ($lyricsActive || $coverActive) {
            $msg = '已更新' . ($lyricsActive ? '歌词' : '') . ($lyricsActive && $coverActive ? '和' : '') . ($coverActive ? '封面' : '');
        }
        json_out(['ok' => true, 'msg' => $msg, 'compose' => true, 'token' => $cfg['token'],
            'path' => $cfg['path'], 'title' => $title, 'artist' => $artist,
            'lyrics' => $lyricsActive, 'lyrics_text' => $lyrics,
            'cover' => $coverActive, 'cover_url' => $coverActive ? full_url($coverRel) : '', 'cover_path' => $coverActive ? $coverRel : '']);
    }
    $rowId = (int) ($row['id'] ?? 0);
    $newName = $fileName;
    if ($cfg['rename']) {
        $ext = strtolower((string) pathinfo((string) $row['path'], PATHINFO_EXTENSION));
        if ($ext === '') { $ext = strtolower((string) pathinfo($fileName, PATHINFO_EXTENSION)); }
        $baseName = $artist !== '' ? ($artist . ' - ' . $title) : $title;
        $baseName = mb_substr(trim($baseName), 0, 100, 'UTF-8');
        if ($baseName === '') { $baseName = (string) pathinfo($fileName, PATHINFO_FILENAME); }
        $newName = $baseName . ($ext !== '' ? '.' . $ext : '');
        DB::run('UPDATE ' . DB::table($cfg['table']) . ' SET lyrics = ?, cover_path = ?, matched_title = ?, matched_artist = ?, matched_at = ?, name = ? WHERE id = ?',
            [$lyrics, $coverRel, mb_substr($title, 0, 200, 'UTF-8'), mb_substr($artist, 0, 200, 'UTF-8'), now(), mb_substr($newName, 0, 120, 'UTF-8'), $rowId]);
    } else {
        DB::run('UPDATE ' . DB::table($cfg['table']) . ' SET lyrics = ?, cover_path = ?, matched_title = ?, matched_artist = ?, matched_at = ? WHERE id = ?',
            [$lyrics, $coverRel, mb_substr($title, 0, 200, 'UTF-8'), mb_substr($artist, 0, 200, 'UTF-8'), now(), $rowId]);
    }
    $msg = '已更新歌曲信息';
    if ($lyricsActive || $coverActive) {
        $msg = '已更新' . ($lyricsActive ? '歌词' : '') . ($lyricsActive && $coverActive ? '和' : '') . ($coverActive ? '封面' : '') . ($cfg['rename'] ? '及文件名' : '');
    } else {
        $msg = $cfg['rename'] ? '已更新文件名,未获取到新的歌词或封面' : '已更新歌曲信息,未获取到新的歌词或封面';
    }
    json_out(['ok' => true, 'msg' => $msg, 'name' => $newName, 'lyrics' => $lyricsActive,
        'cover' => $coverActive, 'title' => $title, 'artist' => $artist,
        'lyrics_text' => $lyrics, 'cover_url' => $coverRel !== '' ? full_url($coverRel) : '',
        'cover_path' => $coverRel]);
}

// ---------- 网盘歌曲:一键匹配歌词与封面 ----------
if ($action === 'drive_match_audio') {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        json_out(['ok' => false, 'msg' => '请用 POST 发起匹配'], 405);
    }
    check_csrf();
    $u = current_user();
    if (!$u) {
        json_out(['ok' => false, 'msg' => '请先登录'], 401);
    }
    $id = trim((string) input('id', ''));
    $target = (string) input('target', 'netdisk');
    $platform = audio_match_platform_key(input('platform', 'all'));
    $platformLabel = audio_match_platforms()[$platform] ?? '全部';
    $matchMode = input('match', 'exact') === 'fuzzy' ? 'fuzzy' : 'exact';
    $cfg = media_match_require_audio($target, $id, $u);
    $row = $cfg['row'];
    $fileName = (string) ($row[$cfg['name_col']] ?? '');
    $meta = audio_track_meta_stored($row);
    $title = trim((string) ($meta['title'] ?? ''));
    $artist = trim((string) ($meta['artist'] ?? ''));
    if ($title === '') { $title = (string) pathinfo($fileName, PATHINFO_FILENAME); }
    $lyrics = trim((string) ($row['lyrics'] ?? ''));
    $coverRel = trim((string) ($row['cover_path'] ?? ''));
    if ($coverRel === '' && !empty($meta['cover'])) {
        $local = audio_meta_local_path((string) $meta['cover']);
        if ($local !== '' && is_file(APP_ROOT . '/' . $local)) { $coverRel = $local; }
    }
    if ($lyrics === '' && !empty($meta['lyrics'])) {
        $lyrics = (string) $meta['lyrics'];
    }
    $online = audio_match_online($title, $artist, $platform, $matchMode);
    if (($online['matched'] ?? 'none') === 'none') {
        json_out(['ok' => false, 'msg' => '「' . $platformLabel . '」没有精准匹配结果,请换一个平台或使用手动搜索', 'platform' => $platform], 422);
    }
    if (!empty($online['lyrics'])) { $lyrics = (string) $online['lyrics']; }
    if (!empty($online['cover_data'])) {
        $coverRel = audio_cover_cache_store($cfg['path'], (string) $online['cover_data']);
    }
    $matchedTitle = trim((string) ($online['lyrics_title'] ?? ''));
    $matchedArtist = trim((string) ($online['lyrics_artist'] ?? ''));
    if ($matchedTitle === '') { $matchedTitle = $title; }
    if ($matchedArtist === '') { $matchedArtist = $artist; }
    if ($cfg['target'] === 'compose') {
        json_out(['ok' => true, 'compose' => true, 'token' => $cfg['token'], 'path' => $cfg['path'],
            'title' => $matchedTitle, 'artist' => $matchedArtist,
            'lyrics' => $lyrics !== '', 'lyrics_text' => $lyrics,
            'cover' => $coverRel !== '', 'cover_url' => $coverRel !== '' ? full_url($coverRel) : '', 'cover_path' => $coverRel,
            'platform' => $platform, 'platform_label' => $platformLabel,
            'msg' => '「' . $platformLabel . '」精准匹配完成:' . ($lyrics !== '' ? '已获取歌词' : '未找到歌词') . ',' . ($coverRel !== '' ? '已获取封面' : '未找到封面')]);
    }
    DB::run('UPDATE ' . DB::table($cfg['table']) . ' SET lyrics = ?, cover_path = ?, matched_title = ?, matched_artist = ?, matched_at = ? WHERE id = ?',
        [$lyrics, $coverRel, mb_substr($matchedTitle, 0, 200, 'UTF-8'), mb_substr($matchedArtist, 0, 200, 'UTF-8'), now(), (int) ($row['id'] ?? 0)]);
    $msg = '「' . $platformLabel . '」精准匹配完成:' . ($lyrics !== '' ? '已获取歌词' : '未找到歌词') . ',' . ($coverRel !== '' ? '已获取封面' : '未找到封面');
    json_out([
        'ok' => true,
        'msg' => $msg,
        'lyrics' => $lyrics !== '',
        'cover' => $coverRel !== '',
        'title' => $title,
        'artist' => $artist,
        'platform' => $platform,
        'platform_label' => $platformLabel,
    ]);
}

// ---------- 网盘下载 / 原图 ----------
if ($action === 'drive_download' || $action === 'drive_raw' || $action === 'drive_play') {
    $u = current_user();
    if ($u && feature_denied($u, 'netdisk')) {
        http_response_code(403);
        exit('网盘功能已被管理员关闭');
    }
    $folderCode = strtoupper(trim((string) input('folder', '')));
    if ($folderCode !== '') {
        $folder = DB::one('SELECT * FROM ' . DB::table('netdisk_folders') . ' WHERE share_code = ?', [$folderCode]);
        if (!$folder) {
            http_response_code(404);
            exit('文件夹链接不存在或已失效');
        }
        $isOwner = $u && (int) ($u['id'] ?? 0) === (int) $folder['user_id'];
        if (!$isOwner && trim((string) ($folder['share_password'] ?? '')) !== '' && empty($_SESSION['drive_folder_pw'][$folderCode])) {
            http_response_code(403);
            exit('需要文件夹访问密码');
        }
        $fileId = (int) input('id', 0);
        $row = DB::one('SELECT * FROM ' . DB::table('netdisk') . ' WHERE id = ? AND user_id = ? AND folder_id = ?',
            [$fileId, (int) $folder['user_id'], (int) $folder['id']]);
        if (!$row) {
            http_response_code(404);
            exit('文件不在这个文件夹里');
        }
        $needPw = false;
    } else {
        $code = strtoupper((string) input('code', ''));
        $row = DB::one('SELECT * FROM ' . DB::table('netdisk') . ' WHERE share_code = ?', [$code]);
        if (!$row) {
            http_response_code(404);
            exit('提取码不存在');
        }
        $isOwner = $u && (int) ($u['id'] ?? 0) === (int) $row['user_id'];
        $needPw = !$isOwner && trim((string) $row['share_password']) !== '';
        if ($needPw && empty($_SESSION['drive_pw'][$code])) {
            http_response_code(403);
            exit('需要访问密码');
        }
    }
    $full = APP_ROOT . '/' . $row['path'];
    if (strpos($row['path'], 'storage/drive/') !== 0 || !is_file($full)) {
        http_response_code(404);
        exit('文件已丢失');
    }
    if ($action === 'drive_raw' && input('view') === '1') {
        $view = image_make_compatible($row['path']);
        if ($view) { $full = APP_ROOT . '/' . $view; }
    }
    if ($action === 'drive_play') {
        $kind = media_kind_by_name($row['name']);
        if (!in_array($kind, ['video', 'audio'], true)) {
            http_response_code(404);
            exit('不是音视频文件');
        }
        $play = media_playable_copy($row['path'], $kind);
        if ($play) { $full = APP_ROOT . '/' . $play; }
    }
    if ($action === 'drive_raw' || $action === 'drive_play') {
        $mime = 'application/octet-stream';
        if (function_exists('finfo_open')) {
            $fi = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($fi, $full) ?: $mime;
            finfo_close($fi);
        }
        $size = filesize($full);
        header('Content-Type: ' . $mime);
        // iOS Safari 更依赖文件名后缀判断音频格式,显式给 inline 文件名。
        $inlineName = preg_replace('/[\r\n\"]/', '', basename((string) $row['name']));
        header('Content-Disposition: inline; filename="' . $inlineName . '"');
        header('Accept-Ranges: bytes');
        header('Content-Length: ' . $size);
        $start = 0;
        $end = $size - 1;
        if (isset($_SERVER['HTTP_RANGE']) && preg_match('/bytes=(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $m)) {
            if ($m[1] !== '') { $start = (int) $m[1]; }
            if ($m[2] !== '') { $end = (int) $m[2]; }
            if ($start > $end || $start >= $size) {
                http_response_code(416);
                header('Content-Range: bytes */' . $size);
                exit;
            }
            $end = min($end, $size - 1);
            http_response_code(206);
            header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
            header('Content-Length: ' . ($end - $start + 1));
        }
        if ($start > 0 || $end < $size - 1) {
            $fp = fopen($full, 'rb');
            fseek($fp, $start);
            $remain = $end - $start + 1;
            while ($remain > 0 && !feof($fp)) {
                $chunk = fread($fp, min(8192, $remain));
                echo $chunk;
                $remain -= strlen($chunk);
            }
            fclose($fp);
        } else {
            readfile($full);
        }
        exit;
    }
    DB::run('UPDATE ' . DB::table('netdisk') . ' SET downloads = downloads + 1 WHERE id = ?', [$row['id']]);
    $downloadName = (string) $row['name'];
    $isMp3 = strtolower((string) pathinfo($downloadName, PATHINFO_EXTENSION)) === 'mp3';
    $tagPrefix = '';
    $tagSkip = 0;
    if ($isMp3) {
        $meta = audio_track_meta_stored($row);
        $tagPrefix = audio_mp3_tag_prefix($meta);
        if ($tagPrefix !== '') { $tagSkip = audio_mp3_tag_end($full); }
    }
    $fileSize = (int) filesize($full);
    $outSize = strlen($tagPrefix) + max(0, $fileSize - $tagSkip);
    header('Content-Type: ' . ($isMp3 ? 'audio/mpeg' : 'application/octet-stream'));
    header('Content-Disposition: attachment; filename="' . rawurlencode($downloadName) . '"');
    header('Content-Length: ' . $outSize);
    if ($tagPrefix !== '') { echo $tagPrefix; }
    $fp = fopen($full, 'rb');
    if ($tagSkip > 0) { fseek($fp, $tagSkip); }
    while (!feof($fp)) {
        $chunk = fread($fp, 8192);
        if ($chunk === false) { break; }
        echo $chunk;
    }
    fclose($fp);
    exit;
}

// ---------- 聊天大厅轮询 ----------
// ---------- 聊天大厅群语音(信令) ----------
function call_active()
{
    $row = DB::one('SELECT * FROM ' . DB::table('chat_calls') . " WHERE status = 'active' ORDER BY id DESC LIMIT 1");
    if (!$row) { return null; }
    if (strtotime($row['created_at']) < time() - 7200) {
        DB::run('UPDATE ' . DB::table('chat_calls') . " SET status = 'ended', ended_at = ? WHERE id = ?", [now(), $row['id']]);
        return null;
    }
    return $row;
}

function call_state_payload($me, $call, $since = 0)
{
    $members = DB::all('SELECT m.user_id, m.status, u.nickname, u.username FROM ' . DB::table('chat_call_members') . ' m
                         LEFT JOIN ' . DB::table('users') . ' u ON u.id = m.user_id
                         WHERE m.call_id = ? AND m.status = ?', [(int) $call['id'], 'joined']);
    $self = DB::one('SELECT * FROM ' . DB::table('chat_call_members') . ' WHERE call_id = ? AND user_id = ?', [(int) $call['id'], (int) $me['id']]);
    $joined = [];
    foreach ($members as $m) {
        $joined[] = ['uid' => (int) $m['user_id'], 'name' => display_name($m)];
    }
    $signals = [];
    $rows = DB::all('SELECT * FROM ' . DB::table('chat_signals') . ' WHERE call_id = ? AND to_id = ? AND id > ? ORDER BY id ASC LIMIT 80',
        [(int) $call['id'], (int) $me['id'], (int) $since]);
    foreach ($rows as $r) {
        $signals[] = ['id' => (int) $r['id'], 'from' => (int) $r['from_id'], 'kind' => $r['kind'], 'payload' => $r['payload']];
    }
    $host = DB::one('SELECT id, nickname, username FROM ' . DB::table('users') . ' WHERE id = ?', [(int) $call['host_id']]);
    return [
        'ok' => true,
        'call' => [
            'id' => (int) $call['id'],
            'host' => (int) $call['host_id'],
            'host_name' => $host ? display_name($host) : '茶客',
            'members' => $joined,
            'self' => $self ? $self['status'] : 'none',
        ],
        'signals' => $signals,
    ];
}

if ($action === 'call_state') {
    $me = api_require_login();
    $call = call_active();
    if (!$call) { json_out(['ok' => true, 'call' => null]); }
    json_out(call_state_payload($me, $call, 0));
}

if ($action === 'call_start') {
    $me = api_require_login();
    api_csrf();
    if (user_is_muted($me)) { json_out(['ok' => false, 'msg' => '你已被禁言,暂时不能发起语音通话']); }
    $call = call_active();
    if ($call) { json_out(['ok' => false, 'msg' => '聊天大厅正在通话中,请先结束当前通话']); }
    $id = DB::insert('chat_calls', ['host_id' => (int) $me['id'], 'status' => 'active', 'created_at' => now(), 'ended_at' => '']);
    DB::insert('chat_call_members', ['call_id' => (int) $id, 'user_id' => (int) $me['id'], 'status' => 'joined', 'joined_at' => now()]);
    json_out(['ok' => true, 'call_id' => (int) $id]);
}

if ($action === 'call_join' || $action === 'call_decline') {
    $me = api_require_login();
    api_csrf();
    $call = call_active();
    if (!$call) { json_out(['ok' => false, 'msg' => '通话已结束']); }
    $status = $action === 'call_join' ? 'joined' : 'declined';
    $exist = DB::one('SELECT id FROM ' . DB::table('chat_call_members') . ' WHERE call_id = ? AND user_id = ?', [(int) $call['id'], (int) $me['id']]);
    if ($exist) {
        DB::run('UPDATE ' . DB::table('chat_call_members') . ' SET status = ?, joined_at = ? WHERE id = ?', [$status, now(), (int) $exist['id']]);
    } else {
        DB::insert('chat_call_members', ['call_id' => (int) $call['id'], 'user_id' => (int) $me['id'], 'status' => $status, 'joined_at' => now()]);
    }
    json_out(['ok' => true, 'call_id' => (int) $call['id'], 'members' => call_state_payload($me, $call, 0)['call']['members']]);
}

if ($action === 'call_leave') {
    $me = api_require_login();
    api_csrf();
    $call = call_active();
    if (!$call) { json_out(['ok' => true]); }
    if ((int) $call['host_id'] === (int) $me['id']) {
        DB::run('UPDATE ' . DB::table('chat_calls') . " SET status = 'ended', ended_at = ? WHERE id = ?", [now(), (int) $call['id']]);
    } else {
        DB::run('UPDATE ' . DB::table('chat_call_members') . ' SET status = ? WHERE call_id = ? AND user_id = ?', ['left', (int) $call['id'], (int) $me['id']]);
    }
    json_out(['ok' => true]);
}

if ($action === 'call_end') {
    $me = api_require_login();
    api_csrf();
    $call = call_active();
    if ($call && ((int) $call['host_id'] === (int) $me['id'] || is_admin($me))) {
        DB::run('UPDATE ' . DB::table('chat_calls') . " SET status = 'ended', ended_at = ? WHERE id = ?", [now(), (int) $call['id']]);
    }
    json_out(['ok' => true]);
}

if ($action === 'call_signal') {
    $me = api_require_login();
    api_csrf();
    $call = call_active();
    if (!$call) { json_out(['ok' => false, 'msg' => '通话已结束']); }
    $kind = (string) input('kind');
    if (!in_array($kind, ['offer', 'answer', 'candidate'], true)) { json_out(['ok' => false, 'msg' => '非法信令']); }
    $payload = (string) input('payload');
    if (strlen($payload) > 65535) { json_out(['ok' => false, 'msg' => '信令过大']); }
    $toId = (int) input('to_id');
    $fromJoined = DB::val('SELECT COUNT(*) FROM ' . DB::table('chat_call_members') . ' WHERE call_id = ? AND user_id = ? AND status = ?', [(int) $call['id'], (int) $me['id'], 'joined'], 0);
    $toJoined = DB::val('SELECT COUNT(*) FROM ' . DB::table('chat_call_members') . ' WHERE call_id = ? AND user_id = ? AND status = ?', [(int) $call['id'], $toId, 'joined'], 0);
    if (!$fromJoined || !$toJoined) { json_out(['ok' => false, 'msg' => '不在通话中']); }
    DB::insert('chat_signals', ['call_id' => (int) $call['id'], 'from_id' => (int) $me['id'], 'to_id' => $toId, 'kind' => $kind, 'payload' => $payload, 'created_at' => now()]);
    json_out(['ok' => true]);
}

if ($action === 'call_poll') {
    $me = api_require_login();
    $call = call_active();
    if (!$call) { json_out(['ok' => true, 'call' => null]); }
    json_out(call_state_payload($me, $call, (int) input('since', 0)));
}

// ---------- 个人资料:自动定位 ----------
if ($action === 'geo_locate') {
    $me = api_require_login();
    api_csrf();
    $lat = trim((string) input('lat'));
    $lon = trim((string) input('lon'));
    $out = ['province' => '', 'city' => '', 'district' => '', 'town' => '', 'village' => ''];
    $source = 'ip';

    if (is_numeric($lat) && is_numeric($lon)) {
        $url = 'https://nominatim.openstreetmap.org/reverse?format=jsonv2&addressdetails=1&zoom=18&accept-language=zh-CN&lat='
            . rawurlencode($lat) . '&lon=' . rawurlencode($lon);
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CONNECTTIMEOUT => 4,
                CURLOPT_TIMEOUT        => 7,
                CURLOPT_USERAGENT      => 'Komorebi-Forum/1.0 (profile location)',
                CURLOPT_HTTPHEADER     => ['Accept: application/json'],
            ]);
            $body = curl_exec($ch);
            curl_close($ch);
            $json = is_string($body) ? json_decode($body, true) : null;
            if (is_array($json) && !empty($json['address']) && is_array($json['address'])) {
                $a = $json['address'];
                $display = trim((string) ($json['display_name'] ?? ''));
                $province = location_addr_pick($a, ['state', 'province', 'region']);
                // city 只取真正的市 / 直辖市;county 常常是区县,误当市会让区县被清空。
                $city = location_addr_pick($a, ['city', 'municipality']);
                if ($city === '') {
                    $cityLike = location_addr_pick($a, ['county', 'city_district']);
                    if (preg_match('/(?:市|州|盟|地区)$/u', $cityLike)) { $city = $cityLike; }
                }
                $district = location_addr_pick($a, ['city_district', 'district', 'county', 'borough', 'suburb']);
                $town = location_addr_pick($a, ['town', 'township', 'ward', 'street']);
                $village = location_addr_pick($a, ['village', 'hamlet', 'neighbourhood', 'quarter', 'residential', 'allotments']);
                // 逆地理编码缺少细粒度字段时,从 display_name 的逗号分段中补齐。
                if (($city === '' || $district === '' || $town === '' || $village === '') && $display !== '') {
                    $parts = preg_split('/\s*[,,]\s*/u', $display);
                    foreach ($parts as $part) {
                        $part = trim($part);
                        if ($part === '') { continue; }
                        if ($district === '' && preg_match('/(?:区|县|旗|自治县|自治旗)$/u', $part)) { $district = $part; }
                        elseif ($town === '' && preg_match('/(?:街道|镇|乡|苏木)$/u', $part)) { $town = $part; }
                        elseif ($village === '' && preg_match('/(?:社区|村委会|居委会|村|嘎查)$/u', $part)) { $village = $part; }
                        elseif ($city === '' && preg_match('/(?:市|州|盟|地区)$/u', $part)
                            && $part !== $province && $part !== '中国') { $city = $part; }
                    }
                }
                if ($village === '' && $display !== ''
                    && preg_match('/[,,]\s*([^,,]{2,24}?(?:社区|村委会|居委会|村|嘎查))/u', $display, $vm)) {
                    $village = trim($vm[1]);
                }
                if ($village === '' && $town !== '') {
                    [$town, $village] = location_split_street_village($town);
                }
                if ($district === $city) { $district = ''; }
                if ($district !== '' && $town !== '' && mb_strpos($town, $district) === 0) {
                    $town = trim(mb_substr($town, mb_strlen($district)));
                }
                if ($village === $town || $village === $district || $village === $city) { $village = ''; }
                if ($province !== '' || $city !== '') {
                    $out = [
                        'province' => normalize_province_text($province),
                        'city'     => normalize_city_text($city),
                        'district' => $district,
                        'town'     => $town,
                        'village'  => $village,
                    ];
                    $source = 'gps';
                }
            }
        }
    }

    // 网络 IP 结果始终取一份,用于补齐 GPS 逆地理编码缺失的区县 / 街道 / 社区。
    $loc = ip_location(client_ip());
    $ipOut = ['province' => '', 'city' => '', 'district' => '', 'town' => '', 'village' => ''];
    $region = (string) ($loc['region'] ?? '');
    if ($region !== '' && $region !== '本地') {
        [$town, $village] = location_split_street_village($loc['street'] ?? '');
        $district = (string) ($loc['district'] ?? '');
        if ($district !== '' && $town !== '' && mb_strpos($town, $district) === 0) {
            $town = trim(mb_substr($town, mb_strlen($district)));
        }
        $ipOut = [
            'province' => normalize_province_text($region),
            'city'     => normalize_city_text((string) ($loc['city'] ?? '')),
            'district' => $district,
            'town'     => $town,
            'village'  => $village,
        ];
    }
    if ($source === 'gps') {
        foreach ($ipOut as $k => $v) {
            if (trim((string) ($out[$k] ?? '')) === '' && $v !== '') {
                $out[$k] = $v;
            }
        }
    } else {
        $out = $ipOut;
        $source = 'ip';
    }

    json_out(['ok' => true, 'source' => $source, 'location' => $out]);
}

// ---------- 聊天大厅:全员禁言开关(仅管理员 / 超级管理员) ----------
if ($action === 'chat_global_mute') {
    $me = api_require_login();
    if (!is_admin($me)) {
        json_out(['ok' => false, 'msg' => '只有管理员可以设置全员禁言'], 403);
    }
    $enabled = input('enabled', '0') === '1' ? '1' : '0';
    set_setting('chat_global_mute', $enabled);
    json_out(['ok' => true, 'global_mute' => $enabled === '1']);
}

if ($action === 'chat_unread') {
    $me = api_require_login();
    if (feature_denied($me, 'chat_room')) {
        json_out(['ok' => false, 'msg' => '聊天大厅功能已被管理员关闭'], 403);
    }
    $since = max(0, (int) input('since', 0));
    $latest = (int) DB::val('SELECT MAX(id) FROM ' . DB::table('chat') . ' WHERE is_deleted = 0', [], 0);
    $count = $since > 0
        ? (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('chat') . ' WHERE is_deleted = 0 AND id > ?', [$since], 0)
        : 0;
    json_out(['ok' => true, 'latest' => $latest, 'count' => min($count, 999)]);
}

if ($action === 'chat_list') {
    $me = api_require_login();
    if (feature_denied($me, 'chat_room')) {
        json_out(['ok' => false, 'msg' => '聊天大厅功能已被管理员关闭'], 403);
    }
    $since = (int) input('since', 0);
    $rows = DB::all('SELECT c.*, u.nickname, u.username, u.avatar, u.role, u.comment_bubble FROM ' . DB::table('chat') . ' c
                     LEFT JOIN ' . DB::table('users') . ' u ON u.id = c.user_id
                     WHERE c.is_deleted = 0 AND c.id > ? ORDER BY c.id ASC LIMIT 60', [$since]);
    $out = [];
    foreach ($rows as $r) {
        $out[] = [
            'id'      => (int) $r['id'],
            'uid'     => (int) $r['user_id'],
            'name'    => display_name($r),
            'avatar'  => avatar_of($r),
            'role'    => $r['role'],
            'bubble'  => comment_bubble_of($r),
            'mine'    => (int) $r['user_id'] === (int) $me['id'],
            'type'    => $r['type'],
            'content' => $r['content'],
            'voice_text' => (string) ($r['voice_text'] ?? ''),
            'audio_title' => $r['type'] === 'audio' ? audio_track_meta($r['path'])['title'] : '',
            'audio_artist' => $r['type'] === 'audio' ? audio_track_meta($r['path'])['artist'] : '',
            'audio_cover' => $r['type'] === 'audio' ? (audio_track_meta($r['path'])['cover'] ?? '') : '',
            'audio_lyrics_b64' => $r['type'] === 'audio' && !empty(audio_track_meta($r['path'])['lyrics']) ? base64_encode(audio_track_meta($r['path'])['lyrics']) : '',
            'path'    => $r['type'] !== 'text'
                ? (in_array($r['type'], ['audio', 'voice'], true)
                    ? audio_playable_url(upload_url($r['path']))
                    : ($r['type'] === 'video' ? video_playable_url(upload_url($r['path'])) : upload_url($r['path'])))
                : '',
            'time'    => date('m-d H:i', strtotime($r['created_at'])),
        ];
    }
    json_out(['ok' => true, 'items' => $out, 'last' => $rows ? (int) end($rows)['id'] : $since,
        'global_mute' => setting('chat_global_mute', '0') === '1']);
}

// ---------- 登录页用户名头像 ----------
if ($action === 'user_avatar') {
    $username = trim((string) input('username', ''));
    if ($username === '' || mb_strlen($username) > 20) {
        json_out(['ok' => false, 'avatar' => '']);
    }
    $user = null;
    if ($username !== '' && ctype_digit($username)) {
        $user = user_by_id((int) $username);
    }
    if (!$user) {
        $user = user_by_username($username);
    }
    if (!$user || (int) $user['status'] !== 1) {
        json_out(['ok' => false, 'avatar' => '']);
    }
    json_out(['ok' => true, 'avatar' => avatar_of($user), 'avatar_type' => avatar_media_kind($user), 'name' => display_name($user)]);
}

// ---------- 私信轮询 ----------
if ($action === 'msg_list') {
    $me = api_require_login();
    if (feature_denied($me, 'friends')) {
        json_out(['ok' => false, 'msg' => '好友与私信功能已被管理员关闭'], 403);
    }
    $peer = (int) input('peer', 0);
    $since = (int) input('since', 0);
    if ($peer <= 0) {
        json_out(['ok' => false, 'msg' => '会话无效'], 400);
    }
    DB::run('UPDATE ' . DB::table('messages') . ' SET is_read = 1 WHERE from_id = ? AND to_id = ? AND is_read = 0', [$peer, $me['id']]);
    $rows = DB::all('SELECT * FROM ' . DB::table('messages') . '
                     WHERE ((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?)) AND id > ?
                     ORDER BY id ASC LIMIT 50', [$me['id'], $peer, $peer, $me['id'], $since]);
    $out = [];
    foreach ($rows as $r) {
        $type = (string) ($r['type'] ?? 'text');
        $path = trim((string) ($r['path'] ?? ''));
        $playUrl = '';
        if ($path !== '') {
            $raw = upload_url($path);
            if ($type === 'audio' || $type === 'voice') { $playUrl = audio_playable_url($raw); }
            elseif ($type === 'video') { $playUrl = video_playable_url($raw); }
            else { $playUrl = $raw; }
        }
        $audioMeta = $type === 'audio' && $path !== '' ? audio_track_meta($path) : ['title' => '', 'artist' => ''];
        $out[] = [
            'id'      => (int) $r['id'],
            'mine'    => (int) $r['from_id'] === (int) $me['id'],
            'type'    => $type,
            'content' => $r['content'],
            'path'    => $playUrl,
            'audio_title' => $audioMeta['title'],
            'audio_artist' => $audioMeta['artist'],
            'audio_cover' => $audioMeta['cover'] ?? '',
            'audio_lyrics_b64' => !empty($audioMeta['lyrics']) ? base64_encode($audioMeta['lyrics']) : '',
            'time'    => date('m-d H:i', strtotime($r['created_at'])),
        ];
    }
    json_out(['ok' => true, 'items' => $out, 'last' => $rows ? (int) end($rows)['id'] : $since]);
}

// ---------- 好友列表轮询 ----------
if ($action === 'friend_list') {
    $me = api_require_login();
    if (feature_denied($me, 'friends')) {
        json_out(['ok' => false, 'msg' => '好友与私信功能已被管理员关闭'], 403);
    }
    json_out(['ok' => true, 'friends' => friend_list($me['id'])]);
}

// ---------- 未读数 ----------
if ($action === 'unread') {
    $me = api_require_login();
    json_out([
        'ok' => true,
        'pm' => (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('messages') . ' WHERE to_id = ? AND is_read = 0', [$me['id']], 0),
        'nt' => (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('notifications') . ' WHERE user_id = ? AND is_read = 0', [$me['id']], 0),
    ]);
}

// ---------- 图片代理(采集预览) ----------
if ($action === 'imgproxy') {
    $url = (string) input('url', '');
    if (!preg_match('#^https?://#i', $url)) {
        http_response_code(400);
        exit('bad url');
    }
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_CONNECTTIMEOUT => 6,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 4,
        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/*,*/*;q=0.8'],
    ]);
    $bin = curl_exec($ch);
    $type = strtolower((string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
    $http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($bin === false || $http >= 400 || strlen($bin) < 10 || strpos($type, 'image/') !== 0) {
        http_response_code(404);
        exit('not an image');
    }
    header('Content-Type: ' . $type);
    header('Cache-Control: public, max-age=3600');
    echo $bin;
    exit;
}

// ---------- 源码下载 ----------
if ($action === 'source_download' || $action === 'source_zip') {
    $sourceAccess = source_center_access_state();
    if (!$sourceAccess['allowed']) {
        http_response_code(403);
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        echo json_encode([
            'ok' => false,
            'error' => $sourceAccess['reason'] === 'disabled' ? '本站未开放源码下载中心' : ($sourceAccess['reason'] === 'login' ? '请先登录管理员账号' : ($sourceAccess['reason'] === 'role' ? '仅限管理员和超级管理员进入源码下载中心' : '请先完成邮箱验证')),
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $excludeDirs = ['storage', 'uploads', 'data', '.git', '.idea', 'node_modules', 'system'];
    $excludeFiles = ['config.php'];
    $allowed = function ($rel) use ($excludeDirs, $excludeFiles) {
        $rel = str_replace('\\', '/', $rel);
        if ($rel === '' || strpos($rel, '..') !== false) {
            return false;
        }
        foreach (explode('/', $rel) as $p) {
            if (in_array($p, $excludeDirs, true)) {
                return false;
            }
        }
        if (in_array(basename($rel), $excludeFiles, true)) {
            return false;
        }
        $full = realpath(APP_ROOT . '/' . $rel);
        return ($full !== false && strpos($full, realpath(APP_ROOT)) === 0) ? $full : false;
    };

    require_once APP_ROOT . '/inc/source_release.php';

    if ($action === 'source_download') {
        $rel = (string) input('file', '');
        if (!source_release_snapshot_rel_allowed($rel)) {
            http_response_code(404);
            exit('文件不存在');
        }
        try {
            $meta = source_release_snapshot_ensure();
            $entry = source_release_snapshot_stream($meta, $rel);
            if (!$entry) {
                http_response_code(404);
                exit('文件不存在');
            }
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($rel) . '"');
            header('Content-Length: ' . (int) $entry['size']);
            fpassthru($entry['stream']);
            fclose($entry['stream']);
            $entry['zip']->close();
            exit;
        } catch (Throwable $e) {
            http_response_code(500);
            exit('文件读取失败:' . $e->getMessage());
        }
    }

    if ($action === 'source_zip') {
        try {
            $meta = source_release_snapshot_ensure();
            $path = (string) $meta['path'];
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . basename($path) . '"');
            header('Content-Length: ' . filesize($path));
            header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
            header('Pragma: no-cache');
            header('Expires: 0');
            readfile($path);
            exit;
        } catch (Throwable $e) {
            http_response_code(500);
            exit('源码包发送失败:' . $e->getMessage());
        }
    }
}

json_out(['ok' => false, 'msg' => '未知接口'], 404);
主题