post.php11.1 KB
<?php
// 0. 开启会话,用于获取后台登录状态
session_start();
// 1. 引入配置并连接数据库
if (!file_exists(__DIR__ . '/config.php')) { die('系统未安装!'); }
require __DIR__ . '/config.php';
try {
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
$pdo = new PDO($dsn, DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
} catch (PDOException $e) { die("数据库连接失败:" . $e->getMessage()); }
$is_admin_logged_in = isset($_SESSION['user_id']) && $_SESSION['role'] === 'admin';
// 【修复后】头像获取辅助函数
function getCommentAvatar($comment) {
// 1. 如果是管理员/登录用户,直接返回默认头像
if (!empty($comment['user_name'])) {
return '/images/default-avatar.png'; // 请确保你的网站根目录下有这个图片
}
// 2. 如果是游客,检查是否填写了 QQ 邮箱
if (!empty($comment['guest_email'])) {
// 使用正则匹配是否为 QQ 邮箱格式 (数字@qq.com)
if (preg_match('/^(\d{5,11})@qq\.com$/i', $comment['guest_email'], $matches)) {
// 【关键修复】必须取 $matches[1],这才是正则第一个括号内提取到的纯 QQ 号码
$qq_number = $matches[1];
// 【已更换】使用最新的腾讯官方高清头像 API (s=640 为 640x640 尺寸)
return "https://q1.qlogo.cn/g?b=qq&nk={$qq_number}&s=640";
}
}
// 3. 未填写 QQ 邮箱或非 QQ 邮箱的游客,也使用默认头像
return '/images/default-avatar.png';
}
// 2. 获取文章 ID 并校验
$post_id = $_GET['id'] ?? null;
if (!$post_id || !is_numeric($post_id)) { http_response_code(404); die('文章不存在!'); }
// 3. 查询文章详情
$stmt = $pdo->prepare("SELECT p.*, u.username AS author_name, c.name AS category_name
FROM posts p LEFT JOIN users u ON p.author_id = u.id
LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = :id");
$stmt->execute([':id' => $post_id]);
$post = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$post) { http_response_code(404); die('未找到该文章!'); }
// 4. 处理评论提交 (POST 请求)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_comment'])) {
$comment_content = $_POST['content'] ?? '';
$comment_content = htmlspecialchars(strip_tags($comment_content));
if (!empty(trim($comment_content))) {
if ($is_admin_logged_in) {
$sql = "INSERT INTO comments (post_id, user_id, content, status) VALUES (:pid, :uid, :content, 'approved')";
$stmt = $pdo->prepare($sql);
$stmt->execute([':pid' => $post_id, ':uid' => $_SESSION['user_id'], ':content' => $comment_content]);
} else {
$guest_name = trim($_POST['guest_name'] ?? '');
$guest_email = trim($_POST['guest_email'] ?? '');
if (!empty($guest_name)) {
$sql = "INSERT INTO comments (post_id, guest_name, guest_email, content, status) VALUES (:pid, :name, :email, :content, 'pending')";
$stmt = $pdo->prepare($sql);
$stmt->execute([':pid' => $post_id, ':name' => $guest_name, ':email' => $guest_email, ':content' => $comment_content]);
}
}
header('Location: post.php?id=' . $post_id . '#comments'); exit;
}
}
// 5. 查询已审核通过的评论(注意:这里必须把 guest_email 也查出来)
$comment_stmt = $pdo->prepare("SELECT c.*, u.username AS user_name FROM comments c LEFT JOIN users u ON c.user_id = u.id WHERE c.post_id = :pid AND c.status = 'approved' ORDER BY c.created_at ASC");
$comment_stmt->execute([':pid' => $post_id]);
$comments = $comment_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($post['title']); ?> - 我的博客</title>
<style>
.article-card { background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-bottom: 30px; }
.article-title { margin: 0 0 15px; font-size: 28px; line-height: 1.3; }
.article-meta { font-size: 13px; color: #888; margin-bottom: 20px; display: flex; gap: 15px; flex-wrap: wrap;}
.article-content { font-size: 16px; color: #444; white-space: pre-wrap; word-wrap: break-word; }
.comment-section { background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.comment-item { border-bottom: 1px solid #eee; padding: 15px 0; display: flex; gap: 15px; align-items: flex-start;}
.comment-item:last-child { border-bottom: none; }
/* 【新增】头像样式 */
.comment-avatar { width: 45px; height: 45px; border-radius: 50%; object-fit: cover; flex-shrink: 0; background: #eee;}
.comment-body { flex: 1; }
.comment-header { display: flex; align-items: center; gap: 10px; margin-bottom: 5px; }
.comment-author { font-weight: bold; color: #333; }
.admin-badge { background-color: #007bff; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; }
.reply-btn { font-size: 12px; color: #888; cursor: pointer; text-decoration: none; transition: color 0.2s; }
.reply-btn:hover { color: #007bff; text-decoration: underline; }
.comment-date { font-size: 12px; color: #aaa; }
.comment-text { margin-top: 8px; font-size: 14px; color: #555; }
form input, form textarea { width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; font-family: inherit;}
form button { background: #333; color: #fff; border: none; padding: 12px 20px; border-radius: 4px; cursor: pointer; font-size: 16px; }
form button:hover { background: #555; }
.admin-notice { background-color: #e8f4fc; border-left: 4px solid #007bff; padding: 10px 15px; margin-bottom: 15px; font-size: 14px; color: #0c5460; display: flex; justify-content: space-between; align-items: center;}
.admin-notice a { color: #007bff; text-decoration: none; font-weight: bold;}
</style>
</head>
<body>
<!-- 搜索弹窗 -->
<?php require_once __DIR__ . '/search-tc.php'; ?>
<div class="container">
<?php require_once __DIR__ . '/header.php'; ?>
<div class="main-content">
<div class="content-left">
<div class="article-card">
<h1 class="article-title"><?php echo htmlspecialchars($post['title']); ?></h1>
<div class="article-meta">
<span>🕒 <?php echo date('Y-m-d H:i', strtotime($post['created_at'])); ?></span>
<?php if (!empty($post['author_name'])): ?><span>✍️ <?php echo htmlspecialchars($post['author_name']); ?></span><?php endif; ?>
<?php if (!empty($post['category_name'])): ?><span>📁 <?php echo htmlspecialchars($post['category_name']); ?></span><?php endif; ?>
</div>
<div class="article-content"><?php echo $post['content']; ?></div>
</div>
<div class="comment-section" id="comments">
<h3>💬 评论 (<?php echo count($comments); ?>)</h3>
<?php if (!empty($comments)): ?>
<?php foreach ($comments as $comment): ?>
<?php
$commenter_name = !empty($comment['user_name']) ? $comment['user_name'] : $comment['guest_name'];
$avatar_url = getCommentAvatar($comment); // 调用函数获取头像
?>
<div class="comment-item">
<!-- 【新增】渲染头像 -->
<img src="<?php echo $avatar_url; ?>" alt="avatar" class="comment-avatar" onerror="this.src='/images/default-avatar.png'">
<div class="comment-body">
<div class="comment-header">
<span class="comment-author">
<?php echo htmlspecialchars($commenter_name); ?>
<?php if (!empty($comment['user_name'])): ?><span class="admin-badge">作者</span><?php endif; ?>
</span>
<a href="#comment-form-box" class="reply-btn" onclick="setReply('<?php echo addslashes(htmlspecialchars($commenter_name)); ?>')">回复</a>
<span class="comment-date"><?php echo date('Y-m-d H:i', strtotime($comment['created_at'])); ?></span>
</div>
<div class="comment-text"><?php echo htmlspecialchars($comment['content']); ?></div>
</div>
</div>
<?php endforeach; ?>
<?php else: ?>
<p style="color:#aaa;">暂无评论,快来抢沙发吧!</p>
<?php endif; ?>
<hr style="border:none;border-top:1px solid #eee;margin:20px 0;">
<div id="comment-form-box">
<?php if ($is_admin_logged_in): ?>
<div class="admin-notice">
<span>👋 欢迎回来,<b><?php echo htmlspecialchars($_SESSION['username']); ?></b>!您正在以管理员身份回复。</span>
<a href="../admin/logout.php">退出登录</a>
</div>
<form method="POST">
<textarea id="comment-textarea" name="content" rows="4" placeholder="写下你的官方回复..." required></textarea>
<button type="submit" name="submit_comment">提交回复</button>
</form>
<?php else: ?>
<h4>发表评论</h4>
<form method="POST">
<input type="text" name="guest_name" placeholder="你的昵称 *" required>
<!-- 【修改】提示用户填写 QQ 邮箱以获取头像 -->
<input type="email" name="guest_email" placeholder="你的 QQ 邮箱 (用于显示 QQ 头像)">
<textarea id="comment-textarea" name="content" rows="4" placeholder="写下你的评论..." required></textarea>
<button type="submit" name="submit_comment">提交评论</button>
</form>
<?php endif; ?>
</div>
</div>
</div>
<?php require_once __DIR__ . '/sidebar-right.php'; ?>
</div>
<!-- 【结构优化】将 footer 移出 container,使其能够横跨整个屏幕宽度 -->
<?php require_once __DIR__ . '/footer.php'; ?>
</div>
<script>
function setReply(name) {
const textarea = document.getElementById('comment-textarea');
textarea.value = '@' + name + ' ';
textarea.focus();
}
</script>
</body>
</html>