forum.php

<?php
/**
 * =====================================================================
 * FlatForum v2.8.5 极简单文件版 —— 单文件 PHP + SQLite 论坛
 * =====================================================================
 * 部署:
 *   1. 需要 PHP >= 7.4,启用 pdo_sqlite 扩展(默认自带)
 *   2. 将本文件放入站点目录,浏览器访问 forum.php
 *   3. 首次访问自动创建 data/forum.db 数据库与 uploads/ 目录
 *      (Linux 下如无写权限,请 chmod 775 data/ uploads/,并把属主设为 PHP 运行用户;
 *        切勿长期使用 777)
 *   4. 注册的第一个账号自动成为管理员
 *   5. 可选:与 index.php 同目录部署,访问站点根目录自动进入论坛
 *
 * 功能:
 *   - 注册 / 登录 / 退出(游客可浏览,发帖回复需登录;支持用户名或数字ID登录)
 *   - 三种角色:管理员(admin) / 普通用户(user) / 分区版主
 *   - 分区(板块)管理:管理员可增删分区、为每个分区指定版主
 *   - 发帖 / 回复 / 编辑 / 引用回复 / 分页 / 浏览计数
 *   - 普通用户可删除自己发布的主题与回复;版主可管理分区内容;管理员全站管理
 *   - 图片上传:发帖与回复均可附带多张图片(jpg/png/gif/webp)
 *     程序限额:单张 ≤5MB、单次 ≤9 张、合计 ≤40MB(顶部常量可调)
 *     另受 nginx client_max_body_size / PHP post_max_size 限制,需 ≥ 程序限额
 *   - 管理后台标签顺序:站点设置 / 用户管理 / 分区管理 / 备份维护
 *     站点设置含「安全自检」(数据库位置、目录保护、HTTPS、错误回显,支持一键修复
 *     与数据库站内/站外互迁);备份维护含一键导出备份与孤儿图片清理
 *   - 前台个人中心显示个人ID,可修改本人用户名与密码(改密需验证当前密码)
 *
 * v2.8.5 修订说明(基于 v2.8.4 加固版逐行审查后的修复版本)
 *
 * 一、数据库位置回到「站点内置」为默认
 *   - 全新部署默认写入 data/forum.db(与 LiteNote 一致的 data/ 集中存放思路)
 *   - 已迁移出站的老站点继续沿用 data/.dbpath 指针,不丢数据
 *   - 后台「安全自检」可在站内 / 站外之间双向迁移(VACUUM INTO 快照 + 校验 + 回滚)
 *
 * 二、修复清单
 *   P0 封禁即时生效:require_login() 改为判 cur_user(),被 status=0 的账号
 *      无法再发帖/回复(原实现只看 $_SESSION['uid'],封禁在发帖路径上不生效)
 *   P1 楼层号固化:replies 增加 floor 列,插入时取「当前最大楼层 + 1」,
 *      渲染直接读列值,删除与置顶都不再导致楼层号重排(历史数据一次性回填)
 *   P1 dir_size() 真正使用入参 $dir(原来忽略参数、恒扫 uploads)
 *   P1 注册首管理员改用 BEGIN IMMEDIATE(DEFERRED 事务在 WAL 下会遇到
 *      SQLITE_BUSY_SNAPSHOT,且 busy_timeout 不会重试该错误码)
 *   P2 CSP 去掉 script-src 的 'unsafe-inline':改用每请求 nonce,
 *      并把所有内联 onsubmit/onclick 改为 data-confirm / data-quote + 事件绑定
 *   P2 登录用户名大小写不敏感(与注册查重规则保持一致)
 *   P2 版主不可指派给被禁用户;后台 tab 白名单化
 *   P2 退出登录同时清除会话 Cookie
 *   P2 set_setting() 改为 UPDATE + INSERT OR IGNORE,兼容 SQLite < 3.24(无 UPSERT)
 *   P3 错误页提示的日志路径随数据库位置动态显示
 *   P3 正文长度上限 CONTENT_MAX_LEN,防超大帖子
 *   P3 备份打包后校验 ZipArchive 实际条目数
 *   P3 清理死代码 image_in_use()
 *
 * 部署必读(重要):
 *   1. 请务必禁止外部访问 data/ 目录:
 *      Apache: 本文件已自动生成 data/.htaccess(需 AllowOverride All 生效)
 *      nginx : 在 server 块中加入
 *              location ^~ /data/    { deny all; }
 *              location ~* \.(db|sqlite|log)$ { deny all; }
 *   2. 升级部署:直接覆盖 forum.php 即可,data/forum.db 与 uploads/ 原样保留。
 * =====================================================================
 */

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
date_default_timezone_set('Asia/Shanghai');
ini_set('display_errors', '0');
ini_set('log_errors', '1');

/* ---------- 上传限额(可按需调整) ---------- */
define('IMG_MAX_SIZE', 5 * 1024 * 1024);    // 单张上限 5MB
define('IMG_MAX_FILES', 9);                 // 单次最多 9 张
define('IMG_MAX_TOTAL', 40 * 1024 * 1024);  // 单次合计上限 40MB(早于「张数×单张」生效)
/* ---------- 登录防爆破 ---------- */
define('LOGIN_MAX_FAIL', 5);                // 同一 IP+账号 连续失败次数
define('LOGIN_LOCK_SEC', 900);              // 触发后锁定时长(秒)
/* ---------- 口令长度(bcrypt 只取前 72 字节,过长纯属 DoS 燃料) ---------- */
define('PW_MIN_LEN', 6);
define('PW_MAX_LEN', 200);
/* ---------- 正文长度上限(防超大帖子拖垮渲染与备份) ---------- */
define('CONTENT_MAX_LEN', 20000);
/* ---------- 反向代理 ----------
 * 默认 false:直接使用 REMOTE_ADDR,适合局域网自用与直连部署。
 * 若站点跑在「可信」反向代理 / CDN 之后,改为 true,程序才会采信
 * X-Forwarded-Proto / X-Forwarded-For;否则这些头可被客户端伪造。
 */
define('TRUST_PROXY', false);

function is_https() {
  if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') return true;
  if ((int)($_SERVER['SERVER_PORT'] ?? 0) === 443) return true;
  if (TRUST_PROXY && (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')) return true;
  return false;
}

session_set_cookie_params([
  'httponly' => true,
  'samesite' => 'Lax',
  'path'     => '/',
  'secure'   => is_https(),
]);
session_start();

/* ---------- 数据库位置 ----------
 * v2.8.5 起默认回到站点内置:data/forum.db
 * 兼容:既往已迁移站外的站点,data/.dbpath 仍然有效,继续读取站外库,不丢数据。
 * 想搬回站内:后台「站点设置 → 安全自检 → 搬回站内」一键完成。
 */
$FF_LEGACY_DB = __DIR__ . '/data/forum.db';
$FF_SAFE_DIR  = dirname(__DIR__) . '/flatforum_data';
$FF_PTR       = __DIR__ . '/data/.dbpath';          // 迁移后记录数据库实际位置
$FF_DB = null;
if (is_file($FF_PTR)) {
  $c = trim((string)@file_get_contents($FF_PTR));
  if ($c !== '' && is_file($c)) $FF_DB = $c;        // 指针有效才采用,失效则忽略
}
if ($FF_DB === null) $FF_DB = $FF_LEGACY_DB;        // 默认:站点内置
define('DB_FILE', $FF_DB);
define('UPLOAD_DIR', __DIR__ . '/uploads');
$ALLOW_IMG = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

/* ===================== 数据库初始化 ===================== */
if (!is_dir(dirname(DB_FILE))) @mkdir(dirname(DB_FILE), 0775, true);
$db = new PDO('sqlite:' . DB_FILE);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('PRAGMA foreign_keys = ON');
$db->exec('PRAGMA busy_timeout = 5000');                       // 并发写等待 5s
try { $db->exec('PRAGMA journal_mode = WAL'); } catch (Throwable $ex) {}   // 不支持时静默回退

$db->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS users (
  id         INTEGER PRIMARY KEY AUTOINCREMENT,
  username   TEXT NOT NULL UNIQUE,
  password   TEXT NOT NULL,
  role       TEXT NOT NULL DEFAULT 'user',   -- admin / user
  status     INTEGER NOT NULL DEFAULT 1,     -- 1=正常 0=禁止登录
  created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
SQL);
$db->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS forums (
  id           INTEGER PRIMARY KEY AUTOINCREMENT,
  name         TEXT NOT NULL,
  description  TEXT NOT NULL DEFAULT '',
  moderator_id INTEGER DEFAULT NULL,          -- 分区版主(users.id)
  sort         INTEGER NOT NULL DEFAULT 0,
  created_at   TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
SQL);
$db->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS topics (
  id         INTEGER PRIMARY KEY AUTOINCREMENT,
  forum_id   INTEGER NOT NULL REFERENCES forums(id) ON DELETE CASCADE,
  user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  title      TEXT NOT NULL,
  content    TEXT NOT NULL,
  views      INTEGER NOT NULL DEFAULT 0,
  sticky     INTEGER NOT NULL DEFAULT 0,        -- 1=置顶
  created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
SQL);
$db->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS replies (
  id         INTEGER PRIMARY KEY AUTOINCREMENT,
  topic_id   INTEGER NOT NULL REFERENCES topics(id) ON DELETE CASCADE,
  user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  content    TEXT NOT NULL,
  sticky     INTEGER NOT NULL DEFAULT 0,        -- 1=置顶(只影响排序,不影响楼层号)
  floor      INTEGER NOT NULL DEFAULT 0,        -- 楼层号,插入时固化
  created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
SQL);
$db->exec('CREATE INDEX IF NOT EXISTS idx_topics_forum ON topics(forum_id)');
$db->exec('CREATE INDEX IF NOT EXISTS idx_replies_topic ON replies(topic_id)');
$db->exec('CREATE INDEX IF NOT EXISTS idx_topics_user ON topics(user_id)');
$db->exec('CREATE INDEX IF NOT EXISTS idx_replies_user ON replies(user_id)');
/* 站点设置表(key/value) */
$db->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS settings (
  k     TEXT PRIMARY KEY,
  value TEXT NOT NULL DEFAULT ''
);
SQL);
/* 登录失败计数表(仅用于防爆破;新增表,不影响既有数据) */
$db->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS login_throttle (
  k        TEXT PRIMARY KEY,
  cnt      INTEGER NOT NULL DEFAULT 0,
  last_at  TEXT NOT NULL
);
SQL);

/* 老版本数据库兼容:为已存在的表补加 sticky / status / floor 列 */
$tk = array_column($db->query('PRAGMA table_info(topics)')->fetchAll(PDO::FETCH_ASSOC), 'name');
if (!in_array('sticky', $tk, true)) $db->exec('ALTER TABLE topics ADD COLUMN sticky INTEGER NOT NULL DEFAULT 0');
$rk = array_column($db->query('PRAGMA table_info(replies)')->fetchAll(PDO::FETCH_ASSOC), 'name');
if (!in_array('sticky', $rk, true)) $db->exec('ALTER TABLE replies ADD COLUMN sticky INTEGER NOT NULL DEFAULT 0');
if (!in_array('floor', $rk, true))  $db->exec('ALTER TABLE replies ADD COLUMN floor INTEGER NOT NULL DEFAULT 0');
$uk = array_column($db->query('PRAGMA table_info(users)')->fetchAll(PDO::FETCH_ASSOC), 'name');
if (!in_array('status', $uk, true)) $db->exec('ALTER TABLE users ADD COLUMN status INTEGER NOT NULL DEFAULT 1');

/* 楼层号一次性回填:老数据 floor=0 时按 (topic_id, id) 顺序重新编号 */
if (get_setting('floor_backfill', '') !== '1') {
  try {
    $db->exec("UPDATE replies SET floor = (SELECT COUNT(*) FROM replies r2 WHERE r2.topic_id = replies.topic_id AND r2.id <= replies.id) WHERE floor IS NULL OR floor = 0");
    set_setting('floor_backfill', '1');
  } catch (Throwable $ex) { /* 回填失败不阻断站点,仅楼层号沿用旧值 */ }
}

if (!is_dir(UPLOAD_DIR)) @mkdir(UPLOAD_DIR, 0775, true);
protect_data_dirs();                                            // 生成 .htaccess / index.html
@ini_set('error_log', dirname(DB_FILE) . '/php_errors.log');     // 错误写入受保护目录

/* ===================== 工具函数 ===================== */

/* 每请求 CSP nonce:让 script-src 可以去掉 'unsafe-inline'
 * 注意:style 仍有 30 处内联 style="" 属性(历史写法),nonce 无法覆盖属性,
 * 故 style-src 暂时保留 'unsafe-inline';脚本侧已全部 nonce 化。 */
function csp_nonce() {
  if (empty($GLOBALS['FF_NONCE'])) $GLOBALS['FF_NONCE'] = base64_encode(random_bytes(16));
  return $GLOBALS['FF_NONCE'];
}

function send_security_headers() {
  if (headers_sent()) return;
  $n = csp_nonce();
  header('X-Content-Type-Options: nosniff');
  header('X-Frame-Options: SAMEORIGIN');
  header('Referrer-Policy: strict-origin-when-cross-origin');
  header("Content-Security-Policy: default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'nonce-$n'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'");
  if (is_https()) header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}

/* 兜底错误页:不查库、不泄露绝对路径 */
function fatal_page() {
  if (!headers_sent()) header('HTTP/1.1 500 Internal Server Error');
  send_security_headers();
  $n  = csp_nonce();
  $lg = short_path(dirname(DB_FILE) . '/php_errors.log');
  echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8">';
  echo '<meta name="viewport" content="width=device-width,initial-scale=1"><title>服务器开小差了</title>';
  echo '<style nonce="' . $n . '">body{font:14px/1.7 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif;background:#f2f4f7;color:#222;margin:0;padding:40px 16px}';
  echo '.box{max-width:520px;margin:40px auto;background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:22px}';
  echo 'h1{font-size:18px;margin:0 0 10px}.hint{color:#6b7280;font-size:13px}</style></head><body><div class="box">';
  echo '<h1>⚠️ 服务器开小差了</h1><p class="hint">请求未能完成,请稍后重试。若持续出现,请联系管理员查看 <code>' . e($lg) . '</code>。</p>';
  echo '<p style="margin-top:16px"><a href="forum.php" style="color:#2563eb">返回首页</a></p></div></body></html>';
}

/* 目录访问保护:data/ 全面禁止;uploads/ 允许图片但禁止执行脚本与列目录 */
function protect_data_dirs($force = false) {
  $deny = "# FlatForum 自动生成:禁止直接访问\n"
        . "<IfModule mod_authz_core.c>\n  Require all denied\n</IfModule>\n"
        . "<IfModule !mod_authz_core.c>\n  Order allow,deny\n  Deny from all\n</IfModule>\n";
  $safe = "# FlatForum 自动生成:允许图片,禁止执行脚本与列目录\n"
        . "Options -Indexes -ExecCGI\n"
        . "AddType text/plain .php .php3 .php4 .php5 .phtml .pht .phar .inc .shtml\n"
        . "<IfModule mod_php.c>\n  php_flag engine off\n</IfModule>\n"
        . "<IfModule mod_php7.c>\n  php_flag engine off\n</IfModule>\n";
  $denyDirs = [dirname(DB_FILE)];
  if (is_dir(__DIR__ . '/data')) $denyDirs[] = __DIR__ . '/data';
  foreach ($denyDirs as $d) {
    if (!is_dir($d) && !@mkdir($d, 0775, true)) continue;
    if ($force) { @unlink($d . '/.htaccess'); @unlink($d . '/index.html'); }
    if (!is_file($d . '/.htaccess')) @file_put_contents($d . '/.htaccess', $deny);
    if (!is_file($d . '/index.html')) @file_put_contents($d . '/index.html', '');
  }
  if (is_dir(UPLOAD_DIR)) {
    if ($force) { @unlink(UPLOAD_DIR . '/.htaccess'); @unlink(UPLOAD_DIR . '/index.html'); }
    if (!is_file(UPLOAD_DIR . '/.htaccess')) @file_put_contents(UPLOAD_DIR . '/.htaccess', $safe);
    if (!is_file(UPLOAD_DIR . '/index.html')) @file_put_contents(UPLOAD_DIR . '/index.html', '');
  }
}

/* 统一时间源:PHP 时区(避免 SQLite 走系统时区导致入库时间与页面时间不一致) */
function now_sql() { return date('Y-m-d H:i:s'); }

function client_ip() {
  $ip = (string)($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
  if (TRUST_PROXY) {
    $fwd = trim((string)($_SERVER['HTTP_X_FORWARDED_FOR'] ?? ''));
    if ($fwd !== '') {
      $first = trim(explode(',', $fwd)[0]);
      if ($first !== '') $ip = $first;
    }
  }
  return $ip === '' ? '0.0.0.0' : $ip;
}

/* 用户名查重(大小写不敏感;SQLite 默认 UNIQUE 区分大小写) */
function username_taken($name, $exceptId = 0) {
  $c = (int)scalar('SELECT COUNT(*) FROM users WHERE username COLLATE NOCASE = ? AND id<>?', [$name, (int)$exceptId]);
  return $c > 0;
}

/* POST 体积超过服务器限制时,$_POST/$_FILES 会双双为空,需单独识别以免被误报为 CSRF 失败 */
function post_too_large() {
  $len = (int)($_SERVER['CONTENT_LENGTH'] ?? 0);
  if ($len <= 0) return false;
  if (!empty($_POST) || !empty($_FILES)) return false;
  $max = 0;
  foreach (['post_max_size', 'upload_max_filesize'] as $k) {
    $v = strtolower(trim((string)ini_get($k)));
    if ($v === '' || $v === '0') continue;
    $n = (int)$v;
    $u = substr($v, -1);
    $mul = $u === 'g' ? 1073741824 : ($u === 'm' ? 1048576 : ($u === 'k' ? 1024 : 1));
    $max = max($max, $n * $mul);
  }
  return $max > 0 && $len > $max;
}

/* ---------------- 登录限流 ---------------- */
function throttle_key($name) { return client_ip() . '|' . mb_strtolower(trim((string)$name)); }
function throttle_left($key) {           // 返回剩余锁定分钟数,0 表示未锁定
  $r = row('SELECT cnt,last_at FROM login_throttle WHERE k=?', [$key]);
  if (!$r) return 0;
  if ((int)$r['cnt'] < LOGIN_MAX_FAIL) return 0;
  $left = strtotime($r['last_at']) + LOGIN_LOCK_SEC - time();
  if ($left <= 0) { row('DELETE FROM login_throttle WHERE k=?', [$key]); return 0; }
  return (int)ceil($left / 60);
}
function throttle_fail($key) {
  $now = now_sql();
  /* 用 INSERT OR IGNORE + UPDATE 兼容旧版 SQLite(不依赖 UPSERT) */
  row('INSERT OR IGNORE INTO login_throttle(k,cnt,last_at) VALUES(?,0,?)', [$key, $now]);
  row('UPDATE login_throttle SET cnt=cnt+1, last_at=? WHERE k=?', [$now, $key]);
  row('DELETE FROM login_throttle WHERE last_at<?', [date('Y-m-d H:i:s', time() - 86400)]);   // 顺带清理一天前的记录
}
function throttle_clear($key) { row('DELETE FROM login_throttle WHERE k=?', [$key]); }

/* ---------------- 图片回收 ---------------- */
function extract_images($content) {
  if (preg_match_all('/\[img\](uploads\/\d{6}\/[A-Za-z0-9._-]+)\[\/img\]/', (string)$content, $m)) {
    return array_values(array_unique($m[1]));
  }
  return [];
}
function delete_image_file($rel) {
  if (!preg_match('#^uploads/\d{6}/[A-Za-z0-9._-]+$#', (string)$rel)) return false;   // 白名单,防穿越
  $abs = __DIR__ . '/' . $rel;
  if (!is_file($abs)) return false;
  if (!@unlink($abs)) return false;
  $dir = dirname($abs);
  $left = @scandir($dir);
  if (is_array($left) && count($left) <= 2) @rmdir($dir);   // 空目录回收
  return true;
}
function gc_orphan_images(array $paths) {
  $paths = array_values(array_unique(array_filter($paths)));
  if (!$paths) return;
  if (count($paths) > 200) $paths = array_slice($paths, 0, 200);   // 放宽到 200,降低漏回收概率
  $used = [];
  $cond = []; $args = [];
  foreach ($paths as $p) {
    $used[$p] = false;
    $cond[] = 'instr(content,?)>0';
    $args[] = '[img]' . $p . '[/img]';
  }
  $where = implode(' OR ', $cond);
  foreach (rows('SELECT content FROM topics WHERE ' . $where, $args) as $r) {
    foreach ($paths as $p) if (strpos($r['content'], '[img]' . $p . '[/img]') !== false) $used[$p] = true;
  }
  foreach (rows('SELECT content FROM replies WHERE ' . $where, $args) as $r) {
    foreach ($paths as $p) if (strpos($r['content'], '[img]' . $p . '[/img]') !== false) $used[$p] = true;
  }
  foreach ($used as $p => $inuse) {          // 全库确认无人引用才真正删文件
    if (!$inuse) delete_image_file($p);
  }
}
/* 删除主题(含其下回复)并回收图片 */
function delete_topic_with_images($id) {
  global $db;
  $imgs = [];
  $t = row('SELECT content FROM topics WHERE id=?', [(int)$id]);
  if ($t) $imgs = extract_images($t['content']);
  foreach (rows('SELECT content FROM replies WHERE topic_id=?', [(int)$id]) as $r) {
    $imgs = array_merge($imgs, extract_images($r['content']));
  }
  $started = false;
  try {
    $db->exec('BEGIN IMMEDIATE');
    $started = true;
    row('DELETE FROM replies WHERE topic_id=?', [(int)$id]);
    row('DELETE FROM topics WHERE id=?', [(int)$id]);
    $db->exec('COMMIT');
  } catch (Throwable $ex) {
    /* 只有事务确实开启过才 ROLLBACK:未开启时执行 ROLLBACK 会抛
       “no transaction is active”,反而把原始异常吃掉 */
    if ($started) { try { $db->exec('ROLLBACK'); } catch (Throwable $e2) {} }
    throw $ex;
  }
  gc_orphan_images($imgs);
}
function delete_reply_with_images($id) {
  $r = row('SELECT content FROM replies WHERE id=?', [(int)$id]);
  $imgs = $r ? extract_images($r['content']) : [];
  row('DELETE FROM replies WHERE id=?', [(int)$id]);       // 楼层号不重排
  gc_orphan_images($imgs);
}
function collect_forum_images($fid) {
  $imgs = [];
  foreach (rows('SELECT content FROM topics WHERE forum_id=?', [(int)$fid]) as $r) $imgs = array_merge($imgs, extract_images($r['content']));
  foreach (rows('SELECT r.content FROM replies r JOIN topics t ON t.id=r.topic_id WHERE t.forum_id=?', [(int)$fid]) as $r) $imgs = array_merge($imgs, extract_images($r['content']));
  return $imgs;
}
function collect_user_images($uid) {
  $imgs = [];
  foreach (rows('SELECT content FROM topics WHERE user_id=?', [(int)$uid]) as $r) $imgs = array_merge($imgs, extract_images($r['content']));
  foreach (rows('SELECT content FROM replies WHERE user_id=?', [(int)$uid]) as $r) $imgs = array_merge($imgs, extract_images($r['content']));
  return $imgs;
}
/* 新楼层号:当前主题内最大楼层 + 1(删除与置顶都不会改变既有楼层) */
function next_floor($topic_id) {
  $m = (int)scalar('SELECT COALESCE(MAX(floor),0) FROM replies WHERE topic_id=?', [(int)$topic_id]);
  return $m + 1;
}

/* ---------------- 备份与图片维护 ---------------- */
/* 长路径缩略显示:把站点目录/上级目录前缀替换为 …,手机上不再撑破布局 */
function short_path($p) {
  $p = (string)$p;
  foreach ([__DIR__, dirname(__DIR__)] as $root) {
    if ($root !== '' && $root !== '/' && strpos($p, $root) === 0) return '…' . substr($p, strlen($root));
  }
  return $p;
}
function human_size($b) {
  $b = (float)$b;
  foreach (['B', 'KB', 'MB', 'GB'] as $u) {
    if ($b < 1024 || $u === 'GB') return ($u === 'B' ? (int)$b : number_format($b, 1)) . ' ' . $u;
    $b /= 1024;
  }
  return number_format($b, 1) . ' GB';
}
/* 通用目录体积统计:真正使用入参 $dir(v2.8.4 中该函数忽略入参,恒扫 uploads) */
function scan_dir_files($dir) {
  $out = [];
  if (!is_dir($dir)) return $out;
  foreach ((@scandir($dir) ?: []) as $fn) {
    if ($fn === '.' || $fn === '..') continue;
    $p = rtrim($dir, '/') . '/' . $fn;
    if (is_dir($p)) { foreach (scan_dir_files($p) as $s) $out[] = $s; }
    elseif (is_file($p)) $out[] = $p;
  }
  return $out;
}
function dir_size($dir) {
  $s = 0;
  if (!is_dir($dir)) return 0;
  foreach (scan_dir_files($dir) as $f) $s += (int)@filesize($f);
  return $s;
}
/* 备份目录:位于数据库同级的 backups/(继承 data 的禁止访问规则) */
function backup_dir($create = true) {
  $d = dirname(DB_FILE) . '/backups';
  if (!is_dir($d)) {
    if (!$create || !@mkdir($d, 0775, true)) return null;
  }
  if (!is_file($d . '/.htaccess')) {
    @file_put_contents($d . '/.htaccess',
      "# FlatForum 自动生成:备份目录禁止直接访问(下载请走后台“备份维护”)\n"
      . "<IfModule mod_authz_core.c>\n  Require all denied\n</IfModule>\n"
      . "<IfModule !mod_authz_core.c>\n  Order allow,deny\n  Deny from all\n</IfModule>\n");
  }
  if (!is_file($d . '/index.html')) @file_put_contents($d . '/index.html', '');
  return $d;
}
function backup_name_ok($f) {
  return (bool)preg_match('/^(db|backup)-\d{8}-\d{6}\.(sqlite|zip)$/', (string)$f);
}
/* 列出 uploads 下所有图片(相对路径),严格白名单,防目录穿越 */
function scan_upload_files() {
  $out = [];
  if (!is_dir(UPLOAD_DIR)) return $out;
  foreach ((@scandir(UPLOAD_DIR) ?: []) as $sub) {
    if ($sub === '.' || $sub === '..' || !preg_match('/^\d{6}$/', (string)$sub)) continue;
    $d = UPLOAD_DIR . '/' . $sub;
    if (!is_dir($d)) continue;
    foreach ((@scandir($d) ?: []) as $fn) {
      if ($fn === '.' || $fn === '..') continue;
      $rel = 'uploads/' . $sub . '/' . $fn;
      if (preg_match('#^uploads/\d{6}/[A-Za-z0-9._-]+$#', $rel) && is_file($d . '/' . $fn)) $out[] = $rel;
    }
  }
  return $out;
}
/* 全库收集仍被引用的图片(分块读取,避免大站一次载入全部正文) */
function collect_all_used_images() {
  $used = [];
  foreach (['topics', 'replies'] as $tbl) {          // 表名白名单
    $off = 0;
    while (true) {
      $rs = rows("SELECT content FROM $tbl WHERE instr(content,'[img]')>0 LIMIT 500 OFFSET ?", [(int)$off]);
      if (!$rs) break;
      foreach ($rs as $r) foreach (extract_images($r['content']) as $p) $used[$p] = true;
      if (count($rs) < 500) break;
      $off += 500;
    }
  }
  return $used;
}

/* 数据库位置互迁:站内 <-> 站外
 * 统一流程:VACUUM INTO 快照 -> 校验用户数 -> 落位 -> 更新/删除指针 -> 旧库改名
 * 任一步失败即回滚,不会静默建空库 */
function db_relocate($to) {
  global $db;
  $cur      = DB_FILE;
  $inWeb    = (strpos($cur, __DIR__) === 0);
  if ($to === 'inside'  && $inWeb)  return ['ok' => true, 'msg' => '数据库已在站点内(data/),无需迁移'];
  if ($to === 'outside' && !$inWeb) return ['ok' => true, 'msg' => '数据库已在站点目录之外,无需迁移'];

  $stamp   = date('Ymd-His');
  $dataDir = __DIR__ . '/data';
  if ($to === 'inside') {
    if (!is_dir($dataDir) && !@mkdir($dataDir, 0775, true)) return ['error' => '无法创建 data 目录,请检查权限'];
    $new = $dataDir . '/forum.db';
  } else {
    $safeDir = dirname(__DIR__) . '/flatforum_data';
    if (!is_dir($safeDir) && !@mkdir($safeDir, 0775, true)) return ['error' => '无法在站点上级目录创建 flatforum_data,请检查权限'];
    if (!is_writable($safeDir)) return ['error' => '目标目录不可写:' . short_path($safeDir)];
    $new = $safeDir . '/forum.db';
  }
  if (is_file($new)) $new = preg_replace('/\.db$/', '', $new) . '-' . $stamp . '.db';

  set_setting('maintenance', '1');                 // 迁移期间先停站,避免并发写入旧库
  $tmp = $new . '.tmp';
  @unlink($tmp);
  $ok = false;
  try { $db->exec('VACUUM INTO ' . $db->quote($tmp)); $ok = is_file($tmp); } catch (Throwable $ex) { $ok = false; }
  if (!$ok) {                                      // SQLite < 3.27:先落盘 WAL 再复制,否则会丢未 checkpoint 的事务
    try { $db->exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (Throwable $ex) {}
    @unlink($tmp); $ok = @copy($cur, $tmp);
  }
  if (!$ok) { @unlink($tmp); return ['error' => '数据库快照失败,请检查目标目录权限']; }

  try {                                            // 校验:新库能打开且用户数一致
    $t = new PDO('sqlite:' . $tmp);
    $t->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $a = (int)scalar('SELECT COUNT(*) FROM users');
    $b = (int)$t->query('SELECT COUNT(*) FROM users')->fetchColumn();
    $t = null;
    if ($a !== $b) { @unlink($tmp); return ['error' => '快照校验不一致,已中止迁移,数据未改动']; }
  } catch (Throwable $ex) {
    @unlink($tmp); return ['error' => '快照无法打开,已中止迁移,数据未改动'];
  }
  if (!@rename($tmp, $new)) { @unlink($tmp); return ['error' => '写入目标文件失败,已中止迁移']; }

  try { $db->exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (Throwable $ex) {}
  if ($to === 'outside') {
    if (!@file_put_contents($dataDir . '/.dbpath', $new)) { @unlink($new); return ['error' => '无法写入 data/.dbpath,已回滚']; }
  } else {
    @unlink($dataDir . '/.dbpath');                // 删指针:后续请求走默认站内路径
    protect_data_dirs(true);
  }
  $oldBak = $cur . '.moved-' . $stamp;
  $moved  = @rename($cur, $oldBak);
  @unlink($cur . '-wal'); @unlink($cur . '-shm');

  $msg  = ($to === 'inside' ? '数据库已搬回站点内:' : '数据库已迁到 Web 根目录之外:') . short_path($new);
  $msg .= $moved ? '(原文件已重命名为 ' . basename($oldBak) . ',确认无误后可删除)' : '(原文件未能自动改名,请手动处理)';
  $msg .= '。迁移期间已自动开启站点维护,确认论坛正常后请到「站点设置」关闭。';
  return ['ok' => true, 'msg' => $msg];
}

/* 生成备份:优先 SQLite VACUUM INTO(一致性快照),否则复制文件;有 ZipArchive 时连同图片打包 */
function make_backup() {
  global $db;
  $dir = backup_dir();
  if (!$dir) return ['error' => '无法创建备份目录,请检查数据目录权限'];
  $stamp = date('Ymd-His');
  $tmpDb = $dir . '/db-' . $stamp . '.sqlite';
  $ok = false;
  try { $db->exec('VACUUM INTO ' . $db->quote($tmpDb)); $ok = is_file($tmpDb); } catch (Throwable $ex) { $ok = false; }
  if (!$ok) {
    try { $db->exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (Throwable $ex) {}
    @unlink($tmpDb); $ok = @copy(DB_FILE, $tmpDb);
  }
  if (!$ok) { @unlink($tmpDb); return ['error' => '数据库备份失败,请检查数据目录权限']; }

  $res = ['file' => basename($tmpDb), 'size' => (int)@filesize($tmpDb), 'note' => ''];
  if (class_exists('ZipArchive')) {
    if (dir_size(UPLOAD_DIR) > 800 * 1024 * 1024) {
      $res['note'] = '图片目录超过 800MB,已跳过打包,仅备份数据库(图片请自行打包 uploads/)';
    } else {
      $zipPath = $dir . '/backup-' . $stamp . '.zip';
      $zip = new ZipArchive();
      if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
        $zip->addFile($tmpDb, 'forum.sqlite');
        $files = scan_upload_files();
        foreach ($files as $rel) $zip->addFile(__DIR__ . '/' . $rel, $rel);
        $zip->close();
        if (is_file($zipPath) && @filesize($zipPath) > 0) {
          /* 条目数校验:addFile 在 close() 才真正读取源文件,
             打包期间若文件被删会静默缺失,这里做一次总数核对 */
          $v = new ZipArchive();
          $got = -1;
          if ($v->open($zipPath) === true) { $got = $v->numFiles; $v->close(); }
          $want = 1 + count($files);
          if ($got !== $want) $res['note'] = '打包条目数 ' . $got . ',预期 ' . $want . ',可能有图片在打包期间被删除,建议重新生成';
          @unlink($tmpDb);
          $res = ['file' => basename($zipPath), 'size' => (int)@filesize($zipPath), 'note' => ($res['note'] ? $res['note'] : '已包含数据库与全部图片')];
        } else {
          @unlink($zipPath);
          $res['note'] = '打包失败,已仅备份数据库';
        }
      } else {
        $res['note'] = '无法创建 zip,已仅备份数据库';
      }
    }
  } else {
    $res['note'] = '服务器未启用 ZipArchive 扩展,仅备份数据库(图片请直接打包 uploads/ 目录)';
  }
  return $res;
}

function e($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function slen($s) { return function_exists('mb_strlen') ? mb_strlen($s) : strlen($s); }
function redirect($u) { while (ob_get_level() > 0) { @ob_end_clean(); } header('Location: ' . $u); exit; }
function flash($m, $ok = true) { $_SESSION['flash'] = $m; $_SESSION['flash_ok'] = $ok; }
function pull_flash() {
  if (!isset($_SESSION['flash'])) return null;
  $f = ['m' => $_SESSION['flash'], 'ok' => $_SESSION['flash_ok'] ?? true];
  unset($_SESSION['flash'], $_SESSION['flash_ok']);
  return $f;
}
function csrf() { if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16)); return $_SESSION['csrf']; }
function csrf_ok() { return isset($_POST['csrf'], $_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $_POST['csrf']); }

function row($sql, $args = []) { global $db; $st = $db->prepare($sql); $st->execute($args); return $st->fetch(PDO::FETCH_ASSOC); }
function rows($sql, $args = []) { global $db; $st = $db->prepare($sql); $st->execute($args); return $st->fetchAll(PDO::FETCH_ASSOC); }
function scalar($sql, $args = []) { global $db; $st = $db->prepare($sql); $st->execute($args); return $st->fetchColumn(); }

function cur_user() {
  if (empty($_SESSION['uid'])) return null;
  if (!array_key_exists('__user', $GLOBALS)) {
    $u = row('SELECT * FROM users WHERE id=?', [$_SESSION['uid']]);
    if (!$u || (int)$u['status'] === 0) {   // 被禁止的账号立即失效
      unset($_SESSION['uid']);
      $u = null;
    }
    $GLOBALS['__user'] = $u;
  }
  return $GLOBALS['__user'];
}
function user_row($id) { return row('SELECT * FROM users WHERE id=?', [(int)$id]); }
function forum_row($id) { return row('SELECT * FROM forums WHERE id=?', [(int)$id]); }

/* 站点设置(key/value 存 settings 表)
 * 用 UPDATE + INSERT OR IGNORE 而不是 UPSERT,兼容 SQLite < 3.24 */
function get_setting($k, $d = '') {
  $v = scalar('SELECT value FROM settings WHERE k=?', [$k]);
  return $v === false ? $d : (string)$v;
}
function set_setting($k, $v) {
  global $db;
  $st = $db->prepare('UPDATE settings SET value=? WHERE k=?');
  $st->execute([(string)$v, $k]);
  if ($st->rowCount() === 0) {
    $st2 = $db->prepare('INSERT OR IGNORE INTO settings(k,value) VALUES(?,?)');
    $st2->execute([$k, (string)$v]);
  }
}
function site_name() { $n = trim(get_setting('site_name', 'FlatForum')); return $n === '' ? 'FlatForum' : $n; }

/* 登录校验:必须拿到有效用户对象(含 status 检查),
   不能只看 $_SESSION['uid'] —— 否则被封禁账号仍可发帖 */
function require_login() { if (!cur_user()) { flash('请先登录', false); redirect('forum.php?p=login'); } }
function require_admin() { $u = cur_user(); if (!$u || $u['role'] !== 'admin') { flash('需要超级管理员权限', false); redirect('forum.php'); } }

/* 当前用户能否管理某分区:管理员=全部,版主=自己负责的分区 */
function can_manage($forum_id) {
  $u = cur_user();
  if (!$u) return false;
  if ($u['role'] === 'admin') return true;
  $f = forum_row($forum_id);
  return $f && $f['moderator_id'] && (int)$f['moderator_id'] === (int)$u['id'];
}

/* 正文渲染:转义 -> 引用行 -> 图片标签 -> 换行 */
function render_content($t) {
  $t = e($t);
  /* 引用回复块:行首 "> " 转为引用样式 */
  $t = (string)preg_replace('/^&gt; (.*)$/m', '<blockquote class="quote">$1</blockquote>', $t);
  $t = (string)preg_replace(
    '/\[img\](uploads\/[0-9]{6}\/[A-Za-z0-9._-]+)\[\/img\]/',
    '<a href="$1" target="_blank" rel="noopener"><img class="post-img" src="$1" alt="图片"></a>',
    $t
  );
  return nl2br($t);
}

/* 多图上传:成功返回 ['ok'=>[相对路径...]],失败返回 ['error'=>原因],未选图返回 null */
function upload_images() {
  if (empty($_FILES['images']) || !is_array($_FILES['images']['name'] ?? null)) return null;
  $oks = [];
  $err = null;
  $total = 0; $n = 0;
  foreach ($_FILES['images']['name'] as $i => $name) {
    $error = $_FILES['images']['error'][$i] ?? UPLOAD_ERR_NO_FILE;
    if ($error === UPLOAD_ERR_NO_FILE) continue;                    // 空位跳过
    $size = (int)($_FILES['images']['size'][$i] ?? 0);
    if ($error === UPLOAD_ERR_INI_SIZE || $error === UPLOAD_ERR_FORM_SIZE) {
      $err = '单张图片超过服务器上传上限(upload_max_filesize)'; break;
    }
    if (++$n > IMG_MAX_FILES) { $err = '单次最多上传 ' . IMG_MAX_FILES . ' 张图片'; break; }
    if ($size > IMG_MAX_SIZE) { $err = '单张图片不能超过 ' . round(IMG_MAX_SIZE / 1048576) . ' MB'; break; }
    $total += $size;
    if ($total > IMG_MAX_TOTAL) { $err = '本次图片总大小不能超过 ' . round(IMG_MAX_TOTAL / 1048576) . ' MB'; break; }
    $f = [
      'name'     => (string)$name,
      'tmp_name' => $_FILES['images']['tmp_name'][$i] ?? '',
      'error'    => $error,
      'size'     => $size,
    ];
    $r = upload_image_file($f);
    if (isset($r['error'])) { $err = $r['error']; break; }
    $oks[] = $r['ok'];
  }
  if ($err) {                                   // 任一环节失败:回滚本次已落盘的文件,避免孤儿图
    foreach ($oks as $p) delete_image_file($p);
    return ['error' => $err];
  }
  if (!$oks) return null;
  return ['ok' => $oks];
}

/* 单张图片校验+保存:成功返回 ['ok'=>相对路径],失败返回 ['error'=>原因] */
function upload_image_file($f) {
  if ($f['error'] !== UPLOAD_ERR_OK) return ['error' => '图片上传失败'];
  $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
  if (!in_array($ext, $GLOBALS['ALLOW_IMG'], true)) return ['error' => '仅支持 jpg / png / gif / webp 图片'];
  if (function_exists('finfo_open')) {
    $fi = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($fi, $f['tmp_name']);
    finfo_close($fi);
    if (!in_array($mime, ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], true)) return ['error' => '文件不是有效图片'];
  }
  $sub = date('Ym');
  $dir = UPLOAD_DIR . '/' . $sub;
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
  $name = $sub . '/' . bin2hex(random_bytes(8)) . '.' . $ext;
  if (!move_uploaded_file($f['tmp_name'], UPLOAD_DIR . '/' . $name)) return ['error' => '保存图片失败,请检查 uploads 目录权限'];
  return ['ok' => 'uploads/' . $name];
}

function pager($total, $per, $base) {
  $pages = max(1, (int)ceil($total / $per));
  $cur = min($pages, max(1, (int)($_GET['pg'] ?? 1)));
  $off = ($cur - 1) * $per;
  $sep = strpos($base, '?') === false ? '?' : '&';
  $h = '<div class="pager">';
  if ($cur > 1) $h .= '<a href="' . $base . $sep . 'pg=' . ($cur - 1) . '">上一页</a>';
  /* 只渲染窗口内的页码,页数极多时不再 O(pages) 空转 */
  $win = [];
  for ($i = 1; $i <= min(2, $pages); $i++) $win[$i] = true;
  for ($i = max(1, $pages - 1); $i <= $pages; $i++) $win[$i] = true;
  for ($i = max(1, $cur - 2); $i <= min($pages, $cur + 2); $i++) $win[$i] = true;
  $win = array_keys($win);
  sort($win, SORT_NUMERIC);
  $prev = 0;
  foreach ($win as $i) {
    if ($prev && $i - $prev > 1) $h .= '<span style="color:#6b7280">…</span>';
    if ($i === $cur) $h .= '<span class="cur">' . $i . '</span>';
    else $h .= '<a href="' . $base . $sep . 'pg=' . $i . '">' . $i . '</a>';
    $prev = $i;
  }
  if ($cur < $pages) $h .= '<a href="' . $base . $sep . 'pg=' . ($cur + 1) . '">下一页</a>';
  $h .= '<span class="total">共 ' . $total . ' 条</span></div>';
  return [$h, $off, $cur];
}

function role_badge($role) {
  if ($role === 'admin') return '<span class="badge role-admin">超级管理员</span>';
  if ($role === 'mod')   return '<span class="badge role-mod">版主</span>';
  return '<span class="badge role-user">普通用户</span>';
}

/* ===================== 页面布局 ===================== */
function page_header($title) {
  send_security_headers();
  $me = cur_user();
  $flash = pull_flash();
  $site = site_name();
  $n = csp_nonce();
  $css = <<<'CSS'
*{box-sizing:border-box;margin:0;padding:0}
body{font:14px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;background:#f2f4f7;color:#222}
a{color:#2563eb;text-decoration:none}
a:hover{text-decoration:underline}
.wrap{max-width:900px;margin:0 auto;padding:0 14px}
nav{background:#1f2937}
nav .wrap{display:flex;align-items:center;gap:18px;padding:11px 14px;flex-wrap:wrap}
nav .brand{font-weight:700;font-size:16px;color:#fff}
nav a{color:#cbd5e1}
nav a:hover{color:#fff}
nav .sp{flex:1}
.notice-bar{background:#fef3c7;border-bottom:1px solid #fde68a;color:#92400e;padding:8px 0;font-size:13px}
.notice-bar .wrap{display:flex;align-items:center;gap:8px}
main{padding:18px 0 30px}
h1{font-size:19px;margin:2px 0 12px}
h2{font-size:16px;margin:16px 0 10px}
h3{font-size:15px;margin-bottom:8px}
.card{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:16px;margin-bottom:14px}
.meta{color:#6b7280;font-size:12px;margin:2px 0 8px}
.hint{color:#6b7280;font-size:12px}
.content{word-break:break-word;overflow-wrap:break-word}
.post-img{max-width:100%;border-radius:8px;margin:8px 0;display:block}
.quote{background:#f8fafc;border-left:3px solid #cbd5e1;margin:6px 0;padding:8px 12px;color:#475569;border-radius:0 6px 6px 0;white-space:pre-wrap}
.flash{border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:14px}
.flash.ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#047857}
.flash.err{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c}
.btn{display:inline-block;background:#2563eb;color:#fff;border:0;border-radius:6px;padding:8px 16px;font-size:14px;cursor:pointer}
.btn:hover{background:#1d4ed8}
.btn.gray{background:#6b7280}
.btn.gray:hover{background:#4b5563}
.btn.danger{background:#dc2626}
.btn.danger:hover{background:#b91c1c}
.btn.small{padding:4px 10px;font-size:12px;border-radius:5px}
input[type=text],input[type=password],input[type=file],select,textarea{width:100%;border:1px solid #d1d5db;border-radius:7px;padding:9px 10px;font:inherit;background:#fff;color:#222}
textarea{min-height:130px;resize:vertical}
input:focus,textarea:focus,select:focus{outline:2px solid #bfdbfe;border-color:#2563eb}
label{display:block;margin:12px 0 5px;font-size:13px;font-weight:600;color:#374151}
form.inline{display:inline}
/* 按钮行:统一间距,替代原先靠空格分隔的写法 */
.btn-row{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}
.btn-row.none{margin-top:0}
code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#f1f5f9;border-radius:4px;padding:1px 5px;font-size:12px}
pre.code{background:#f8fafc;border:1px solid #e5e7eb;border-radius:6px;padding:10px;overflow:auto;font-size:12px;margin-top:8px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-all}
details{margin-top:8px}
summary{cursor:pointer;font-size:13px;font-weight:600;color:#374151;padding:2px 0}
summary:hover{color:#2563eb}
code.path{display:inline;word-break:break-all;overflow-wrap:anywhere;font-size:12px}
.forum-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:12px}
.forum-card{display:block;color:#222}
.forum-card:hover{text-decoration:none;border-color:#2563eb;box-shadow:0 2px 8px rgba(0,0,0,.06)}
.fname{font-size:16px;font-weight:700;margin-bottom:4px}
.fdesc{color:#6b7280;font-size:13px;margin-bottom:8px}
.fmeta{color:#6b7280;font-size:12px}
.topic-list .row{display:flex;justify-content:space-between;gap:12px;padding:11px 2px;border-bottom:1px solid #f1f3f5;align-items:baseline}
.topic-list .row:last-child{border-bottom:0}
.tt{font-size:15px;color:#1f2937;font-weight:500}
.tt:hover{color:#2563eb}
.badge{font-size:11px;border:1px solid currentColor;border-radius:11px;padding:1px 8px;vertical-align:1px;white-space:nowrap}
.sticky-tag{font-size:11px;color:#fff;background:#f59e0b;border-radius:4px;padding:1px 6px;vertical-align:1px;white-space:nowrap}
.role-admin{color:#dc2626}
.role-mod{color:#7c3aed}
.role-user{color:#6b7280}
.st-on{color:#16a34a}
.st-off{color:#dc2626}
.st-info{color:#2563eb}
.pager{display:flex;gap:6px;flex-wrap:wrap;align-items:center;margin:12px 0}
.pager a,.pager .cur{border:1px solid #d1d5db;border-radius:6px;padding:3px 10px;font-size:13px;color:#374151;background:#fff}
.pager a:hover{background:#eff6ff;text-decoration:none}
.pager .cur{background:#2563eb;color:#fff;border-color:#2563eb}
.pager .total{margin-left:auto;color:#6b7280;font-size:12px}
.crumbs{font-size:13px;color:#6b7280;margin-bottom:12px}
.reply{border-left:3px solid #e5e7eb}
.tabs{margin-bottom:14px;border-bottom:1px solid #e5e7eb;display:flex;gap:4px;flex-wrap:wrap}
.tabs a{padding:9px 16px;color:#4b5563;border-bottom:2px solid transparent;font-size:14px}
.tabs a.on{color:#2563eb;border-bottom-color:#2563eb;font-weight:600}
table.admin{width:100%;border-collapse:collapse;font-size:13px}
table.admin th{background:#f9fafb;text-align:left}
table.admin th,table.admin td{border:1px solid #e5e7eb;padding:8px 10px;vertical-align:middle}
footer{padding:18px 0 30px;color:#6b7280}
@media(max-width:560px){.forum-grid{grid-template-columns:1fr}.topic-list .row{flex-direction:column;gap:4px}.tabs a{padding:8px 12px}}
/* 手机端:后台表格转卡片 */
@media(max-width:640px){
  table.admin tr.head{display:none}
  table.admin tr{display:block;border:1px solid #e5e7eb;border-radius:8px;margin-bottom:10px;padding:8px 12px;background:#fff}
  table.admin td{display:flex;flex-wrap:wrap;align-items:center;gap:2px 10px;border:0!important;padding:6px 0;border-bottom:1px dashed #f0f2f5!important}
  table.admin td:last-child{border-bottom:0!important}
  table.admin td::before{content:attr(data-label);font-weight:600;color:#6b7280;font-size:12px;min-width:72px}
  table.admin td form.inline{margin-right:6px}
}
CSS;
  echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8">';
  echo '<meta name="viewport" content="width=device-width,initial-scale=1">';
  echo '<title>' . e($title) . ' - ' . e($site) . '</title><style nonce="' . $n . '">' . $css . '</style></head><body>';
  echo '<nav><div class="wrap">';
  echo '<a class="brand" href="forum.php">' . e($site) . '</a>';
  echo '<a href="forum.php">首页</a>';
  if ($me) {
    echo '<a href="forum.php?p=profile&id=' . $me['id'] . '">' . e($me['username']) . '</a>';
    if ($me['role'] === 'admin') echo '<a href="forum.php?p=admin">管理后台</a>';
    echo '<span class="sp"></span><a href="forum.php?p=logout&t=' . rawurlencode(csrf()) . '">退出</a>';
  } else {
    echo '<span class="sp"></span><a href="forum.php?p=login">登录</a>';
    if ((int)get_setting('register', '1') === 1) echo '<a href="forum.php?p=register">注册</a>';
  }
  echo '</div></nav>';
  if ((int)get_setting('notice_on', '0') === 1) {
    $nt = trim(get_setting('notice', ''));
    if ($nt !== '') echo '<div class="notice-bar"><div class="wrap">📢 ' . e($nt) . '</div></div>';
  }
  echo '<main><div class="wrap">';
  if ($flash) echo '<div class="flash ' . ($flash['ok'] ? 'ok' : 'err') . '">' . e($flash['m']) . '</div>';
}
function page_footer() {
  echo '</div></main><footer class="wrap">';
  /* 底部信息读取独立文件 footer.html(方便手动修改,支持 HTML);
     文件不存在或为空时回退到默认底部 */
  $ft = @file_get_contents(__DIR__ . '/footer.html');
  if ($ft === false || trim($ft) === '') {
    echo '<p class="hint">' . e(site_name()) . ' v2.8.5 极简单文件版 · 单文件 PHP + SQLite</p>';
  } else {
    echo $ft;
  }
  echo '</footer>';
  /* 内联脚本走每请求 nonce,替代原先的 onclick / onsubmit 内联处理器 */
  $n = csp_nonce();
  $js = <<<'JS'
(function(){
  function all(a){ return Array.prototype.slice.call(document.querySelectorAll('[' + a + ']')); }
  all('data-confirm').forEach(function(el){
    el.addEventListener('submit', function(ev){
      if (!window.confirm(el.getAttribute('data-confirm') || '确定继续?')) ev.preventDefault();
    });
  });
  all('data-quote').forEach(function(el){
    el.addEventListener('click', function(){ window.ffQuote(el); });
  });
})();
function ffQuote(b){
  var ta = document.getElementById('replyContent');
  if (!ta) return;
  var d;
  try { d = JSON.parse(b.getAttribute('data-quote')); } catch (err) { return; }
  var q = '> 引用 第' + d[0] + '楼 @' + d[1] + ':' + d[2] + '\n';
  var v = ta.value.replace(/\s+$/, '');
  ta.value = v ? v + '\n\n' + q : q;
  ta.focus();
}
JS;
  echo '<script nonce="' . $n . '">' . $js . '</script></body></html>';
}

/* ===================== 路由 ===================== */
ob_start();                       // 出错时可整体丢弃半成品页面,改出统一错误页
try {
$p = $_GET['p'] ?? 'home';

/* ---------- 站点维护模式:仅管理员可登录/访问 ---------- */
$MAINTENANCE = (int)get_setting('maintenance', '0') === 1;
if ($MAINTENANCE) {
  $me0 = cur_user();
  if (!$me0 || $me0['role'] !== 'admin') {
    $isLoginReq = ($_SERVER['REQUEST_METHOD'] === 'GET' && $p === 'login')
               || ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'login');
    if (!$isLoginReq) {
      page_header('站点维护中');
      echo '<div class="card"><h1>🔧 站点维护中</h1>';
      echo '<p class="hint">站点正在维护升级,暂时无法访问,请稍后再来。</p>';
      echo '<p style="margin-top:14px"><a class="btn" href="forum.php?p=login">管理员登录</a></p></div>';
      page_footer(); exit;
    }
  }
}

/* ---------- POST 动作 ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (post_too_large()) { flash('提交内容过大,已超出服务器 post_max_size / upload_max_filesize 限制,请压缩图片或减少数量后重试', false); redirect('forum.php'); }
  $action = $_POST['action'] ?? '';
  if (!csrf_ok()) { flash('页面已过期,请重试', false); redirect('forum.php'); }
  switch ($action) {
    case 'register': {
      if ((int)get_setting('register', '1') !== 1) { flash('注册功能已关闭,请联系管理员', false); redirect('forum.php'); }
      $name = trim($_POST['username'] ?? '');
      $pw = (string)($_POST['password'] ?? '');
      $pw2 = (string)($_POST['password2'] ?? '');
      if (!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,20}$/u', $name)) { flash('用户名需为 2-20 位中文/字母/数字/下划线', false); redirect('forum.php?p=register'); }
      if (strlen($pw) < PW_MIN_LEN) { flash('密码至少 ' . PW_MIN_LEN . ' 位', false); redirect('forum.php?p=register'); }
      if (strlen($pw) > PW_MAX_LEN) { flash('密码过长(最多 ' . PW_MAX_LEN . ' 位)', false); redirect('forum.php?p=register'); }
      if ($pw !== $pw2) { flash('两次输入的密码不一致', false); redirect('forum.php?p=register'); }
      if (username_taken($name)) { flash('该用户名已被占用', false); redirect('forum.php?p=register'); }
      /* 首管理员判定与写入放入同一「写事务」:BEGIN IMMEDIATE 从第一条语句起
         就持有 RESERVED 锁,避免 DEFERRED 事务在升级为写锁时拿到
         SQLITE_BUSY_SNAPSHOT(busy_timeout 不会重试该错误码) */
      $started = false;
      try {
        $db->exec('BEGIN IMMEDIATE');
        $started = true;
        $role = ((int)scalar('SELECT COUNT(*) FROM users')) === 0 ? 'admin' : 'user';
        row('INSERT INTO users(username,password,role,status,created_at) VALUES(?,?,?,1,?)',
            [$name, password_hash($pw, PASSWORD_DEFAULT), $role, now_sql()]);
        $uid = (int)$db->lastInsertId();
        $db->exec('COMMIT');
      } catch (Throwable $ex) {
        /* 只有事务确实开启过才 ROLLBACK,否则 ROLLBACK 自身会抛异常 */
        if ($started) { try { $db->exec('ROLLBACK'); } catch (Throwable $e2) {} }
        flash('该用户名已被占用', false); redirect('forum.php?p=register');
      }
      session_regenerate_id(true);
      $_SESSION['uid'] = $uid;
      flash($role === 'admin' ? '注册成功!您是第一位用户,已自动成为超级管理员' : '注册成功,欢迎加入!');
      redirect('forum.php');
    }
    case 'login': {
      $name = trim($_POST['username'] ?? '');
      $pw = (string)($_POST['password'] ?? '');
      $tkey = throttle_key($name);
      $lock = throttle_left($tkey);
      if ($lock > 0) { flash('尝试次数过多,请在 ' . $lock . ' 分钟后再试', false); redirect('forum.php?p=login'); }
      /* 与注册查重一致,登录也按大小写不敏感匹配 */
      $u = row('SELECT * FROM users WHERE username COLLATE NOCASE = ?', [$name]);
      if (!$u && preg_match('/^\d{1,10}$/', $name)) $u = row('SELECT * FROM users WHERE id=?', [(int)$name]);  // 支持数字ID登录
      if (!$u || !password_verify($pw, $u['password'])) {
        throttle_fail($tkey);
        flash('用户名/ID 或密码错误', false); redirect('forum.php?p=login');
      }
      if ((int)$u['status'] === 0) { flash('该账号已被禁止登录,请联系管理员', false); redirect('forum.php?p=login'); }
      if ($MAINTENANCE && $u['role'] !== 'admin') { flash('站点维护中,仅管理员可登录', false); redirect('forum.php?p=login'); }
      throttle_clear($tkey);
      session_regenerate_id(true);
      $_SESSION['uid'] = (int)$u['id'];
      flash('欢迎回来,' . $u['username']);
      redirect('forum.php');
    }
    case 'new_topic': {
      require_login();
      $me = cur_user();
      $fid = (int)($_POST['forum_id'] ?? 0);
      $f = forum_row($fid);
      if (!$f) { flash('分区不存在', false); redirect('forum.php'); }
      $title = trim($_POST['title'] ?? '');
      $content = trim($_POST['content'] ?? '');
      if (slen($title) < 2 || slen($title) > 100) { flash('标题需为 2-100 字', false); redirect('forum.php?p=new&forum=' . $fid); }
      if ($content === '') { flash('内容不能为空', false); redirect('forum.php?p=new&forum=' . $fid); }
      if (slen($content) > CONTENT_MAX_LEN) { flash('内容过长(最多 ' . CONTENT_MAX_LEN . ' 字)', false); redirect('forum.php?p=new&forum=' . $fid); }
      $ups = upload_images();
      if ($ups && isset($ups['error'])) { flash($ups['error'], false); redirect('forum.php?p=new&forum=' . $fid); }
      if ($ups) foreach ($ups['ok'] as $img) $content .= "\n[img]" . $img . "[/img]";
      row('INSERT INTO topics(forum_id,user_id,title,content,created_at) VALUES(?,?,?,?,?)', [$fid, $me['id'], $title, $content, now_sql()]);
      redirect('forum.php?p=topic&id=' . $db->lastInsertId());
    }
    case 'reply': {
      require_login();
      $me = cur_user();
      $tid = (int)($_POST['topic_id'] ?? 0);
      $t = row('SELECT * FROM topics WHERE id=?', [$tid]);
      if (!$t) { flash('主题不存在', false); redirect('forum.php'); }
      $content = trim($_POST['content'] ?? '');
      if ($content === '') { flash('回复内容不能为空', false); redirect('forum.php?p=topic&id=' . $tid); }
      if (slen($content) > CONTENT_MAX_LEN) { flash('内容过长(最多 ' . CONTENT_MAX_LEN . ' 字)', false); redirect('forum.php?p=topic&id=' . $tid); }
      $ups = upload_images();
      if ($ups && isset($ups['error'])) { flash($ups['error'], false); redirect('forum.php?p=topic&id=' . $tid); }
      if ($ups) foreach ($ups['ok'] as $img) $content .= "\n[img]" . $img . "[/img]";
      $floor = next_floor($tid);
      row('INSERT INTO replies(topic_id,user_id,content,floor,created_at) VALUES(?,?,?,?,?)', [$tid, $me['id'], $content, $floor, now_sql()]);
      redirect('forum.php?p=topic&id=' . $tid);
    }
    case 'del_topic': {
      $id = (int)($_POST['id'] ?? 0);
      $t = row('SELECT forum_id, user_id FROM topics WHERE id=?', [$id]);
      if (!$t) { flash('主题不存在', false); redirect('forum.php'); }
      $me = cur_user();
      if (!$me || (!can_manage($t['forum_id']) && (int)$me['id'] !== (int)$t['user_id'])) { flash('没有权限', false); redirect('forum.php'); }
      delete_topic_with_images($id);
      flash('主题已删除');
      redirect('forum.php?p=forum&id=' . $t['forum_id']);
    }
    case 'del_reply': {
      $id = (int)($_POST['id'] ?? 0);
      $tid = (int)($_POST['topic_id'] ?? 0);
      $r = row('SELECT r.id, r.user_id, t.forum_id FROM replies r JOIN topics t ON t.id=r.topic_id WHERE r.id=?', [$id]);
      if (!$r) { flash('回复不存在', false); redirect('forum.php'); }
      $me = cur_user();
      if (!$me || (!can_manage($r['forum_id']) && (int)$me['id'] !== (int)$r['user_id'])) { flash('没有权限', false); redirect('forum.php'); }
      delete_reply_with_images($id);
      flash('回复已删除(楼层号不重排)');
      redirect('forum.php?p=topic&id=' . $tid);
    }
    case 'edit_topic': {
      $id = (int)($_POST['id'] ?? 0);
      $t = row('SELECT * FROM topics WHERE id=?', [$id]);
      if (!$t) { flash('主题不存在', false); redirect('forum.php'); }
      $me = cur_user();
      if (!$me || ((int)$me['id'] !== (int)$t['user_id'] && !can_manage($t['forum_id']))) { flash('没有编辑权限', false); redirect('forum.php?p=topic&id=' . $id); }
      $title = trim($_POST['title'] ?? '');
      $content = trim($_POST['content'] ?? '');
      if (slen($title) < 2 || slen($title) > 100) { flash('标题需为 2-100 字', false); redirect('forum.php?p=edit_topic&id=' . $id); }
      if ($content === '') { flash('内容不能为空', false); redirect('forum.php?p=edit_topic&id=' . $id); }
      if (slen($content) > CONTENT_MAX_LEN) { flash('内容过长(最多 ' . CONTENT_MAX_LEN . ' 字)', false); redirect('forum.php?p=edit_topic&id=' . $id); }
      $ups = upload_images();
      if ($ups && isset($ups['error'])) { flash($ups['error'], false); redirect('forum.php?p=edit_topic&id=' . $id); }
      if ($ups) foreach ($ups['ok'] as $img) $content .= "\n[img]" . $img . "[/img]";
      row('UPDATE topics SET title=?, content=? WHERE id=?', [$title, $content, $id]);
      flash('主题已更新');
      redirect('forum.php?p=topic&id=' . $id);
    }
    case 'edit_reply': {
      $id = (int)($_POST['id'] ?? 0);
      $tid = (int)($_POST['topic_id'] ?? 0);
      $r = row('SELECT r.*, t.forum_id FROM replies r JOIN topics t ON t.id=r.topic_id WHERE r.id=?', [$id]);
      if (!$r) { flash('回复不存在', false); redirect('forum.php'); }
      $me = cur_user();
      if (!$me || ((int)$me['id'] !== (int)$r['user_id'] && !can_manage($r['forum_id']))) { flash('没有编辑权限', false); redirect('forum.php?p=topic&id=' . $tid); }
      $content = trim($_POST['content'] ?? '');
      if ($content === '') { flash('回复内容不能为空', false); redirect('forum.php?p=edit_reply&id=' . $id); }
      if (slen($content) > CONTENT_MAX_LEN) { flash('内容过长(最多 ' . CONTENT_MAX_LEN . ' 字)', false); redirect('forum.php?p=edit_reply&id=' . $id); }
      $ups = upload_images();
      if ($ups && isset($ups['error'])) { flash($ups['error'], false); redirect('forum.php?p=edit_reply&id=' . $id); }
      if ($ups) foreach ($ups['ok'] as $img) $content .= "\n[img]" . $img . "[/img]";
      row('UPDATE replies SET content=? WHERE id=?', [$content, $id]);
      flash('回复已更新');
      redirect('forum.php?p=topic&id=' . $tid);
    }
    case 'sticky_topic': {
      $id = (int)($_POST['id'] ?? 0);
      $t = row('SELECT forum_id, sticky FROM topics WHERE id=?', [$id]);
      if (!$t) { flash('主题不存在', false); redirect('forum.php'); }
      if (!can_manage($t['forum_id'])) { flash('没有权限', false); redirect('forum.php'); }
      row('UPDATE topics SET sticky=? WHERE id=?', [$t['sticky'] ? 0 : 1, $id]);
      flash($t['sticky'] ? '已取消置顶' : '已置顶');
      redirect('forum.php?p=topic&id=' . $id);
    }
    case 'sticky_reply': {
      $id = (int)($_POST['id'] ?? 0);
      $tid = (int)($_POST['topic_id'] ?? 0);
      $r = row('SELECT r.id, r.sticky, t.forum_id FROM replies r JOIN topics t ON t.id=r.topic_id WHERE r.id=?', [$id]);
      if (!$r) { flash('回复不存在', false); redirect('forum.php'); }
      if (!can_manage($r['forum_id'])) { flash('没有权限', false); redirect('forum.php'); }
      row('UPDATE replies SET sticky=? WHERE id=?', [$r['sticky'] ? 0 : 1, $id]);
      flash($r['sticky'] ? '已取消置顶' : '已置顶(楼层号不变)');
      redirect('forum.php?p=topic&id=' . $tid);
    }
    case 'add_forum': {
      require_admin();
      $name = trim($_POST['name'] ?? '');
      $desc = trim($_POST['description'] ?? '');
      if (slen($name) < 2 || slen($name) > 30) { flash('分区名称需为 2-30 字', false); redirect('forum.php?p=admin&tab=forums'); }
      row('INSERT INTO forums(name,description,created_at) VALUES(?,?,?)', [$name, $desc, now_sql()]);
      flash('分区已创建');
      redirect('forum.php?p=admin&tab=forums');
    }
    case 'del_forum': {
      require_admin();
      $id = (int)($_POST['id'] ?? 0);
      $imgs = collect_forum_images($id);
      row('DELETE FROM forums WHERE id=?', [$id]);       // FK 级联删除其下主题与回复
      gc_orphan_images($imgs);
      flash('分区已删除');
      redirect('forum.php?p=admin&tab=forums');
    }
    case 'edit_forum': {
      require_admin();
      $id = (int)($_POST['id'] ?? 0);
      $name = trim($_POST['name'] ?? '');
      $desc = trim($_POST['description'] ?? '');
      if (!forum_row($id)) { flash('分区不存在', false); redirect('forum.php?p=admin&tab=forums'); }
      if (slen($name) < 2 || slen($name) > 30) { flash('分区名称需为 2-30 字', false); redirect('forum.php?p=admin&tab=forums&edit=' . $id); }
      row('UPDATE forums SET name=?, description=? WHERE id=?', [$name, $desc, $id]);
      flash('分区已更新');
      redirect('forum.php?p=admin&tab=forums');
    }
    case 'set_mod': {
      require_admin();
      $fid = (int)($_POST['forum_id'] ?? 0);
      $mid = (int)($_POST['moderator_id'] ?? 0);
      if (!forum_row($fid)) { flash('分区不存在', false); redirect('forum.php?p=admin&tab=forums'); }
      if ($mid > 0) {
        $mu = user_row($mid);
        /* 不允许把被禁账号任命为版主(被禁账号 cur_user() 恒为 null,等于空设) */
        if (!$mu || (int)$mu['status'] !== 1) { flash('用户不存在或已被禁止,无法设为版主', false); redirect('forum.php?p=admin&tab=forums'); }
      }
      row('UPDATE forums SET moderator_id=? WHERE id=?', [$mid > 0 ? $mid : null, $fid]);
      flash('版主已设置');
      redirect('forum.php?p=admin&tab=forums');
    }
    case 'del_user': {
      require_admin();
      $id = (int)($_POST['id'] ?? 0);
      if ($id === (int)$_SESSION['uid']) { flash('不能删除自己', false); redirect('forum.php?p=admin&tab=users'); }
      $u = user_row($id);
      if (!$u) { flash('用户不存在', false); redirect('forum.php?p=admin&tab=users'); }
      if ($u['role'] === 'admin' && (int)scalar("SELECT COUNT(*) FROM users WHERE role='admin'") <= 1) { flash('不能删除最后一名管理员', false); redirect('forum.php?p=admin&tab=users'); }
      $imgs = collect_user_images($id);
      row('UPDATE forums SET moderator_id=NULL WHERE moderator_id=?', [$id]);
      row('DELETE FROM users WHERE id=?', [$id]);        // FK 级联删除其主题与回复
      gc_orphan_images($imgs);
      flash('用户已删除');
      redirect('forum.php?p=admin&tab=users');
    }
    case 'set_role': {
      require_admin();
      $id = (int)($_POST['id'] ?? 0);
      $role = $_POST['role'] ?? '';
      if (!in_array($role, ['admin', 'user'], true)) { flash('无效角色', false); redirect('forum.php?p=admin&tab=users'); }
      if ($id === (int)$_SESSION['uid']) { flash('不能修改自己的角色', false); redirect('forum.php?p=admin&tab=users'); }
      $u = user_row($id);
      if (!$u) { flash('用户不存在', false); redirect('forum.php?p=admin&tab=users'); }
      if ($u['role'] === 'admin' && $role !== 'admin' && (int)scalar("SELECT COUNT(*) FROM users WHERE role='admin'") <= 1) { flash('不能降级最后一名管理员', false); redirect('forum.php?p=admin&tab=users'); }
      row('UPDATE users SET role=? WHERE id=?', [$role, $id]);
      flash('角色已更新');
      redirect('forum.php?p=admin&tab=users');
    }
    case 'edit_user': {
      require_admin();
      $id = (int)($_POST['id'] ?? 0);
      $u = user_row($id);
      if (!$u) { flash('用户不存在', false); redirect('forum.php?p=admin&tab=users'); }
      $name = trim($_POST['username'] ?? '');
      $pw = (string)($_POST['password'] ?? '');
      $status = (int)($_POST['status'] ?? 1) === 1 ? 1 : 0;
      if ($u['role'] === 'admin') $status = 1;   // 管理员不可被禁止
      if (!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,20}$/u', $name)) { flash('用户名需为 2-20 位中文/字母/数字/下划线', false); redirect('forum.php?p=admin&tab=users&edit=' . $id); }
      if (username_taken($name, $id)) { flash('该用户名已被占用', false); redirect('forum.php?p=admin&tab=users&edit=' . $id); }
      if ($pw !== '') {
        if (strlen($pw) < PW_MIN_LEN) { flash('新密码至少 ' . PW_MIN_LEN . ' 位', false); redirect('forum.php?p=admin&tab=users&edit=' . $id); }
        if (strlen($pw) > PW_MAX_LEN) { flash('新密码过长(最多 ' . PW_MAX_LEN . ' 位)', false); redirect('forum.php?p=admin&tab=users&edit=' . $id); }
        row('UPDATE users SET username=?, password=?, status=? WHERE id=?', [$name, password_hash($pw, PASSWORD_DEFAULT), $status, $id]);
      } else {
        row('UPDATE users SET username=?, status=? WHERE id=?', [$name, $status, $id]);
      }
      /* 若把某人设为版主后又被禁止,其版主身份实际失效,这里不做级联处理,
         后台「分区管理」可随时改派;此处仅同步提示 */
      flash($u['role'] === 'admin' ? '用户信息已更新(管理员账号不可被禁止)' : '用户信息已更新');
      redirect('forum.php?p=admin&tab=users');
    }
    case 'save_settings': {
      require_admin();
      $name = trim($_POST['site_name'] ?? '');
      if ($name !== '' && mb_strlen($name) > 30) { flash('站点名称不能超过 30 字', false); redirect('forum.php?p=admin&tab=settings'); }
      $forceOff = isset($_POST['maintenance']) ? '1' : '0';
      set_setting('site_name', $name);
      set_setting('register', isset($_POST['register']) ? '1' : '0');
      set_setting('maintenance', $forceOff);
      set_setting('notice_on', isset($_POST['notice_on']) ? '1' : '0');
      set_setting('notice', trim($_POST['notice'] ?? ''));
      flash('站点设置已保存');
      redirect('forum.php?p=admin&tab=settings');
    }
    case 'backup': {
      require_admin();
      $r = make_backup();
      if (isset($r['error'])) { flash($r['error'], false); redirect('forum.php?p=admin&tab=tools'); }
      flash('备份已生成:' . $r['file'] . '(' . human_size($r['size']) . ')' . ($r['note'] ? ' — ' . $r['note'] : ''));
      redirect('forum.php?p=admin&tab=tools');
    }
    case 'del_backup': {
      require_admin();
      $f = basename((string)($_POST['file'] ?? ''));
      $d = backup_dir(false);
      if (!backup_name_ok($f) || !$d) { flash('文件不存在', false); redirect('forum.php?p=admin&tab=tools'); }
      @unlink($d . '/' . $f);
      flash('备份已删除:' . $f);
      redirect('forum.php?p=admin&tab=tools');
    }
    case 'gc_images': {
      require_admin();
      $mode = (($_POST['mode'] ?? 'scan') === 'clean') ? 'clean' : 'scan';
      $all = scan_upload_files();
      $used = collect_all_used_images();
      $orphan = [];
      foreach ($all as $rel) if (!isset($used[$rel])) $orphan[] = $rel;
      if ($mode === 'scan') {
        $sz = 0; foreach ($orphan as $rel) $sz += (int)@filesize(__DIR__ . '/' . $rel);
        flash('扫描完成:图片共 ' . count($all) . ' 张,其中无引用 ' . count($orphan) . ' 张(约 ' . human_size($sz) . ')');
      } else {
        $n = 0; $sz = 0;
        foreach ($orphan as $rel) {
          $sz += (int)@filesize(__DIR__ . '/' . $rel);
          if (delete_image_file($rel)) $n++;
        }
        flash('清理完成:删除孤儿图片 ' . $n . ' 张,释放约 ' . human_size($sz));
      }
      redirect('forum.php?p=admin&tab=tools');
    }
    case 'toggle_dbloc': {
      require_admin();
      $to = (($_POST['to'] ?? 'inside') === 'outside') ? 'outside' : 'inside';
      $r = db_relocate($to);
      if (isset($r['error'])) flash($r['error'], false); else flash($r['msg']);
      redirect('forum.php?p=admin&tab=settings');
    }
    case 'fix_protect': {
      require_admin();
      protect_data_dirs(true);
      flash('已重新生成目录保护文件(data/ 与 uploads/ 下的 .htaccess、index.html)');
      redirect('forum.php?p=admin&tab=settings');
    }
    case 'edit_profile': {
      require_login();
      $id = (int)($_POST['id'] ?? 0);
      if ($id !== (int)$_SESSION['uid']) { flash('只能修改自己的资料', false); redirect('forum.php?p=profile&id=' . $id); }
      $name = trim($_POST['username'] ?? '');
      $pw = (string)($_POST['password'] ?? '');
      $curpw = (string)($_POST['current_password'] ?? '');
      $u = user_row($id);
      if (!$u) { flash('用户不存在', false); redirect('forum.php?p=profile&id=' . $id); }
      if (!password_verify($curpw, $u['password'])) { flash('当前密码不正确', false); redirect('forum.php?p=profile&id=' . $id); }
      if (!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,20}$/u', $name)) { flash('用户名需为 2-20 位中文/字母/数字/下划线', false); redirect('forum.php?p=profile&id=' . $id); }
      if (username_taken($name, $id)) { flash('该用户名已被占用', false); redirect('forum.php?p=profile&id=' . $id); }
      if ($pw !== '') {
        if (strlen($pw) < PW_MIN_LEN) { flash('新密码至少 ' . PW_MIN_LEN . ' 位', false); redirect('forum.php?p=profile&id=' . $id); }
        if (strlen($pw) > PW_MAX_LEN) { flash('新密码过长(最多 ' . PW_MAX_LEN . ' 位)', false); redirect('forum.php?p=profile&id=' . $id); }
        row('UPDATE users SET username=?, password=? WHERE id=?', [$name, password_hash($pw, PASSWORD_DEFAULT), $id]);
      } else {
        row('UPDATE users SET username=? WHERE id=?', [$name, $id]);
      }
      session_regenerate_id(true);
      unset($GLOBALS['__user']);                 // 资料变更後丢弃缓存,下一请求重新读库
      flash('资料已更新');
      redirect('forum.php?p=profile&id=' . $id);
    }
    default: flash('未知操作', false); redirect('forum.php');
  }
}

/* ---------- GET 页面 ---------- */
switch ($p) {
  case 'login': {
    if (cur_user()) redirect('forum.php');
    page_header('登录');
    if ($MAINTENANCE) echo '<div class="flash err">站点维护中,当前仅管理员可登录</div>';
    echo '<div class="card"><h1>登录</h1><form method="post" action="forum.php">';
    echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="login">';
    echo '<label>用户名或ID<input type="text" name="username" required autofocus placeholder="用户名 或 数字ID"></label>';
    echo '<label>密码<input type="password" name="password" required></label>';
    echo '<p style="margin-top:14px"><button class="btn" type="submit">登录</button></p>';
    echo '<p class="hint" style="margin-top:10px">支持用户名或个人ID登录' . ((int)get_setting('register', '1') === 1 ? ',还没有账号?<a href="forum.php?p=register">立即注册</a>' : '') . '</p></form></div>';
    page_footer(); break;
  }
  case 'register': {
    if (cur_user()) redirect('forum.php');
    if ((int)get_setting('register', '1') !== 1) {
      page_header('注册');
      echo '<div class="card"><h1>注册已关闭</h1><p class="hint">本站暂不开放注册,如有需要请联系管理员。</p>';
      echo '<p style="margin-top:14px"><a class="btn gray" href="forum.php">返回首页</a></p></div>';
      page_footer(); break;
    }
    page_header('注册');
    echo '<div class="card"><h1>注册</h1><form method="post" action="forum.php">';
    echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="register">';
    echo '<label>用户名<input type="text" name="username" maxlength="20" required placeholder="2-20 位中文/字母/数字/下划线"></label>';
    echo '<label>密码<input type="password" name="password" required placeholder="至少 ' . PW_MIN_LEN . ' 位"></label>';
    echo '<label>确认密码<input type="password" name="password2" required></label>';
    echo '<p style="margin-top:14px"><button class="btn" type="submit">注册</button></p>';
    echo '<p class="hint" style="margin-top:10px">首位注册用户将自动成为超级管理员</p></form></div>';
    page_footer(); break;
  }
  case 'logout': {
    $tk = (string)($_GET['t'] ?? '');
    if ($tk === '' || !hash_equals((string)($_SESSION['csrf'] ?? ''), $tk)) {
      flash('退出链接已失效,请重新点击“退出”', false); redirect('forum.php');
    }
    $_SESSION = [];
    /* 同时清除会话 Cookie:session_destroy() 只删服务端文件,不删浏览器里的 ID */
    $cp = session_get_cookie_params();
    @setcookie(session_name(), '', time() - 42000, $cp['path'], $cp['domain'] ?? '', (bool)$cp['secure'], (bool)$cp['httponly']);
    session_destroy();
    redirect('forum.php');
  }
  case 'home': {
    page_header('首页');
    $forums = rows("SELECT f.*,
      (SELECT COUNT(*) FROM topics t WHERE t.forum_id=f.id) tc,
      (SELECT COUNT(*) FROM replies r JOIN topics t ON r.topic_id=t.id WHERE t.forum_id=f.id) rc,
      (SELECT username FROM users u WHERE u.id=f.moderator_id) modname
      FROM forums f ORDER BY f.sort,f.id");
    echo '<h1>论坛分区</h1>';
    if (!$forums) {
      $me = cur_user();
      echo '<div class="card"><p class="hint">还没有分区。' . ($me && $me['role'] === 'admin' ? '<a href="forum.php?p=admin">去后台创建分区</a>' : '请联系管理员创建分区。') . '</p></div>';
    } else {
      echo '<div class="forum-grid">';
      foreach ($forums as $f) {
        echo '<a class="card forum-card" href="forum.php?p=forum&id=' . $f['id'] . '">';
        echo '<div class="fname">' . e($f['name']) . '</div>';
        if ($f['description'] !== '') echo '<div class="fdesc">' . e($f['description']) . '</div>';
        echo '<div class="fmeta">主题 ' . $f['tc'] . ' · 回复 ' . $f['rc'] . ($f['modname'] ? ' · 版主 ' . e($f['modname']) : '') . '</div>';
        echo '</a>';
      }
      echo '</div>';
    }
    $lts = rows("SELECT t.id,t.title,t.sticky,t.user_id,t.forum_id,t.created_at,t.views,
      (SELECT COUNT(*) FROM replies r WHERE r.topic_id=t.id) rc,
      u.username,f.name fname
      FROM topics t JOIN users u ON u.id=t.user_id JOIN forums f ON f.id=t.forum_id
      ORDER BY t.id DESC LIMIT 10");
    if ($lts) {
      echo '<h1 style="margin-top:22px">最新主题</h1><div class="card topic-list">';
      foreach ($lts as $t) {
        echo '<div class="row"><a class="tt" href="forum.php?p=topic&id=' . $t['id'] . '">' . ($t['sticky'] ? '<span class="sticky-tag">置顶</span> ' : '') . e($t['title']) . '</a>';
        echo '<span class="meta">' . e($t['fname']) . ' · ' . e($t['username']) . ' · ' . e($t['created_at']) . ' · ' . $t['rc'] . ' 回复 / ' . $t['views'] . ' 浏览</span></div>';
      }
      echo '</div>';
    }
    page_footer(); break;
  }
  case 'forum': {
    $fid = (int)($_GET['id'] ?? 0);
    $f = forum_row($fid);
    if (!$f) { flash('分区不存在', false); redirect('forum.php'); }
    page_header($f['name']);
    $me = cur_user();
    $modname = $f['moderator_id'] ? (user_row($f['moderator_id'])['username'] ?? '') : '';
    echo '<div class="crumbs"><a href="forum.php">首页</a> / ' . e($f['name']) . '</div>';
    echo '<div class="card"><h1>' . e($f['name']) . '</h1>';
    if ($f['description'] !== '') echo '<div class="meta">' . e($f['description']) . '</div>';
    echo '<div class="meta">版主:' . ($modname ? e($modname) : '未设置') . '</div>';
    if ($me) echo '<a class="btn" href="forum.php?p=new&forum=' . $fid . '">发新主题</a>';
    echo '</div>';
    $total = (int)scalar('SELECT COUNT(*) FROM topics WHERE forum_id=?', [$fid]);
    list($pager, $off) = pager($total, 20, 'forum.php?p=forum&id=' . $fid);
    $list = rows("SELECT t.*,u.username,
      (SELECT COUNT(*) FROM replies r WHERE r.topic_id=t.id) rc
      FROM topics t JOIN users u ON u.id=t.user_id
      WHERE t.forum_id=? ORDER BY t.sticky DESC, t.id DESC LIMIT 20 OFFSET ?", [$fid, (int)$off]);
    if (!$list) {
      echo '<div class="card hint">本分区还没有主题' . ($me ? ',<a href="forum.php?p=new&forum=' . $fid . '">发一个吧</a>' : '') . '</div>';
    } else {
      echo '<div class="card topic-list">';
      foreach ($list as $t) {
        echo '<div class="row"><a class="tt" href="forum.php?p=topic&id=' . $t['id'] . '">' . ($t['sticky'] ? '<span class="sticky-tag">置顶</span> ' : '') . e($t['title']) . '</a>';
        echo '<span class="meta">' . e($t['username']) . ' · ' . e($t['created_at']) . ' · ' . $t['rc'] . ' 回复 / ' . $t['views'] . ' 浏览</span></div>';
      }
      echo '</div>' . $pager;
    }
    page_footer(); break;
  }
  case 'topic': {
    $tid = (int)($_GET['id'] ?? 0);
    $t = row("SELECT t.*,u.username,f.name fname FROM topics t JOIN users u ON u.id=t.user_id JOIN forums f ON f.id=t.forum_id WHERE t.id=?", [$tid]);
    if (!$t) { flash('主题不存在', false); redirect('forum.php'); }
    $fresh = empty($_SESSION['viewed'][$tid]);                 // 同一会话刷新不重复计数
    if ($fresh) {
      row('UPDATE topics SET views=views+1 WHERE id=?', [$tid]);
      if (!isset($_SESSION['viewed']) || !is_array($_SESSION['viewed'])) $_SESSION['viewed'] = [];
      if (count($_SESSION['viewed']) > 500) $_SESSION['viewed'] = array_slice($_SESSION['viewed'], -200, null, true);
      $_SESSION['viewed'][$tid] = 1;
    }
    $views = $t['views'] + ($fresh ? 1 : 0);
    $me = cur_user();
    $can = can_manage($t['forum_id']);
    page_header($t['title']);
    echo '<div class="crumbs"><a href="forum.php">首页</a> / <a href="forum.php?p=forum&id=' . $t['forum_id'] . '">' . e($t['fname']) . '</a> / ' . e($t['title']) . '</div>';
    echo '<div class="card op"><h1>' . ($t['sticky'] ? '<span class="sticky-tag">置顶</span> ' : '') . e($t['title']) . '</h1>';
    echo '<div class="meta">' . e($t['username']) . ' 发布于 ' . e($t['created_at']) . ' · ' . $views . ' 浏览';
    if ($me && ((int)$me['id'] === (int)$t['user_id'] || $can)) echo ' <a class="btn gray small" href="forum.php?p=edit_topic&id=' . $tid . '">编辑</a>';
    if ($can) echo ' <form class="inline" method="post" action="forum.php"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="sticky_topic"><input type="hidden" name="id" value="' . $tid . '"><button class="btn gray small">' . ($t['sticky'] ? '取消置顶' : '置顶') . '</button></form>';
    if ($can || ($me && (int)$me['id'] === (int)$t['user_id'])) echo ' <form class="inline" method="post" action="forum.php" data-confirm="确定删除该主题?"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="del_topic"><input type="hidden" name="id" value="' . $tid . '"><button class="btn danger small">删除主题</button></form>';
    echo '</div><div class="content">' . render_content($t['content']) . '</div></div>';
    $rtotal = (int)scalar('SELECT COUNT(*) FROM replies WHERE topic_id=?', [$tid]);
    list($rpager, $roff, $rcur) = pager($rtotal, 30, 'forum.php?p=topic&id=' . $tid);
    $rlist = rows("SELECT r.*,u.username FROM replies r JOIN users u ON u.id=r.user_id WHERE r.topic_id=? ORDER BY r.sticky DESC, r.id ASC LIMIT 30 OFFSET ?", [$tid, (int)$roff]);
    echo '<h2>全部回复(' . $rtotal . ')</h2>';
    if (!$rlist) echo '<div class="card hint">暂无回复,来抢沙发~</div>';
    foreach ($rlist as $i => $r) {
      /* 楼层号直接读库内固化的 floor,删除与置顶都不会改变它 */
      $floor = (int)$r['floor'];
      if ($floor <= 0) $floor = $roff + $i + 1;      // 兜底:个别老数据未回填时
      echo '<div class="card reply" id="reply-' . $r['id'] . '"><div class="meta">#' . $floor . ' ' . ($r['sticky'] ? '<span class="sticky-tag">置顶</span> ' : '') . e($r['username']) . ' 发表于 ' . e($r['created_at']);
      if ($me) {
        /* 引用按钮:抄楼号 + 正文前 10 个字符 */
        $qtext = trim((string)preg_replace('/\s+/', ' ', preg_replace('/\[img\].*?\[\/img\]/', ' ', $r['content'])));
        $q10 = mb_strlen($qtext) > 10 ? mb_substr($qtext, 0, 10) . '…' : $qtext;
        $qdata = e((string)json_encode([$floor, $r['username'], $q10], JSON_UNESCAPED_UNICODE));
        echo ' <button type="button" class="btn gray small" data-quote="' . $qdata . '">引用</button>';
        if ((int)$me['id'] === (int)$r['user_id'] || $can) echo ' <a class="btn gray small" href="forum.php?p=edit_reply&id=' . $r['id'] . '">编辑</a>';
      }
      if ($can) echo ' <form class="inline" method="post" action="forum.php"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="sticky_reply"><input type="hidden" name="id" value="' . $r['id'] . '"><input type="hidden" name="topic_id" value="' . $tid . '"><button class="btn gray small">' . ($r['sticky'] ? '取消置顶' : '置顶') . '</button></form>';
      if ($can || ($me && (int)$me['id'] === (int)$r['user_id'])) echo ' <form class="inline" method="post" action="forum.php" data-confirm="确定删除该回复?删除后楼层号不会重排。"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="del_reply"><input type="hidden" name="id" value="' . $r['id'] . '"><input type="hidden" name="topic_id" value="' . $tid . '"><button class="btn danger small">删除</button></form>';
      echo '</div><div class="content">' . render_content($r['content']) . '</div></div>';
    }
    echo $rpager;
    if ($me) {
      echo '<div class="card"><h3>发表回复</h3><form method="post" action="forum.php" enctype="multipart/form-data">';
      echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="reply"><input type="hidden" name="topic_id" value="' . $tid . '">';
      echo '<textarea name="content" id="replyContent" required placeholder="回复内容"></textarea>';
      echo '<label>附带图片(jpg/png/gif/webp,单张≤' . round(IMG_MAX_SIZE / 1048576) . 'MB,最多 ' . IMG_MAX_FILES . ' 张,合计≤' . round(IMG_MAX_TOTAL / 1048576) . 'MB)<input type="file" name="images[]" accept="image/*" multiple></label>';
      echo '<p style="margin-top:12px"><button class="btn" type="submit">发布回复</button></p></form></div>';
    } else {
      echo '<div class="card hint">请<a href="forum.php?p=login">登录</a>后发表回复</div>';
    }
    page_footer(); break;
  }
  case 'edit_topic': {
    $id = (int)($_GET['id'] ?? 0);
    $t = row('SELECT * FROM topics WHERE id=?', [$id]);
    if (!$t) { flash('主题不存在', false); redirect('forum.php'); }
    $me = cur_user();
    if (!$me || ((int)$me['id'] !== (int)$t['user_id'] && !can_manage($t['forum_id']))) { flash('没有编辑权限', false); redirect('forum.php?p=topic&id=' . $id); }
    page_header('编辑主题');
    echo '<div class="card"><h1>编辑主题</h1><form method="post" action="forum.php" enctype="multipart/form-data">';
    echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="edit_topic"><input type="hidden" name="id" value="' . $id . '">';
    echo '<label>标题<input type="text" name="title" maxlength="100" required value="' . e($t['title']) . '"></label>';
    echo '<label>内容<textarea name="content" required>' . e($t['content']) . '</textarea></label>';
    echo '<label>追加图片(单张≤' . round(IMG_MAX_SIZE / 1048576) . 'MB,最多 ' . IMG_MAX_FILES . ' 张,附在正文末尾;删除正文中 [img] 标记即可移除原图)<input type="file" name="images[]" accept="image/*" multiple></label>';
    echo '<p style="margin-top:12px"><button class="btn">保存修改</button> <a class="btn gray" href="forum.php?p=topic&id=' . $id . '">取消</a></p></form></div>';
    page_footer(); break;
  }
  case 'edit_reply': {
    $id = (int)($_GET['id'] ?? 0);
    $r = row('SELECT r.*, t.forum_id FROM replies r JOIN topics t ON t.id=r.topic_id WHERE r.id=?', [$id]);
    if (!$r) { flash('回复不存在', false); redirect('forum.php'); }
    $me = cur_user();
    if (!$me || ((int)$me['id'] !== (int)$r['user_id'] && !can_manage($r['forum_id']))) { flash('没有编辑权限', false); redirect('forum.php?p=topic&id=' . $r['topic_id']); }
    page_header('编辑回复');
    echo '<div class="card"><h1>编辑回复</h1><form method="post" action="forum.php" enctype="multipart/form-data">';
    echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="edit_reply"><input type="hidden" name="id" value="' . $id . '"><input type="hidden" name="topic_id" value="' . $r['topic_id'] . '">';
    echo '<label>内容<textarea name="content" required>' . e($r['content']) . '</textarea></label>';
    echo '<label>追加图片(单张≤' . round(IMG_MAX_SIZE / 1048576) . 'MB,最多 ' . IMG_MAX_FILES . ' 张,附在正文末尾;删除正文中 [img] 标记即可移除原图)<input type="file" name="images[]" accept="image/*" multiple></label>';
    echo '<p style="margin-top:12px"><button class="btn">保存修改</button> <a class="btn gray" href="forum.php?p=topic&id=' . $r['topic_id'] . '">取消</a></p></form></div>';
    page_footer(); break;
  }
  case 'new': {
    require_login();
    $preset = (int)($_GET['forum'] ?? 0);
    $forums = rows('SELECT * FROM forums ORDER BY sort,id');
    if (!$forums) { flash('还没有分区,无法发帖', false); redirect('forum.php'); }
    page_header('发新主题');
    echo '<div class="card"><h1>发新主题</h1><form method="post" action="forum.php" enctype="multipart/form-data">';
    echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="new_topic">';
    echo '<label>选择分区<select name="forum_id">';
    foreach ($forums as $f) echo '<option value="' . $f['id'] . '"' . ($preset === (int)$f['id'] ? ' selected' : '') . '>' . e($f['name']) . '</option>';
    echo '</select></label>';
    echo '<label>标题<input type="text" name="title" maxlength="100" required placeholder="2-100 字"></label>';
    echo '<label>内容<textarea name="content" required placeholder="支持纯文本,可附带多张图片"></textarea></label>';
    echo '<label>附带图片(jpg/png/gif/webp,单张≤' . round(IMG_MAX_SIZE / 1048576) . 'MB,最多 ' . IMG_MAX_FILES . ' 张,合计≤' . round(IMG_MAX_TOTAL / 1048576) . 'MB)<input type="file" name="images[]" accept="image/*" multiple></label>';
    echo '<p style="margin-top:12px"><button class="btn" type="submit">发布</button></p></form></div>';
    page_footer(); break;
  }
  case 'profile': {
    $id = (int)($_GET['id'] ?? 0);
    $u = user_row($id);
    if (!$u) { flash('用户不存在', false); redirect('forum.php'); }
    $mods = rows('SELECT name FROM forums WHERE moderator_id=?', [$id]);
    $tc = (int)scalar('SELECT COUNT(*) FROM topics WHERE user_id=?', [$id]);
    $rc = (int)scalar('SELECT COUNT(*) FROM replies WHERE user_id=?', [$id]);
    $eff = $u['role'] === 'admin' ? 'admin' : ($mods ? 'mod' : 'user');
    page_header($u['username']);
    echo '<div class="card"><h1>' . e($u['username']) . ' ' . role_badge($eff) . '</h1>';
    echo '<div class="meta">ID:' . $u['id'] . ' · 注册于 ' . e($u['created_at']) . ' · 主题 ' . $tc . ' · 回复 ' . $rc . '</div>';
    if ($mods) echo '<div class="meta">版主分区:' . e(implode('、', array_column($mods, 'name'))) . '</div>';
    if ((int)$u['status'] === 0) echo '<div class="meta"><span class="badge st-off">该账号已被禁止登录</span></div>';
    echo '</div>';
    if (isset($_SESSION['uid']) && (int)$_SESSION['uid'] === $id) {
      echo '<div class="card"><h3>修改资料</h3><form method="post" action="forum.php">';
      echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="edit_profile"><input type="hidden" name="id" value="' . $id . '">';
      echo '<label>用户名<input type="text" name="username" maxlength="20" required value="' . e($u['username']) . '"></label>';
      echo '<label>当前密码(修改资料需验证)<input type="password" name="current_password" required autocomplete="current-password" placeholder="请输入当前登录密码"></label>';
      echo '<label>新密码(留空则不修改)<input type="password" name="password" autocomplete="new-password" placeholder="留空保持原密码"></label>';
      echo '<p style="margin-top:12px"><button class="btn">保存修改</button></p></form></div>';
    }
    $recent = rows("SELECT t.id,t.title,f.name fname FROM topics t JOIN forums f ON f.id=t.forum_id WHERE t.user_id=? ORDER BY t.id DESC LIMIT 10", [$id]);
    if ($recent) {
      echo '<h2>最近主题</h2><div class="card topic-list">';
      foreach ($recent as $t) {
        echo '<div class="row"><a class="tt" href="forum.php?p=topic&id=' . $t['id'] . '">' . e($t['title']) . '</a><span class="meta">' . e($t['fname']) . '</span></div>';
      }
      echo '</div>';
    }
    page_footer(); break;
  }
  case 'admin': {
    require_admin();
    $tab = (string)($_GET['tab'] ?? 'settings');
    if (!in_array($tab, ['settings', 'users', 'forums', 'tools'], true)) $tab = 'settings';
    page_header('管理后台');
    echo '<h1>管理后台</h1>';
    echo '<div class="tabs"><a class="' . ($tab === 'settings' ? 'on' : '') . '" href="forum.php?p=admin&tab=settings">站点设置</a><a class="' . ($tab === 'users' ? 'on' : '') . '" href="forum.php?p=admin&tab=users">用户管理</a><a class="' . ($tab === 'forums' ? 'on' : '') . '" href="forum.php?p=admin&tab=forums">分区管理</a><a class="' . ($tab === 'tools' ? 'on' : '') . '" href="forum.php?p=admin&tab=tools">备份维护</a></div>';
    if ($tab === 'settings') {
      echo '<div class="card"><h3>站点设置</h3><form method="post" action="forum.php">';
      echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="save_settings">';
      echo '<label>站点名称<input type="text" name="site_name" maxlength="30" value="' . e(get_setting('site_name', '')) . '" placeholder="留空则显示 FlatForum(最多 30 字)"></label>';
      echo '<label style="display:flex;align-items:center;gap:8px;font-weight:500"><input type="checkbox" name="register" style="width:auto"' . ((int)get_setting('register', '1') === 1 ? ' checked' : '') . '> 开放注册(关闭后新用户无法注册)</label>';
      echo '<label style="display:flex;align-items:center;gap:8px;font-weight:500"><input type="checkbox" name="maintenance" style="width:auto"' . ((int)get_setting('maintenance', '0') === 1 ? ' checked' : '') . '> 站点维护(开启后除管理员外其他用户不能登录访问)</label>';
      echo '<label style="display:flex;align-items:center;gap:8px;font-weight:500"><input type="checkbox" name="notice_on" style="width:auto"' . ((int)get_setting('notice_on', '0') === 1 ? ' checked' : '') . '> 启用站点通知(首页顶部公告条)</label>';
      echo '<label>通知内容<textarea name="notice" placeholder="输入通知内容,前台所有页面顶部显示">' . e(get_setting('notice', '')) . '</textarea></label>';
      echo '<p style="margin-top:14px"><button class="btn">保存设置</button></p></form></div>';
      /* ---- 安全自检 ---- */
      $dbDir = dirname(DB_FILE);
      $dbInWebRoot = (strpos($dbDir, __DIR__) === 0);
      $htOk = is_file($dbDir . '/.htaccess');
      $upHtOk = is_file(UPLOAD_DIR . '/.htaccess');
      $btnFixProtect = '<form method="post" action="forum.php"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="fix_protect"><button class="btn gray small">重新生成</button></form>';
      /* 数据库位置可双向迁移;站内为默认,站外为可选加固 */
      $btnMoveDb = $dbInWebRoot
        ? '<form method="post" action="forum.php" data-confirm="将把数据库搬到站点目录之外(上级 flatforum_data/),期间会自动开启站点维护模式。确定继续?"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="toggle_dbloc"><input type="hidden" name="to" value="outside"><button class="btn small">移到站外</button></form>'
        : '<form method="post" action="forum.php" data-confirm="将把数据库搬回站点内 data/forum.db,期间会自动开启站点维护模式。确定继续?"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="toggle_dbloc"><input type="hidden" name="to" value="inside"><button class="btn small">搬回站内</button></form>';
      echo '<div class="card"><h3>安全自检</h3><table class="admin"><tr class="head"><th>项目</th><th>状态</th><th>说明</th><th>操作</th></tr>';
      echo '<tr><td data-label="项目">数据库位置</td><td data-label="状态">'
         . ($dbInWebRoot ? '<span class="badge st-info">站内 data/</span>' : '<span class="badge st-on">站外</span>')
         . '</td><td data-label="说明">'
         . ($dbInWebRoot
            ? '位于 <code>' . e(short_path(DB_FILE)) . '</code>(v2.8.5 起默认)。请确保 data/ 禁止外部访问:Apache 用 .htaccess,nginx 需手动加 <code>location ^~ /data/ { deny all; }</code>'
            : '位于 Web 根目录之外 <code>' . e(short_path(DB_FILE)) . '</code>,无法被直接下载')
         . '</td><td data-label="操作">' . $btnMoveDb . '</td></tr>';
      echo '<tr><td data-label="项目">data 目录保护</td><td data-label="状态">' . ($htOk ? '<span class="badge st-on">已生成</span>' : '<span class="badge st-off">缺失</span>') . '</td><td data-label="说明">'
         . ($htOk ? '已写入 .htaccess(Apache 生效)' : '无法写入 .htaccess,请手动禁止外部访问 data/') . '</td><td data-label="操作">' . $btnFixProtect . '</td></tr>';
      echo '<tr><td data-label="项目">上传目录保护</td><td data-label="状态">' . ($upHtOk ? '<span class="badge st-on">已生成</span>' : '<span class="badge st-off">缺失</span>') . '</td><td data-label="说明">禁止脚本执行与目录列举(Apache 生效;nginx 需自行配置)</td><td data-label="操作">' . $btnFixProtect . '</td></tr>';
      echo '<tr><td data-label="项目">HTTPS</td><td data-label="状态">' . (is_https() ? '<span class="badge st-on">已启用</span>' : '<span class="badge st-off">未启用</span>') . '</td><td data-label="说明">'
         . (is_https() ? 'Cookie 已加 Secure,已下发 HSTS' : '当前为 HTTP,建议配置证书;否则登录 Cookie 可被嗅探') . '</td><td data-label="操作"><span class="hint">需配证书</span></td></tr>';
      echo '<tr><td data-label="项目">错误显示</td><td data-label="状态">' . ((string)ini_get('display_errors') === '0' || strtolower((string)ini_get('display_errors')) === 'off' ? '<span class="badge st-on">已关闭</span>' : '<span class="badge st-off">开启</span>') . '</td><td data-label="说明">错误详情不再回显,已记入 <code>' . e(short_path(dirname(DB_FILE) . '/php_errors.log')) . '</code></td><td data-label="操作"><span class="hint">已在代码中关闭</span></td></tr>';
      echo '<tr><td data-label="项目">反向代理</td><td data-label="状态">' . (TRUST_PROXY ? '<span class="badge st-info">已信任</span>' : '<span class="badge st-info">直连</span>') . '</td><td data-label="说明">'
         . (TRUST_PROXY ? '已采信 X-Forwarded-Proto / X-Forwarded-For(请确保前置代理可信)' : '直接取 REMOTE_ADDR,不采信转发头;若站点在反向代理后请修改顶部常量 TRUST_PROXY') . '</td><td data-label="操作"><span class="hint">改常量</span></td></tr>';
      echo '</table></div>';
    } elseif ($tab === 'users') {
      $editU = (int)($_GET['edit'] ?? 0);
      $users = rows("SELECT u.*,(SELECT COUNT(*) FROM topics t WHERE t.user_id=u.id) tc,(SELECT COUNT(*) FROM replies r WHERE r.user_id=u.id) rc FROM users u ORDER BY u.id");
      if ($editU && ($eu = user_row($editU))) {
        $isAdminTarget = $eu['role'] === 'admin';
        echo '<div class="card"><h3>编辑用户:' . e($eu['username']) . '</h3><form method="post" action="forum.php">';
        echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="edit_user"><input type="hidden" name="id" value="' . $eu['id'] . '">';
        echo '<label>用户名<input type="text" name="username" maxlength="20" required value="' . e($eu['username']) . '"></label>';
        echo '<label>新密码(留空则不改)<input type="password" name="password" placeholder="留空保持原密码"></label>';
        echo '<label>账号状态<select name="status"' . ($isAdminTarget ? ' disabled' : '') . '><option value="1"' . ((int)$eu['status'] === 1 ? ' selected' : '') . '>启用(可正常登录)</option><option value="0"' . ((int)$eu['status'] === 0 ? ' selected' : '') . '>禁止(不可登录)</option></select></label>';
        if ($isAdminTarget) echo '<input type="hidden" name="status" value="1"><p class="hint">管理员账号不可被禁止</p>';
        echo '<p style="margin-top:12px"><button class="btn">保存修改</button> <a class="btn gray" href="forum.php?p=admin&tab=users">取消</a></p></form></div>';
      }
      echo '<div class="card"><table class="admin"><tr class="head"><th>ID</th><th>用户名</th><th>角色</th><th>状态</th><th>注册时间</th><th>主题/回复</th><th>操作</th></tr>';
      foreach ($users as $u) {
        echo '<tr><td data-label="ID">' . $u['id'] . '</td><td data-label="用户名">' . e($u['username']) . '</td><td data-label="角色">' . role_badge($u['role']) . '</td><td data-label="状态"><span class="badge ' . ((int)$u['status'] === 1 ? 'st-on' : 'st-off') . '">' . ((int)$u['status'] === 1 ? '正常' : '已禁止') . '</span></td><td data-label="注册时间">' . e($u['created_at']) . '</td><td data-label="主题/回复">' . $u['tc'] . ' / ' . $u['rc'] . '</td><td data-label="操作">';
        echo '<a class="btn gray small" href="forum.php?p=admin&tab=users&edit=' . $u['id'] . '">编辑</a> ';
        if ((int)$u['id'] !== (int)$_SESSION['uid']) {
          if ($u['role'] !== 'admin') echo '<form class="inline" method="post" action="forum.php"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="set_role"><input type="hidden" name="id" value="' . $u['id'] . '"><input type="hidden" name="role" value="admin"><button class="btn small">设为管理员</button></form> ';
          else echo '<form class="inline" method="post" action="forum.php"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="set_role"><input type="hidden" name="id" value="' . $u['id'] . '"><input type="hidden" name="role" value="user"><button class="btn gray small">设为普通用户</button></form> ';
          echo '<form class="inline" method="post" action="forum.php" data-confirm="确定删除该用户?其全部主题与回复将一并删除!"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="del_user"><input type="hidden" name="id" value="' . $u['id'] . '"><button class="btn danger small">删除</button></form>';
        } else echo '<span class="hint">(当前账号)</span>';
        echo '</td></tr>';
      }
      echo '</table></div>';
    } elseif ($tab === 'tools') {
      $bdir = backup_dir();
      /* 备份下载:走 PHP 流式输出,备份目录本身禁止外部直接访问 */
      $dl = (string)($_GET['dl'] ?? '');
      if ($dl !== '') {
        $f = basename($dl);
        if (!backup_name_ok($f) || !$bdir || !is_file($bdir . '/' . $f)) { flash('备份文件不存在', false); redirect('forum.php?p=admin&tab=tools'); }
        $abs = $bdir . '/' . $f;
        while (ob_get_level() > 0) @ob_end_clean();
        send_security_headers();
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $f . '"');
        header('Content-Length: ' . (string)filesize($abs));
        header('X-Accel-Buffering: no');
        readfile($abs);
        exit;
      }
      /* ---- 一键备份 ---- */
      echo '<div class="card"><h3>一键导出备份</h3>';
      echo '<p class="hint">生成数据库快照(SQLite VACUUM INTO,在线安全),若服务器支持 ZipArchive 会连同 uploads 图片一起打包。备份存于数据目录下的 backups/,不对外可直接下载。</p>';
      echo '<form method="post" action="forum.php" class="btn-row"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="backup"><button class="btn">立即生成备份</button></form>';
      echo '<p class="hint" style="margin-top:10px">建议定期备份并把文件下载到本地;恢复时覆盖数据目录中的 forum.db 即可(图片解压回 uploads/)。</p></div>';
      /* ---- 孤儿图清理 ---- */
      $allFiles = scan_upload_files();          // 只遍历一次,数量与体积一并统计
      $allN = count($allFiles);
      $allSz = 0; foreach ($allFiles as $rel) $allSz += (int)@filesize(__DIR__ . '/' . $rel);
      echo '<div class="card"><h3>清理孤儿图片</h3>';
      echo '<p class="hint">孤儿图片 = uploads 中存在、但主题与回复正文里已无 [img] 引用的文件(如编辑删图、删除帖子、上传中断残留)。当前 uploads 共 ' . $allN . ' 个文件,占用约 ' . human_size($allSz) . '。</p>';
      echo '<div class="btn-row">';
      echo '<form method="post" action="forum.php"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="gc_images"><input type="hidden" name="mode" value="scan"><button class="btn gray">先扫描看看有多少</button></form>';
      echo '<form method="post" action="forum.php" data-confirm="确定删除全部无引用的孤儿图片?此操作不可恢复,建议先做一次备份。"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="gc_images"><input type="hidden" name="mode" value="clean"><button class="btn danger">立即清理孤儿图</button></form>';
      echo '</div><p class="hint" style="margin-top:10px">删除帖子的同时程序已自动回收其图片,此处主要用于清理早期版本遗留的历史孤儿文件。</p></div>';
      /* ---- 备份列表 ---- */
      $files = [];
      if ($bdir) foreach ((@scandir($bdir) ?: []) as $fn) {
        if (backup_name_ok($fn) && is_file($bdir . '/' . $fn)) $files[$fn] = @filemtime($bdir . '/' . $fn);
      }
      arsort($files, SORT_NUMERIC);
      echo '<div class="card"><table class="admin"><tr class="head"><th>文件名</th><th>大小</th><th>生成时间</th><th>操作</th></tr>';
      if (!$files) {
        echo '<tr><td data-label="备份列表" colspan="4" class="hint">还没有备份,点击上方“立即生成备份”。</td></tr>';
      } else {
        foreach ($files as $fn => $mt) {
          echo '<tr><td data-label="文件名">' . e($fn) . '</td>'
             . '<td data-label="大小">' . human_size((int)@filesize($bdir . '/' . $fn)) . '</td>'
             . '<td data-label="生成时间">' . e(date('Y-m-d H:i:s', (int)$mt)) . '</td><td data-label="操作">'
             . '<a class="btn small" href="forum.php?p=admin&tab=tools&dl=' . rawurlencode($fn) . '">下载</a> '
             . '<form class="inline" method="post" action="forum.php" data-confirm="确定删除该备份?"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="del_backup"><input type="hidden" name="file" value="' . e($fn) . '"><button class="btn danger small">删除</button></form>'
             . '</td></tr>';
        }
      }
      echo '</table>';
      $bdirShow = $bdir ? $bdir : '(不可用,请检查权限)';
      echo '<p class="hint" style="margin-top:10px">备份目录:<code class="path" title="' . e($bdirShow) . '">' . e(short_path($bdirShow)) . '</code> 已占用约 ' . human_size(dir_size($bdirShow === '(不可用,请检查权限)' ? '' : $bdirShow)) . '</p>';
      echo '<p class="hint" style="margin-top:6px">恢复:解压后把 <code>forum.sqlite</code>(或 <code>db-*.sqlite</code>)<b>改名为 forum.db</b> 覆盖数据目录中的同名文件即可,扩展名不影响内容;图片解压回 <code>uploads/</code> 并保持 <code>YYYYMM/</code> 目录结构。</p></div>';
      /* ---- 防护说明 ---- */
      echo '<div class="card"><details><summary>配套服务器配置(点击展开)</summary>';
      echo '<p class="hint">若使用 nginx,请务必在 server 块中加入以下规则(.htaccess 对 nginx 无效),否则数据库仍可能被直接下载:</p>';
      echo '<pre class="code">' . e("location ^~ /data/    { deny all; }\nlocation ~* \\.(db|sqlite|log)$ { deny all; }\nlocation ~ /\\. { deny all; }") . '</pre>';
      echo '<p class="hint" style="margin-top:10px">完整站点配置(含 PHP-FPM、上传限额、静态缓存、HTTPS)见交付包中的 nginx-flatforum.conf / apache-flatforum.conf。</p></details></div>';
    } else {
      $edit = (int)($_GET['edit'] ?? 0);
      $forums = rows("SELECT f.*,(SELECT COUNT(*) FROM topics t WHERE t.forum_id=f.id) tc FROM forums f ORDER BY f.sort,f.id");
      $users = rows('SELECT id,username FROM users WHERE status=1 ORDER BY id');
      echo '<div class="card"><h3>新增分区</h3><form method="post" action="forum.php">';
      echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="add_forum">';
      echo '<label>名称<input type="text" name="name" maxlength="30" required placeholder="分区名称(2-30 字)"></label>';
      echo '<label>简介<input type="text" name="description" maxlength="100" placeholder="一句话简介(可选)"></label>';
      echo '<p style="margin-top:12px"><button class="btn">创建分区</button></p></form></div>';
      if ($edit && ($ef = forum_row($edit))) {
        echo '<div class="card"><h3>编辑分区</h3><form method="post" action="forum.php">';
        echo '<input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="edit_forum"><input type="hidden" name="id" value="' . $ef['id'] . '">';
        echo '<label>名称<input type="text" name="name" maxlength="30" required value="' . e($ef['name']) . '"></label>';
        echo '<label>简介<input type="text" name="description" maxlength="100" value="' . e($ef['description']) . '"></label>';
        echo '<p style="margin-top:12px"><button class="btn">保存修改</button> <a class="btn gray" href="forum.php?p=admin&tab=forums">取消</a></p></form></div>';
      }
      echo '<div class="card"><h3>分区列表</h3><table class="admin"><tr class="head"><th>ID</th><th>名称</th><th>主题数</th><th>版主</th><th>操作</th></tr>';
      foreach ($forums as $f) {
        echo '<tr><td data-label="ID">' . $f['id'] . '</td><td data-label="名称">' . e($f['name']) . ($f['description'] !== '' ? '<br><span class="hint">' . e($f['description']) . '</span>' : '') . '</td><td data-label="主题数">' . $f['tc'] . '</td><td data-label="版主">';
        echo '<form class="inline" method="post" action="forum.php"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="set_mod"><input type="hidden" name="forum_id" value="' . $f['id'] . '"><select name="moderator_id">';
        echo '<option value="0">未设置</option>';
        foreach ($users as $u) echo '<option value="' . $u['id'] . '"' . ($f['moderator_id'] !== null && (int)$f['moderator_id'] === (int)$u['id'] ? ' selected' : '') . '>' . e($u['username']) . '</option>';
        echo '</select> <button class="btn small">保存</button></form></td><td data-label="操作">';
        echo '<a class="btn gray small" href="forum.php?p=admin&tab=forums&edit=' . $f['id'] . '">编辑</a> ';
        echo '<form class="inline" method="post" action="forum.php" data-confirm="确定删除该分区?分区内所有主题与回复将一并删除!"><input type="hidden" name="csrf" value="' . csrf() . '"><input type="hidden" name="action" value="del_forum"><input type="hidden" name="id" value="' . $f['id'] . '"><button class="btn danger small">删除分区</button></form>';
        echo '</td></tr>';
      }
      echo '</table></div>';
    }
    page_footer(); break;
  }
  default: redirect('forum.php');
}
} catch (Throwable $ex) {
  while (ob_get_level() > 0) @ob_end_clean();
  @error_log('[FlatForum] ' . get_class($ex) . ': ' . $ex->getMessage() . ' @ ' . basename($ex->getFile()) . ':' . $ex->getLine());
  fatal_page();
}
回复主楼