main
xgkblog/index.php
index.php8.8 KB

<?php
// 1. 引入配置文件并连接数据库
if (!file_exists(__DIR__ . '/config.php')) {
    die('系统未安装!请先访问 <a href="install/">安装向导</a>');
}
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());
}

// --- 分页配置 ---
$per_page = 5; 
// 【已修复】确保页码始终是整数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1; 
if ($page < 1) $page = 1;
$offset = ($page - 1) * $per_page;

// --- 基础数据查询 (分类、页面) ---
$stmt_categories = $pdo->query("SELECT id, name, slug FROM categories ORDER BY id ASC");
$categories = $stmt_categories->fetchAll(PDO::FETCH_ASSOC);

$stmt_pages = $pdo->query("SELECT id, title, slug FROM pages ORDER BY id ASC");
$pages = $stmt_pages->fetchAll(PDO::FETCH_ASSOC);

// --- 动态构建 SQL (检测 status 字段) ---
$has_status = false;
try {
    $pdo->query("SELECT status FROM posts LIMIT 1");
    $has_status = true;
} catch (PDOException $e) {}

$where_clause = $has_status ? "WHERE p.status = 'published'" : "";

// --- 1. 计算总记录数 (用于分页) ---
$count_sql = "SELECT COUNT(*) as total FROM posts p $where_clause";
$total_posts = $pdo->query($count_sql)->fetch()['total'];
$total_pages = ceil($total_posts / $per_page);

// --- 2. 获取当前页文章 ---
$sql = "SELECT 
            p.id, p.title, p.content, p.created_at,
            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_clause
        ORDER BY p.created_at DESC 
        LIMIT :limit OFFSET :offset";

$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$posts = $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">
 
  
</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">
                <section class="card hero">
                 
                    <p>以笔墨为笺,收藏人间细碎!</p>
                    <div class="hero-buttons">
                        <a href="/admin/" class="btn btn-primary">开始使用</a>
                        <a href="/admin/post_edit.php" class="btn btn-outline">发表文章</a>
                    </div>
                </section>

                <div class="announcement">
                    <strong>📢 公告:</strong>家藏经史子集部,人在烟霞泉石间!
                </div>
                
                
                
                     <div class="wz-container">

    <?php if (!empty($posts)): ?>
    <?php 
    // 【新增】初始化一个计数器,用于判断奇偶数
    $count = 0; 
    ?>
    <?php foreach ($posts as $post): ?>
        <?php $count++; ?> <!-- 每次循环计数器加 1 -->
        
        <!-- 【核心】根据 $count 是奇数还是偶数,动态输出 wz-card-1 或 wz-card-2 -->
        <a href="post.php?id=<?php echo $post['id']; ?>" class="wz-card wz-card-<?php echo ($count % 2 == 1) ? '1' : '2'; ?>">
            
            <!-- 【已彻底修复】左侧图片区域 -->
            <div class="wz-card-image" style="background-image: url('<?php 
                // 【终极方案】使用 DOMDocument 安全提取第一张图片
                $thumb_src = '/uploads/default.jpg'; // 默认占位图
                
                // 如果文章内容不为空,尝试提取图片
                if (!empty($post['content'])) {
                    libxml_use_internal_errors(true); // 屏蔽 HTML5 标签产生的警告
                    $dom = new DOMDocument();
                    $dom->loadHTML(mb_convert_encoding($post['content'], 'HTML-ENTITIES', 'UTF-8'));
                    libxml_clear_errors();
                    
                    // 获取所有的 img 标签
                    $img_tags = $dom->getElementsByTagName('img');
                    
                    // 如果找到了至少一张图片,获取第一张的 src 属性
                    if ($img_tags->length > 0) {
                        $first_img = $img_tags->item(0)->getAttribute('src');
                        if (!empty($first_img)) {
                            $thumb_src = htmlspecialchars($first_img, ENT_QUOTES, 'UTF-8'); // 安全转义
                        }
                    }
                }
                
                echo $thumb_src;
            ?>');" 
                 onerror="this.style.backgroundImage='url(\'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22400%22 height=%22300%22><rect width=%22100%%22 height=%22100%%22 fill=%22%23eee%22/><text x=%2250%%22 y=%2250%%22 font-size=%2218%22 text-anchor=%22middle%22 dominant-baseline=%22middle%22 fill=%22%23999%22>No Image</text></svg>\')';">
            </div>
            
            <!-- 右侧文字内容区域 -->
            <div class="wz-card-content">
                <h2 class="wz-card-title"><?php echo htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8'); ?></h2>
                
                <p class="wz-card-desc">
                    <?php 
                    // 截取摘要并去除 HTML 标签
                    echo mb_substr(strip_tags($post['content']), 0, 150) . '...'; 
                    ?>
                </p>
                
                <div class="meta-info">
                    <!-- 时间 -->
                    <div class="meta-item">
                        <svg class="icon icon-time" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/></svg>
                        <span><?php echo date('Y-m-d', strtotime($post['created_at'])); ?></span>
                    </div>
                    
                    <!-- 作者/热度 -->
                    <div class="meta-item">
                        <svg class="icon icon-fire" viewBox="0 0 24 24"><path d="M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 17.41 3.8 13.5.67zM11.71 19c-1.78 0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 4.04 0 2.65-2.15 4.8-4.8 4.8z"/></svg>
                        <span><?php echo !empty($post['author_name']) ? htmlspecialchars($post['author_name'], ENT_QUOTES, 'UTF-8') : 'Admin'; ?></span>
                    </div>
                    
                    <!-- 分类 -->
                    <div class="meta-item">
                        <svg class="icon icon-tag" viewBox="0 0 24 24"><path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z"/></svg>
                        <span><?php echo !empty($post['category_name']) ? htmlspecialchars($post['category_name'], ENT_QUOTES, 'UTF-8') : '未分类'; ?></span>
                    </div>
                </div>
            </div>
        </a>
    <?php endforeach; ?>

    <!-- 【保留】分页区域 -->
    <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php 
            if ($page > 1) {
                echo '<a href="?page=' . ($page - 1) . '">« 上一页</a>';
            }
            for ($i = 1; $i <= $total_pages; $i++) {
                if ($i == $page) {
                    echo '<span class="current">' . $i . '</span>';
                } else {
                    echo '<a href="?page=' . $i . '">' . $i . '</a>';
                }
            }
            if ($page < $total_pages) {
                echo '<a href="?page=' . ($page + 1) . '">下一页 »</a>';
            }
            ?>
        </div>
    <?php endif; ?>

<?php else: ?>
    <div class="empty-state">
        <p>暂无已发布的文章,快去后台发布第一篇吧!</p>
    </div>
<?php endif; ?>
                    </div>
                </div>
            
            <?php require_once __DIR__ . '/sidebar-right.php'; ?>
           </div>

       <!-- 【结构优化】将 footer 移出 container,使其能够横跨整个屏幕宽度 -->
    <?php require_once __DIR__ . '/footer.php'; ?>
    </div>

   
    
    
        
</body>
</html>