<?php include 'zhizhu/tongji.php'; ?>
<?php include '301.php'; ?>
<?php
// 获取当前完整URL
function getCurrentUrl() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $uri = $_SERVER['REQUEST_URI'];
    return $protocol . "://" . $host . $uri;
}

// 判断是否为首页
function isHomePage($url) {
    $path = parse_url($url, PHP_URL_PATH);
    return $path === '/' || $path === '' || $path === '/index.php';
}

// 读取文件内容
function readFileContent($filePath) {
    if (file_exists($filePath)) {
        return file_get_contents($filePath);
    }
    return '';
}

// 从文件夹中随机获取一个文件
function getRandomFile($dir) {
    if (!is_dir($dir)) return false;
    
    $files = glob($dir . '/*');
    if (empty($files)) return false;
    
    return $files[array_rand($files)];
}

// 从文件夹中随机获取多个文件
function getRandomFiles($dir, $count) {
    if (!is_dir($dir)) return [];
    
    $files = glob($dir . '/*');
    if (empty($files)) return [];
    
    shuffle($files);
    return array_slice($files, 0, $count);
}

// 从文本文件中随机获取一行
function getRandomLineFromFile($filePath) {
    if (!file_exists($filePath)) return '';
    
    $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (empty($lines)) return '';
    
    return $lines[array_rand($lines)];
}

// 替换主关键词和随机关键词
function replaceRandomKeywords($content) {
    // 统计并获取所有{随机关键词}占位符
    $pattern = '/\{随机关键词\}/';
    preg_match_all($pattern, $content, $matches);
    $count = count($matches[0]);
    
    if ($count == 0) {
        return $content; // 没有占位符，直接返回
    }
    
    // 关键词文件夹路径
    $keywordsDir = 'admin/data/keywords/';
    
    // 获取文件夹中所有txt文件
    $txtFiles = glob($keywordsDir . '*.txt');
    
    if (empty($txtFiles)) {
        return $content; // 没有关键词文件，返回原内容
    }
    
    // 逐个替换占位符
    for ($i = 0; $i < $count; $i++) {
        // 随机选择一个txt文件
        $randomFile = $txtFiles[array_rand($txtFiles)];
        
        // 读取文件内容
        $lines = file($randomFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        if (!empty($lines)) {
            // 随机选择一行
            $randomLine = $lines[array_rand($lines)];
            // 替换占位符
            $content = preg_replace($pattern, $randomLine, $content, 1);
        }
    }
    
    return $content;
}

// 替换随机图片
function replaceRandomImages($content) {
    $imgDir = 'img/';
    if (!is_dir($imgDir)) return $content;
    
    $images = glob($imgDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
    if (empty($images)) return $content;
    
    preg_match_all('/\{随机图片\}/', $content, $matches, PREG_OFFSET_CAPTURE);
    $replacements = [];
    
    foreach ($matches[0] as $match) {
        $randomImage = $images[array_rand($images)];
        $replacements[$match[1]] = $randomImage;
    }
    
    // 从后往前替换，避免位置变化影响
    krsort($replacements);
    foreach ($replacements as $pos => $img) {
        $content = substr_replace($content, $img, $pos, strlen('{随机图片}'));
    }
    
    return $content;
}

// 替换随机标题和文章简介
function replaceRandomTitlesAndDescriptions($content) {
    $articleDir = 'article/';
    if (!is_dir($articleDir)) return $content;
    
    $articles = glob($articleDir . '/*.txt');
    if (empty($articles)) return $content;
    
    // 处理随机标题
    preg_match_all('/\{随机标题\}/', $content, $titleMatches, PREG_OFFSET_CAPTURE);
    $titleReplacements = [];
    $usedArticles = [];
    
    foreach ($titleMatches[0] as $match) {
        $availableArticles = array_diff($articles, $usedArticles);
        if (empty($availableArticles)) {
            $availableArticles = $articles;
            $usedArticles = [];
        }
        
        $randomArticle = $availableArticles[array_rand($availableArticles)];
        $title = pathinfo($randomArticle, PATHINFO_FILENAME);
        $titleReplacements[$match[1]] = $title;
        $usedArticles[] = $randomArticle;
    }
    
    krsort($titleReplacements);
    foreach ($titleReplacements as $pos => $title) {
        $content = substr_replace($content, $title, $pos, strlen('{随机标题}'));
    }
    
    // 处理文章简介
    preg_match_all('/\{文章简介\}/', $content, $descMatches, PREG_OFFSET_CAPTURE);
    $descReplacements = [];
    $usedArticlesForDesc = [];
    
    foreach ($descMatches[0] as $match) {
        $availableArticles = array_diff($articles, $usedArticlesForDesc);
        if (empty($availableArticles)) {
            $availableArticles = $articles;
            $usedArticlesForDesc = [];
        }
        
        $randomArticle = $availableArticles[array_rand($availableArticles)];
        $articleContent = file_get_contents($randomArticle);
        $description = mb_substr(strip_tags($articleContent), 0, 100);
        $descReplacements[$match[1]] = $description;
        $usedArticlesForDesc[] = $randomArticle;
    }
    
    krsort($descReplacements);
    foreach ($descReplacements as $pos => $desc) {
        $content = substr_replace($content, $desc, $pos, strlen('{文章简介}'));
    }
    
    return $content;
}

// 替换链接和数字/字符/字母
function replaceLinksAndPatterns($content) {
    // 替换链接
    $urlFile = 'admin/zhan/url.txt';
    if (file_exists($urlFile)) {
        $urls = file($urlFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!empty($urls)) {
            preg_match_all('/\{链接\}/', $content, $matches, PREG_OFFSET_CAPTURE);
            $replacements = [];
            
            foreach ($matches[0] as $match) {
                $randomUrl = $urls[array_rand($urls)];
                $replacements[$match[1]] = $randomUrl;
            }
            
            krsort($replacements);
            foreach ($replacements as $pos => $url) {
                $content = substr_replace($content, $url, $pos, strlen('{链接}'));
            }
        }
    }
    
    // 替换数字1-9
    for ($i = 1; $i <= 9; $i++) {
        $pattern = '{数字' . $i . '}';
        $content = preg_replace_callback('/' . preg_quote($pattern, '/') . '/', function() use ($i) {
            $min = pow(10, $i - 1);
            $max = pow(10, $i) - 1;
            return strval(mt_rand($min, $max));
        }, $content);
    }
    
    // 替换字符1-9
    for ($i = 1; $i <= 9; $i++) {
        $pattern = '{字符' . $i . '}';
        $content = preg_replace_callback('/' . preg_quote($pattern, '/') . '/', function() use ($i) {
            $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $result = '';
            for ($j = 0; $j < $i; $j++) {
                $result .= $characters[mt_rand(0, strlen($characters) - 1)];
            }
            return $result;
        }, $content);
    }
    
    // 替换字母1-9
    for ($i = 1; $i <= 9; $i++) {
        $pattern = '{字母' . $i . '}';
        $content = preg_replace_callback('/' . preg_quote($pattern, '/') . '/', function() use ($i) {
            $characters = 'abcdefghijklmnopqrstuvwxyz';
            $result = '';
            for ($j = 0; $j < $i; $j++) {
                $result .= $characters[mt_rand(0, strlen($characters) - 1)];
            }
            return $result;
        }, $content);
    }
    
    return $content;
}

// 替换文章标题和内容
function replaceArticleContent($content) {
    $articleDir = 'article/';
    if (!is_dir($articleDir)) return $content;
    
    // 替换文章标题
    if (strpos($content, '{文章标题}') !== false) {
        $articles = glob($articleDir . '/*.txt');
        if (!empty($articles)) {
            $randomArticle = $articles[array_rand($articles)];
            $title = pathinfo($randomArticle, PATHINFO_FILENAME);
            $content = str_replace('{文章标题}', $title, $content);
            
            // 替换文章内容
            $articleContent = file_get_contents($randomArticle);
            $imgDir = 'img/';
            $images = is_dir($imgDir) ? glob($imgDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE) : [];
            
            if (!empty($images)) {
                // 随机选择3张不同的图片
                $selectedImages = [];
                if (count($images) >= 3) {
                    $selectedImages = (array)array_rand($images, 3);
                    $selectedImages = array_map(function($index) use ($images) {
                        return $images[$index];
                    }, $selectedImages);
                } else {
                    $selectedImages = $images;
                }
                
                // 在随机句号后插入图片
                $sentences = explode('。', $articleContent);
                $insertPositions = array_rand($sentences, min(3, count($sentences) - 1));
                
                if (!is_array($insertPositions)) {
                    $insertPositions = [$insertPositions];
                }
                
                foreach ($insertPositions as $i => $pos) {
                    if ($pos > 0 && isset($selectedImages[$i])) {
                        $sentences[$pos] .= '。<img src="' . $selectedImages[$i] . '" alt="">';
                    }
                }
                
                $articleContent = implode('。', $sentences);
            }
            
            $content = str_replace('{文章内容}', $articleContent, $content);
        }
    }
    
    return $content;
}

// 主处理函数
function processTemplate($content) {
    // 替换站点名称
    $siteNameFile = 'admin/zhan/zdmc.txt';
    if (file_exists($siteNameFile)) {
        $siteName = getRandomLineFromFile($siteNameFile);
        $content = str_replace('{站点名称}', $siteName, $content);
    }
    
    // 替换描述
    $descriptionFile = 'admin/zhan/description.txt';
    if (file_exists($descriptionFile)) {
        $description = getRandomLineFromFile($descriptionFile);
        $content = str_replace('{描述}', $description, $content);
    }
    
    // 替换发布时间
    $content = str_replace('{发布时间}', date('Y-m-d H:i:s'), $content);
    
    // 替换主关键词和随机关键词
    $content = replaceRandomKeywords($content, '{主关键词}');
    $content = replaceRandomKeywords($content, '{随机关键词}');
    
    // 替换随机图片
    $content = replaceRandomImages($content);
    
    // 替换随机标题和文章简介
    $content = replaceRandomTitlesAndDescriptions($content);
    
    // 替换链接和数字/字符/字母
    $content = replaceLinksAndPatterns($content);
    
    // 替换文章标题和内容
    $content = replaceArticleContent($content);
    
    return $content;
}

// 缓存处理
function handleCache($content, $url) {
    $cacheDir = 'cache/';
    if (!is_dir($cacheDir)) {
        mkdir($cacheDir, 0755, true);
    }
    
    $cacheFile = $cacheDir . md5($url) . '.html';
    $hcFile = 'admin/zhan/hc.txt';
    
    if (file_exists($hcFile)) {
        $hcSetting = trim(file_get_contents($hcFile));
        if ($hcSetting === 'on') {
            // 写入缓存
            file_put_contents($cacheFile, $content);
        } elseif ($hcSetting === 'off') {
            // 不处理缓存
        }
    }
    
    return $content;
}

// 主程序
$currentUrl = getCurrentUrl();
$isHome = isHomePage($currentUrl);

// 检查缓存
$cacheDir = 'cache/';
$cacheFile = $cacheDir . md5($currentUrl) . '.html';
$hcFile = 'admin/zhan/hc.txt';

if (file_exists($hcFile) && trim(file_get_contents($hcFile)) === 'on' && file_exists($cacheFile)) {
    // 从缓存读取
    echo file_get_contents($cacheFile);
    exit;
}

// 选择模板
$templateFile = $isHome ? 'tpl/mb1/index.html' : 'tpl/mb1/show.html';
$templateContent = readFileContent($templateFile);

if ($templateContent === '') {
    die('模板文件不存在或为空');
}

// 处理模板内容
$processedContent = processTemplate($templateContent);

// 处理缓存
$finalContent = handleCache($processedContent, $currentUrl);

// 输出最终内容
echo $finalContent;
?>