SOURCE DOWNLOAD

木漏茶室源码下载中心

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

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

已经跑起来的木漏茶室

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

实时检测
2 个站点已部署

已展示全部 2 个站点。

pages/chat.php 23.3 KB · 发布包 v6.25.231
下载
<?php
/**
 * 聊天室:登录发言、图片/文件、搜索、管理员撤回与禁言,消息保留 7 天
 */
require_login();
feature_guard('chat_room');
$me = current_user();
$isAdmin = is_admin(current_user());
$keyword = trim((string) input('q', ''));

// 超过 7 天的消息自动清理
DB::run('DELETE FROM ' . DB::table('chat') . ' WHERE created_at < ?', [date('Y-m-d H:i:s', strtotime('-7 days'))]);

$mute = DB::one('SELECT * FROM ' . DB::table('chat_mutes') . ' WHERE user_id = ? ORDER BY id DESC LIMIT 1', [$me['id']]);
$mutedUntil = ($mute && $mute['until'] > now()) ? $mute['until'] : '';
$siteMuted = user_is_muted($me) || user_is_site_muted($me);
$globalMute = setting('chat_global_mute', '0') === '1';
$canSpeak = ($mutedUntil === '' && !$siteMuted && (!$globalMute || $isAdmin));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $act = input('act');

    if ($act === 'send') {
        if (!$canSpeak) {
            if ($siteMuted) {
                $reason = '你已被管理员禁言,暂时不能聊天';
            } elseif ($mutedUntil !== '') {
                $reason = '你已被禁言至 ' . $mutedUntil;
            } else {
                $reason = '全员禁言中,当前只有管理员和超级管理员可以发言';
            }
            flash($reason, 'err');
            redirect(page_url('chat'));
        }
        $content = trim((string) ($_POST['content'] ?? ''));
        $type = 'text';
        $path = '';
        try {
            if (!empty($_FILES['image']['name'])) {
                $stored = upload_store('image', 'chat', ['image' => true, 'max' => 0, 'allow' => image_upload_extensions()]);
                $type = 'image';
                $path = $stored['path'];
            } elseif (!empty($_FILES['voice']['name'])) {
                $stored = upload_store('voice', 'chat', [
                    'max'   => 15 * 1024 * 1024,
                    'allow' => ['webm','mp4','m4a','ogg','opus','mp3','wav','aac'],
                ]);
                $type = 'voice';
                $compatible = audio_make_compatible($stored['path']);
                if ($compatible) {
                    $stored['path'] = $compatible;
                }
                $path = $stored['path'];
                $dur = max(1, min(120, (int) ($_POST['duration'] ?? 1)));
                $content = (string) $dur;
            } elseif (!empty($_FILES['media']['name'])) {
                $stored = upload_store('media', 'chat', [
                    'max'   => 50 * 1024 * 1024,
                    'allow' => chat_media_extensions(),
                    'mime_media' => true,
                ]);
                $ext = strtolower(pathinfo($stored['name'], PATHINFO_EXTENSION));
                $mime = (string) (new finfo(FILEINFO_MIME_TYPE))->file(APP_ROOT . '/' . $stored['path']);
                $type = media_kind_by_ext($ext);
                if ($type === '') {
                    if (strpos($mime, 'audio/') === 0) { $type = 'audio'; }
                    elseif (strpos($mime, 'video/') === 0) { $type = 'video'; }
                } elseif ($type === 'video' && strpos($mime, 'audio/') === 0) {
                    $type = 'audio';
                }
                if ($type === '') {
                    throw new Exception('不是可播放的视频或音频文件');
                }
                $stored['path'] = chat_prepare_media($stored['path'], $type);
                $path = $stored['path'];
                if ($content === '') {
                    $content = $stored['name'];
                }
            } elseif (!empty($_FILES['file']['name'])) {
                $stored = upload_store('file', 'chat', [
                    'max'   => 50 * 1024 * 1024,
                    'allow' => array_merge(['zip','rar','7z','pdf','txt','md','doc','docx','xls','xlsx','ppt','pptx','apk'], chat_media_extensions()),
                ]);
                $ext = strtolower(pathinfo($stored['name'], PATHINFO_EXTENSION));
                $type = media_kind_by_ext($ext) ?: 'file';
                if ($type === 'video' || $type === 'audio') {
                    $stored['path'] = chat_prepare_media($stored['path'], $type);
                }
                $path = $stored['path'];
                if ($content === '') {
                    $content = $stored['name'];
                }
            }
            if ($type === 'text' && $content !== '') {
                $sens = sensitive_filter($content);
                if ($sens['action'] === 'block') { throw new Exception('消息包含不允许发送的敏感词:' . $sens['hit']); }
                $content = $sens['text'];
            }
            if ($content === '' && $path === '') {
                flash('消息不能为空', 'err');
            } elseif (mb_strlen($content) > 500) {
                flash('单条消息最多 500 字', 'err');
            } else {
                $voiceText = '';
                if ($type === 'voice') {
                    $voiceText = mb_substr(trim((string) ($_POST['voice_text'] ?? '')), 0, 500);
                }
                DB::insert('chat', [
                    'user_id'    => $me['id'],
                    'type'       => $type,
                    'content'    => $content,
                    'voice_text' => $voiceText,
                    'path'       => $path,
                    'is_deleted' => 0,
                    'created_at' => now(),
                ]);
            }
        } catch (Exception $e) {
            flash('发送失败:' . $e->getMessage(), 'err');
        }
        redirect(page_url('chat') . '#chatBottom');
    }

    if ($act === 'transfer') {
        if (feature_denied($me, 'transfer')) {
            flash('「积分转账」功能已被管理员关闭', 'err');
            redirect(page_url('chat') . '#chatBottom');
        }
        $toId = (int) input('to_id');
        $amount = (int) input('amount');
        $note = trim((string) input('note'));
        try {
            transfer_points($me['id'], $toId, $amount, $note, 'chat');
            flash('已转账 ' . $amount . ' 积分');
        } catch (Exception $e) {
            flash('转账失败:' . $e->getMessage(), 'err');
        }
        redirect(page_url('chat'));
    }

    if ($isAdmin) {
        if ($act === 'del') {
            $id = (int) input('id');
            $targetMsg = DB::one('SELECT user_id FROM ' . DB::table('chat') . ' WHERE id = ?', [$id]);
            if (!$targetMsg) {
                flash('消息不存在', 'err');
            } elseif (is_superadmin(user_by_id((int) $targetMsg['user_id'])) && !is_superadmin(current_user())) {
                flash('管理员不能撤回超级管理员的聊天消息', 'err');
            } else {
                DB::run('UPDATE ' . DB::table('chat') . ' SET is_deleted = 1 WHERE id = ?', [$id]);
                flash('消息已撤回');
            }
            redirect(page_url('chat'));
        }
        if ($act === 'clear') {
            if (is_superadmin(current_user())) {
                DB::run('DELETE FROM ' . DB::table('chat'));
                DB::run('DELETE FROM ' . DB::table('chat_mutes'));
                flash('聊天大厅已清空');
            } else {
                // 普通管理员清空聊天时保留超级管理员消息,避免绕过撤回限制
                DB::run('DELETE FROM ' . DB::table('chat') . ' WHERE user_id NOT IN (SELECT id FROM ' . DB::table('users') . " WHERE role = 'superadmin')");
                $nonSuperMutes = DB::all('SELECT m.id FROM ' . DB::table('chat_mutes') . ' m
                                           LEFT JOIN ' . DB::table('users') . ' u ON u.id = m.user_id
                                           WHERE u.role <> ?', ['superadmin']);
                foreach ($nonSuperMutes as $muteRow) {
                    DB::delete('chat_mutes', 'id = ?', [(int) $muteRow['id']]);
                }
                flash('已清空普通用户和管理员的聊天消息,超级管理员消息和禁言状态已保留');
            }
            redirect(page_url('chat'));
        }
        if ($act === 'mute') {
            $uid = (int) input('uid');
            $target = user_by_id($uid);
            $minutes = (int) input('minutes', 60);
            $minutes = $minutes < 0 ? 60 : min($minutes, 525600);
            $until = $minutes > 0 ? date('Y-m-d H:i:s', time() + $minutes * 60) : '9999-12-31 23:59:59';
            if (!$target) {
                flash('用户不存在', 'err');
            } elseif ($uid === (int) $me['id']) {
                flash('管理员不能禁言自己', 'err');
            } elseif (is_superadmin($target) && !is_superadmin(current_user())) {
                flash('只有超级管理员可以操作超级管理员', 'err');
            } else {
                DB::insert('chat_mutes', [
                    'user_id' => $uid,
                    'until'   => $until,
                ]);
                flash($minutes > 0 ? '已禁言该用户 ' . $minutes . ' 分钟' : '已永久禁言该用户');
            }
            redirect(page_url('chat'));
        }
        if ($act === 'unmute') {
            $uid = (int) input('uid');
            $target = user_by_id($uid);
            if (is_superadmin($target) && !is_superadmin(current_user())) {
                flash('只有超级管理员可以解除超级管理员的聊天禁言', 'err');
            } elseif ($uid === (int) $me['id'] && !is_superadmin(current_user())) {
                flash('管理员不能解除自己的聊天禁言,请让超级管理员操作', 'err');
            } else {
                DB::delete('chat_mutes', 'user_id = ?', [$uid]);
                flash('已解除禁言');
            }
            redirect(page_url('chat'));
        }
    }
}

$where = ['c.is_deleted = 0'];
$params = [];
if ($keyword !== '') {
    $where[] = 'c.content LIKE ?';
    $params[] = '%' . $keyword . '%';
}
$messages = DB::all('SELECT c.*, u.nickname, u.username, u.avatar, u.gender, u.role, u.comment_bubble, u.verified, u.verify_style, u.verify_title, u.verify_type FROM ' . DB::table('chat') . ' c
                     LEFT JOIN ' . DB::table('users') . ' u ON u.id = c.user_id
                     WHERE ' . implode(' AND ', $where) . '
                     ORDER BY c.id DESC LIMIT 80', $params);
$messages = array_reverse($messages);
$mutes = $isAdmin ? DB::all('SELECT m.*, u.nickname, u.username, u.role FROM ' . DB::table('chat_mutes') . ' m
                             LEFT JOIN ' . DB::table('users') . ' u ON u.id = m.user_id
                             WHERE m.until > ? ORDER BY m.id DESC', [now()]) : [];

$GLOBALS['PAGE'] = 'chat';
render_header('聊天大厅');
?>
<section class="chat-head">
  <div>
    <span class="hero-kicker">TEA HOUSE CHAT</span>
    <h1>聊天大厅 <span class="chat-live" title="消息实时刷新中"><i class="live-dot red"></i><i class="live-dot green"></i><span>实时刷新</span></span></h1>
    <p>消息保留 7 天 · <?= count($messages) ?> 条近况</p>
  </div>
  <div class="call-banner" id="callBanner" hidden>
    <span class="call-dot">🎙</span>
    <span id="callText">群语音</span>
    <button type="button" class="call-accept" id="callAccept">接听</button>
    <button type="button" class="call-decline" id="callDecline">拒听</button>
    <button type="button" class="call-hang" id="callHang">挂断</button>
  </div>
  <div id="callAudio" class="call-audio"></div>
  <form method="get" action="<?= e(base_url('index.php')) ?>" class="search-box">
    <input type="hidden" name="page" value="chat">
    <input type="search" name="q" value="<?= e($keyword) ?>" placeholder="搜索聊天内容">
    <button type="submit" aria-label="搜索">⌕</button>
  </form>
</section>

<section class="chat-room" data-global-mute="<?= $globalMute ? '1' : '0' ?>">
  <div class="chat-stream" id="chatStream">
    <?php if (!$messages): ?>
      <?php empty_state('聊天大厅还很安静', '先来说句话吧'); ?>
    <?php else: ?>
      <?php foreach ($messages as $m): $mine = (int) $m['user_id'] === (int) $me['id']; ?>
        <div class="chat-msg <?= $mine ? 'mine' : '' ?>" data-mid="<?= (int) $m['id'] ?>">
          <?= avatar_html($m, 'chat-avatar can-actions', 'data-uid="' . (int) $m['user_id'] . '" data-name="' . e(display_name($m)) . '"') ?>
          <div class="chat-body">
            <div class="chat-meta">
              <a href="<?= e(page_url('user', ['id' => $m['user_id']])) ?>"><?= e(display_name($m)) ?></a><?= verify_badge($m) ?>
              <?php if ($m['role'] === 'superadmin'): ?><span class="tag tag-super">超级管理员</span>
              <?php elseif ($m['role'] === 'admin'): ?><span class="tag">管理</span><?php endif; ?>
              <span class="chat-uid">ID <?= (int) $m['user_id'] ?></span>
              <time><?= e(date('m-d H:i', strtotime($m['created_at']))) ?></time>
            </div>
            <?php if ($m['type'] === 'transfer'):
                $transfer = transfer_notice_data($m['content']);
                $tFrom = (int) ($transfer['from_id'] ?? 0);
                $tTo = (int) ($transfer['to_id'] ?? 0);
                $tAmount = (int) ($transfer['amount'] ?? 0);
                $tFromBalance = (int) ($transfer['from_balance'] ?? 0);
                $tToBalance = (int) ($transfer['to_balance'] ?? 0);
                $tBalance = (int) $me['id'] === $tFrom ? $tFromBalance : ((int) $me['id'] === $tTo ? $tToBalance : null);
            ?>
              <div class="transfer-bubble">
                <div class="transfer-bubble-top"><span class="transfer-bubble-icon">💸</span><span>积分转账</span></div>
                <div class="transfer-bubble-names"><?= e($transfer['from_name'] ?? '茶客') ?> <span>→</span> <?= e($transfer['to_name'] ?? '茶客') ?></div>
                <div class="transfer-bubble-amount"><?= $tAmount ?> <small>积分</small></div>
                <?php if (trim((string) ($transfer['note'] ?? '')) !== ''): ?><p class="transfer-bubble-note"><?= e($transfer['note']) ?></p><?php endif; ?>
                <?php if ($tBalance !== null): ?><div class="transfer-bubble-balance">转账后我的余额 <b><?= $tBalance ?></b> 积分</div><?php endif; ?>
              </div>
            <?php elseif ($m['type'] === 'image'): ?>
              <?php $imgExt = strtolower(pathinfo((string) $m['path'], PATHINFO_EXTENSION)); ?>
              <?php if (in_array($imgExt, ['jpg','jpeg','jpe','jfif','png','apng','gif','webp','bmp','avif','svg','ico'], true)): ?>
                <a href="<?= e(upload_url($m['path'])) ?>" target="_blank" rel="noopener" class="chat-img">
                  <img src="<?= e(upload_url($m['path'])) ?>" alt="图片" loading="lazy">
                </a>
              <?php else: ?>
                <a class="chat-file" href="<?= e(upload_url($m['path'])) ?>" target="_blank" rel="noopener">🖼 <?= e($imgExt !== '' ? strtoupper($imgExt) . ' 图片' : '图片') ?>(点击打开原图)</a>
              <?php endif; ?>
            <?php elseif ($m['type'] === 'video'): ?>
              <div class="chat-media">
                <video class="chat-video" controls playsinline preload="metadata" src="<?= e(video_playable_url(upload_url($m['path']))) ?>"></video>
                <?php if (trim((string) $m['content']) !== ''): ?><span class="chat-media-name"><?= e($m['content']) ?></span><?php endif; ?>
              </div>
            <?php elseif ($m['type'] === 'audio'):
                $audioMeta = audio_track_meta($m['path']);
                $audioCaption = trim((string) $m['content']);
                $audioSrc = audio_playable_url(upload_url($m['path']));
            ?>
              <div class="chat-media">
                <audio class="chat-audio" data-km-audio="1" data-audio-title="<?= e($audioMeta['title']) ?>" data-audio-artist="<?= e($audioMeta['artist']) ?>" data-audio-cover="<?= e($audioMeta['cover']) ?>" data-audio-caption="<?= e($audioCaption !== '' ? $audioCaption : basename((string) $m['path'])) ?>" data-audio-lyrics-b64="<?= e(base64_encode((string) ($audioMeta['lyrics'] ?? ''))) ?>" data-audio-download="<?= e(base_url('api.php')) ?>?action=audio_download&amp;id=<?= (int) $m['id'] ?>" controls playsinline preload="metadata" src="<?= e($audioSrc) ?>"></audio>
              </div>
            <?php elseif ($m['type'] === 'voice'): ?>
              <div class="chat-voice">
                <audio controls preload="metadata" src="<?= e(audio_playable_url(upload_url($m['path']))) ?>"></audio>
                <span class="voice-dur"><?= (int) $m['content'] ?>″</span>
              </div>
              <?php $voiceText = trim((string) ($m['voice_text'] ?? '')); ?>
              <?php if ($voiceText !== ''): ?><p class="voice-transcript">📝 <?= nl2br(e($voiceText)) ?></p><?php endif; ?>
            <?php elseif ($m['type'] === 'file'): ?>
              <a class="chat-file" href="<?= e(upload_url($m['path'])) ?>" download>📎 <?= e((int) $m['content'] === 0 ? '文件' : $m['content']) ?></a>
            <?php else: ?>
              <p class="chat-text bubble-<?= e(comment_bubble_of($m)) ?>"><?= nl2br(e($m['content'])) ?></p>
            <?php endif; ?>
            <?php if (!$mine): ?>
            <div class="chat-user-actions">
              <button class="chat-transfer" type="button" data-uid="<?= (int) $m['user_id'] ?>" data-name="<?= e(display_name($m)) ?>">转账积分</button>
            </div>
            <?php endif; ?>
            <?php if ($isAdmin): ?>
              <div class="chat-admin">
                <?php if (!is_superadmin($m) || is_superadmin(current_user())): ?>
                <form method="post" class="inline-form" data-confirm="撤回这条消息?">
                  <?= csrf_field() ?><input type="hidden" name="act" value="del"><input type="hidden" name="id" value="<?= (int) $m['id'] ?>">
                  <button class="link-btn" type="submit">撤回</button>
                </form>
                <?php else: ?>
                <span class="muted">超管消息不可撤回</span>
                <?php endif; ?>
                <?php if (!$mine && (!is_superadmin($m) || is_superadmin(current_user()))): ?>
                <form method="post" class="inline-form chat-mute-form">
                  <?= csrf_field() ?><input type="hidden" name="act" value="mute">
                  <input type="hidden" name="uid" value="<?= (int) $m['user_id'] ?>">
                  <select name="minutes">
                    <option value="10">10 分钟</option>
                    <option value="60" selected>1 小时</option>
                    <option value="1440">1 天</option>
                    <option value="10080">7 天</option>
                    <option value="43200">30 天</option>
                    <option value="0">永久</option>
                  </select>
                  <button class="link-btn" type="submit">禁言</button>
                </form>
                <?php elseif (!$mine): ?>
                  <span class="muted">超管不可禁言</span>
                <?php endif; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
    <div id="chatBottom"></div>
  </div>

  <div class="transfer-modal" id="transferModal" hidden>
    <div class="transfer-card">
      <div class="transfer-head"><h3>转账积分给 <b id="transferName">TA</b></h3><button type="button" class="readers-close" id="transferClose">×</button></div>
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="act" value="transfer">
        <input type="hidden" name="to_id" id="transferToId" value="0">
        <label>转账积分(当前余额 <?= e(points_text($me)) ?>)</label>
        <input type="number" name="amount" min="1" max="99999" required placeholder="例如 10">
        <label>备注(选填)</label>
        <input type="text" name="note" maxlength="60" placeholder="给对方留句话">
        <button class="btn-primary" type="submit">确认转账</button>
      </form>
    </div>
  </div>

  <div class="notice chat-mute-notice" id="chatMuteNotice" <?= $canSpeak ? 'hidden' : '' ?>>
    <?php if ($siteMuted): ?>你已被管理员禁言,暂时无法发言。
    <?php elseif ($mutedUntil !== ''): ?>你已被禁言至 <?= e($mutedUntil) ?>,暂时无法发言。
    <?php else: ?>聊天大厅已开启全员禁言,当前只有管理员和超级管理员可以发言。<?php endif; ?>
  </div>
  <form method="post" enctype="multipart/form-data" class="chat-form" id="chatForm"
        data-upload-progress data-upload-progress-label="正在上传聊天文件"
        data-muted="<?= ($siteMuted || $mutedUntil !== '') ? '1' : '0' ?>" <?= $canSpeak ? '' : 'hidden' ?>>
    <?= csrf_field() ?>
    <input type="hidden" name="act" value="send">
    <div class="chat-attach" id="chatAttach" hidden>
      <label class="attach-item attach-img">🖼<span>图片</span><input type="file" name="image" accept="image/*"></label>
      <label class="attach-item attach-file">📎<span>文件</span><input type="file" name="file"></label>
      <label class="attach-item attach-media">🎬<span>视频/音频</span><input type="file" name="media" accept="video/*,audio/*,<?= e(implode(',', array_map(function ($x) { return '.' . $x; }, chat_media_extensions()))) ?>"></label>
      <button type="button" class="attach-item attach-call" id="callStart">🎙<span>语音通话</span></button>
      <?php if ($isAdmin): ?>
      <button type="button" class="attach-item attach-global-mute <?= $globalMute ? 'on' : '' ?>" id="chatGlobalMute" data-enabled="<?= $globalMute ? '1' : '0' ?>"><?= $globalMute ? '🔊' : '🔇' ?><span id="chatGlobalMuteText"><?= $globalMute ? '解除全员禁言' : '全员禁言' ?></span></button>
      <?php endif; ?>
    </div>
    <div class="chat-bar">
      <textarea name="content" rows="1" maxlength="500" placeholder="说点什么…" id="chatInput"></textarea>
      <button class="chat-mic" type="button" id="chatVoice" aria-label="发语音" title="点击开始录音,再点发送">🎤</button>
      <button class="chat-plus" type="button" id="chatPlus" aria-label="更多功能">+</button>
      <button class="chat-send" type="submit">发送</button>
    </div>
  </form>
</section>

<?php if ($isAdmin): ?>
<section class="panel">
  <div class="panel-head row">
    <h2>聊天大厅管理</h2>
    <form method="post" data-confirm="清空全部聊天记录?此操作不可恢复。">
      <?= csrf_field() ?><input type="hidden" name="act" value="clear">
      <button class="btn-mini danger" type="submit">清空聊天大厅</button>
    </form>
  </div>
  <?php if ($mutes): ?>
    <div class="drive-list">
      <?php foreach ($mutes as $mm): ?>
        <div class="drive-row">
          <div class="dr-main"><strong><?= e(display_name($mm)) ?></strong><span>禁言至 <?= e($mm['until']) ?></span></div>
          <div class="dr-actions">
            <?php if ((!is_superadmin($mm) && ((int) $mm['user_id'] !== (int) $me['id'] || is_superadmin(current_user()))) || is_superadmin(current_user())): ?>
            <form method="post" class="inline-form">
              <?= csrf_field() ?><input type="hidden" name="act" value="unmute"><input type="hidden" name="uid" value="<?= (int) $mm['user_id'] ?>">
              <button class="btn-mini" type="submit">解除禁言</button>
            </form>
            <?php else: ?>
              <span class="muted">超管禁言 · 仅超管可解除</span>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php else: ?>
    <p class="muted">当前没有被禁言的用户。</p>
  <?php endif; ?>
</section>
<?php endif; ?>

<?php render_footer(); ?>
主题