<?php
//禁止用于违法，此程序无任何后门，无任何联系方式，禁止任何人倒卖和联网使用
include 'xinchengxu/t.php';  //xinchengxu文件夹可以改名 但是改名后一定要修改本行引用代码
// include 'gfw.php';
include_once 'data/config.php';
if ($qiangyinon ==1) {
include 'xinchengxu/301.php';  //xinchengxu文件夹可以改名 但是改名后一定要修改本行引用代码
}
ini_set('memory_limit', '10240M');
header('Content-Type: text/html; charset=utf-8');
$templateFolder = 'data/muban/';
$templates = glob($templateFolder . '*.html');
$template = $templates[array_rand($templates)];
$moban = file_get_contents($template);
use sqhlib\Hanzi\HanziConvert;
include_once 'data/fanti/HanziConvert.php';

function encodeValue($str) {
    $content_sz = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
    $encodedValue = '';
    foreach ($content_sz as $content) {
        $encodedValue .= '&#' . base_convert(bin2hex(mb_convert_encoding($content, 'ucs-4', 'utf-8')), 16, 10);
    }
    return $encodedValue;
}

$titlegs_list = file(__DIR__ . '/data/title.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomTitle = array_rand(array_flip($titlegs_list));
$moban = str_replace('{标题格式}', trim($randomTitle), $moban);



$miaoshugs_list = file(__DIR__ . '/data/miaoshu.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomMiaoshu = array_rand(array_flip($miaoshugs_list));

if ($miaoshuSwitch == 1) {
    $randomMiaoshu = encodeValue($randomMiaoshu);
}

$moban = str_replace('{描述格式}', trim($randomMiaoshu), $moban);


$fuzhu_list = file(__DIR__ . '/data/fuzhu.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomFuzhu = array_rand(array_flip($fuzhu_list));
if ($fzms1Switch == 1) {
    $randomFuzhu = encodeValue($randomFuzhu);
}
$moban = str_replace(['{辅助描述}', '{辅助描述1}'], trim($randomFuzhu), $moban);

$fuzhu2_list = file(__DIR__ . '/data/fzms2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomFuzhu2 = array_rand(array_flip($fuzhu2_list));
if ($fzms2Switch == 1) {
    $randomFuzhu2 = encodeValue($randomFuzhu2);
}
$moban = str_replace('{辅助描述2}', trim($randomFuzhu2), $moban);



$url_list = file(__DIR__ . '/data/url.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$moban = preg_replace_callback('/\{链接\}/', function($match) use ($url_list) {
    $randomurl = array_rand(array_flip($url_list));
    return trim($randomurl);
}, $moban);

$randomVersion = 'V' . mt_rand(1, 9) . '.' . mt_rand(0, 19) . '.' . mt_rand(0, 19);
$moban = preg_replace('/\{当前版本\}/', $randomVersion, $moban, 10);

$moban = preg_replace_callback('/\{随机版本\}/', function($matches) {
    return 'V.' . mt_rand(1, 9) . '.' . mt_rand(0, 19) . '.' . mt_rand(0, 19);
}, $moban);

$moban = preg_replace_callback('/{随机数字(\d+)}/', function($match) {
    $length = intval($match[1]);
    return mt_rand(pow(10, ($length - 1)), pow(10, $length) - 1);
}, $moban);

$moban = preg_replace_callback('/{随机数字(\d+)-(\d+)}/', function($match) {
    $min_length = intval($match[1]);
    $max_length = intval($match[2]);

    // 生成指定长度范围内的随机数字
    $random_length = mt_rand($min_length, $max_length);
    $min_range = pow(10, $random_length - 1);
    $max_range = pow(10, $random_length) - 1;

    return mt_rand($min_range, $max_range);
}, $moban);

$moban = preg_replace_callback('/\{固定随机字符(\d+)?\}|\{固定字符(\d+)?\}/', function($match) {
    if (!empty($match[1])) {
        $length = intval($match[1]);
        // 限制随机位数在1-20之间
        $length = max(1, min(20, $length));
    } else if (!empty($match[2])) {
        $length = intval($match[2]);
        // 限制随机位数在1-20之间
        $length = max(1, min(20, $length));
    } else {
        // 如果未指定数字，则随机生成1-20位长度
        $length = rand(1, 20);
    }
    
    // 检查是否已经生成过随机字符
    if(isset($_SESSION['randomString'])) {
        $randomString = $_SESSION['randomString'];
    } else {
        $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';//要大写就加入 ABCDEFGHIJKLMNOPQRSTUVWXYZ
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        // 保存生成的随机字符到会话中
        $_SESSION['randomString'] = $randomString;
    }
    
    return $randomString;
}, $moban);

$moban = preg_replace_callback('/\{随机字符(\d+)\}|\{字符(\d+)\}/', function($match) {
    if (!empty($match[1])) {
        $length = intval($match[1]);
    } else if (!empty($match[2])) {
        $length = intval($match[2]);
    } else {
        return $match[0];
    }
    //$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}, $moban);

$moban = preg_replace_callback('/{随机字母(\d+)}/', function($match) {
    $length = intval($match[1]);

    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}, $moban);

$moban = preg_replace_callback('/{小写字母(\d+)}/', function($match) {
    $length = intval($match[1]);

    $characters = 'abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}, $moban);

$moban = preg_replace_callback('/{大写字母(\d+)}/', function($match) {
    $length = intval($match[1]);

    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}, $moban);

// $class
$domain = $_SERVER['HTTP_HOST'];
$domainWithoutDot = str_replace('.', '', $domain);
if ($class == 1) {
    $moban = preg_replace_callback(
        '/class="([^"]*)"/',
        function ($matches) use ($domainWithoutDot) {
            return 'class="' . $domainWithoutDot . ' ' . $matches[1] . '"';
        },
        $moban
    );
}

// $class1
$domainWithoutDot = $domain;
if ($class1 == 1) {
    $moban = preg_replace_callback(
        '/class="([^"]*)"/',
        function ($matches) use ($domainWithoutDot) {
            return 'class="' . $domainWithoutDot . ' ' . $matches[1] . '"';
        },
        $moban
    );
}

// $class2
$random1 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
$random2 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
$random3 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
$random4 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
$domainWithoutDot = $random1 . '-' . $random2 . '-' . $random3 . '-' . $random4;
if ($class2 == 1) {
    $moban = preg_replace_callback(
        '/class="([^"]*)"/',
        function ($matches) use ($domainWithoutDot) {
            return 'class="' . $domainWithoutDot . ' ' . $matches[1] . '"';
        },
        $moban
    );
}

if ($class3 == 1) {
    // 定义可用字符
    $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';

    // 替换模板中的 class 属性
    $moban = preg_replace_callback('/class="([^"]*)"/', function ($matches) use ($characters) {
        $class3Value = ''; // 用于存储生成的字符串

        // 生成 6 位随机字符串
        for ($i = 0; $i < 6; $i++) {
            $class3Value .= $characters[rand(0, strlen($characters) - 1)]; // 随机选择字符
        }

        return 'class="' . $class3Value . ' ' . $matches[1] . '"'; // 返回生成的字符串
    }, $moban);
}

/**全部模版固定一个
if ($class3 == 1) {
    // 定义可用字符
    $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $class3Value = ''; // 用于存储生成的字符串

    // 生成 6 位随机字符串
    for ($i = 0; $i < 6; $i++) {
        $class3Value .= $characters[rand(0, strlen($characters) - 1)]; // 随机选择字符
    }

    // 替换模板中的 {class3} 占位符
    $moban = preg_replace_callback('/class="([^"]*)"/', function ($matches) use ($class3Value) {
        return 'class="' . $class3Value . ' ' . $matches[1] . '"'; // 返回生成的字符串
    }, $moban);
}
*/

$biaoqing_list = file(__DIR__ . '/data/biaoqing.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randombiaoqing = array_rand(array_flip($biaoqing_list));
$moban = str_replace('{表情}', trim($randombiaoqing), $moban);

$img_files = glob('data/img/*.txt');
$randomImgFile = $img_files[array_rand($img_files)];
$imgLines = file($randomImgFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$moban = preg_replace_callback('/\{图片\}|\{随机图片\}/', function () use ($imgLines) {
    return trim($imgLines[array_rand($imgLines)]);
}, $moban);

$keywords_files = glob('data/keywords/*.txt');
$randomKeywordsFile = $keywords_files[array_rand($keywords_files)];
$keywordLines = file($randomKeywordsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!empty($keywordLines)) {
    $keyword = $keywordLines[array_rand($keywordLines)];
} else {
    $keyword = "";
}

$selectedKeyword = $keyword;

$keywordFiles = glob('data/keywords/*.txt');
$randomKeywordFile = $keywordFiles[array_rand($keywordFiles)];
$keywordLines = file($randomKeywordFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);


$juzi_files = glob('data/juzi/*.txt');
$randomJuziFile = $juzi_files[array_rand($juzi_files)];
$juziLines = file($randomJuziFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$moban = preg_replace_callback('/\{句子\}|\{随机句子\}/', function () use ($juziLines, $zmjuziSwitch) {
    $randomJuzi = trim($juziLines[array_rand($juziLines)]);
    
    if ($zmjuziSwitch == 1) {
        // 使用encodeValue转码
        $randomJuzi = encodeValue($randomJuzi);
    }
    
    return $randomJuzi;
}, $moban);

$title_files = glob('data/title/*.txt');
$randomtitleFile = $title_files[array_rand($title_files)];
$titleLines = file($randomtitleFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$moban = preg_replace_callback('/\{标题\}|\{随机标题\}/', function () use ($titleLines, $zmtitleSwitch) {
    $randomTitle = trim($titleLines[array_rand($titleLines)]);
    
    if ($zmtitleSwitch == 1) {
        // 使用encodeValue转码
        $randomTitle = encodeValue($randomTitle);
    }
    
    return $randomTitle;
}, $moban);

$reci_files = glob('data/reci/*.txt');
$randomreciFile = $reci_files[array_rand($reci_files)];
$reciLines = file($randomreciFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$moban = preg_replace_callback('/\{热词\}|\{随机热词\}/', function () use ($reciLines, $reciSwitch) {
    $randomHotWord = trim($reciLines[array_rand($reciLines)]);
    
    if ($reciSwitch == 1) {
        // 使用encodeValue转码
        $randomHotWord = encodeValue($randomHotWord);
    }
    
    return $randomHotWord;
}, $moban);

$xingming_files = glob('data/name/*.txt');
$randomxingmingFile = $xingming_files[array_rand($xingming_files)];
$xingmingLines = file($randomxingmingFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$moban = preg_replace_callback('/\{姓名\}|\{随机姓名\}/', function () use ($xingmingLines, $xingmingSwitch) {
    $randomNameWord = trim($xingmingLines[array_rand($xingmingLines)]);
    
    // if ($xingmingSwitch == 1) {
    //     // 使用encodeValue转码
    //     $randomNameWord = encodeValue($randomNameWord);
    // }
    
    return $randomNameWord;
}, $moban);

$url = $_SERVER['HTTP_HOST'];
preg_match('/[\w][\w-]*\.(?:com\.cn|net\.cn|org\.cn|gov\.cn|ren|top|com|xyz|shop|mobi|kim|biz|work|store|online|wiki|video|show|world|chat|fund|guru|email|fashion|yoga|host|website|bio|green|pet|promo|VOTO|wang|sohu|net|vip|ink|red|ltd|auto|law|tech|art|love|social|cool|cfd|cx|today|company|gold|run|life|fit|space|archi|black|Lotto|pink|ski|citic|xin|club|site|info|pro|group|link|Beer|fun|design|center|team|zone|city|live|plus|pub|co|luxe|baidu|cloud|press|asia|blue|organic|poker|vote|com|net|space|pro|cyou|org|info|biz|me|mobi|name|cc|tv|co|io|in|cn|us|eu|uk|la|ws|au|jp|kr|shop|xyz|me|fun|store|ltd|pro|xin|vip|site|online|club|work|top|icu|cn|edu|net|org|gov|cc|biz|tech|info)(\/|$)/isU', $url, $match);
$zym = $match[0];
$moban = str_replace("{根域名}", $zym, $moban);
$moban = str_replace("{主域名}", $_SERVER['HTTP_HOST'], $moban);
//$moban = str_replace("<title>", "<!--禁止用于违法、违规，禁止联网使用本源码，仅供本地学习--><title>", $moban);
$moban = str_replace("<title>", "<title>", $moban);
$currentUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$moban = str_replace("{当前url}", $currentUrl, $moban);
$now = time();
$yesterday = strtotime('-1 day');
for ($i = 0; $i < 1000; $i++) {
    $randomTimestamp = mt_rand($yesterday, $now);
    $sjtime = date('Y-m-d H:i:s', $randomTimestamp);
    $moban = preg_replace('/{随机时间}|{动态时间}/', $sjtime, $moban, 1);
}
$time = date("Y-m-d H:i:s");
$time2 = date("Y年m月d日 l");
$weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
$weekdayEnglish = date("l");
$weekdayChinese = $weekdays[array_search($weekdayEnglish, $weekdays)];
$time2 = str_replace($weekdayEnglish, $weekdayChinese, $time2);
$time3 = date("Y-m-d");
$time4 = date("Y");
$time5 = date("m");
$time6 = date("d");
$time8 = time();

$moban = preg_replace([
    '/{时间}|{当前时间}/',
    '/{当前日期}/',
    '/{年月日}/',
    '/{年}/',
    '/{月}/',
    '/{日}/',
    '/{时间戳}/'
], [
    $time,
    $time2,
    $time3,
    $time4,
    $time5,
    $time6,
    $time8
], $moban);

/*
$NEWS_URLS = array(
    "https://www.chinanews.com/china.shtml",
    "https://www.chinanews.com/scroll-news/news1.html",
    "https://www.chinanews.com/scroll-news/news2.html",
    "https://www.chinanews.com/scroll-news/news3.html"
);
$NEWS_URL = $NEWS_URLS[array_rand($NEWS_URLS)];
$html = file_get_contents($NEWS_URL);
preg_match_all('#<div class="dd_bt">.*?<a href="(.*?)".*?>(.*?)</a>.*?</div>#is', $html, $matches);
$index = rand(0, count($matches[0])-1);
$link = $matches[1][$index];
$xwtitle = $matches[2][$index];
if (preg_match("#^https?://#i", $link)) {
    $url = $link;
} else {
    $url = "https://www.chinanews.com/" . ltrim($link, "/");
}
$xwbody_html = file_get_contents($url);
preg_match_all('#<div class="(left_zw|content_desc|current_img)"[^>]*>(.*?)<div class="clear">#is', $xwbody_html, $matches);
$xwbody = isset($matches[1][0]) ? $matches[2][0] : "";
$xwbody = preg_replace('/【编辑:(.*?)】/', '', $xwbody);
$xwbody = preg_replace('/责任编辑：【(.*?)】/', '', $xwbody);
*/

$folderPath = 'data/news/'.date("Y-m-d").'/';
$files = glob($folderPath . '*.txt');

if (!empty($files)) {
    $randomFile = $files[array_rand($files)];
    $xwtitle = basename($randomFile, ".txt");
    $xwbody = file_get_contents($randomFile);
}

if ($zmtitleSwitch == 1) {
    $moban = str_replace('{新闻标题}', encodeValue($xwtitle), $moban);
} else {
    $moban = str_replace('{新闻标题}', $xwtitle, $moban);
}

$moban = str_replace('{新闻内容}', $xwbody, $moban);

if ($zmkeywordSwitch == 1) {
    $selectedKeyword = encodeValue($keyword);
} else {
    $selectedKeyword = $keyword;
} 

if ($crgjcSwitch == 1) {
    $crgjc = '<a href="'.$currentUrl.'" alt="'.$selectedKeyword.'"><strong>'.$selectedKeyword.'</strong></a>';
    // 随机生成插入数量（1-3个）
    $insertCount = rand(1, 3);

    for ($i = 0; $i < $insertCount; $i++) {
        // 匹配中文文本并获取所有匹配结果
        preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $xwbody, $matches);
        $chineseTexts = $matches[0];

        if (count($chineseTexts) > 0) {
            // 随机选择一个中文文本作为插入位置
            $insertPosition = rand(0, count($chineseTexts) - 1);

            // 在插入位置处插入 $crgjc
            $xwbody = mb_substr($xwbody, 0, mb_strpos($xwbody, $chineseTexts[$insertPosition], 0, 'utf-8'), 'utf-8')
                . $crgjc . mb_substr($xwbody, mb_strpos($xwbody, $chineseTexts[$insertPosition], 0, 'utf-8'), null, 'utf-8');
        }
    }
}

$folderPath = 'data/gpt/';
$files = glob($folderPath . '*.txt');
if (!empty($files)) {
    $randomFile = $files[array_rand($files)];
    $bdtitle = basename($randomFile, ".txt");
    $bdbody = file_get_contents($randomFile);
}

  
if ($ybdwitch == 1) {
    // 替换{关键词}
    $bdtitleArr = explode("\n", $bdtitle); // 将$bdtitle按行分割成数组
    $randomKeyword = trim($bdtitleArr[array_rand($bdtitleArr)]); // 随机选择一个关键词

    // 获取标题长度
    $titleLength = mb_strlen($bdtitle, 'utf-8');
    // 在随机位置插入 $randomKeyword
    $randomPosition = mt_rand(0, $titleLength);
    $result = mb_substr($bdtitle, 0, $randomPosition, 'utf-8') . $randomKeyword . mb_substr($bdtitle, $randomPosition, null, 'utf-8');

    $moban = str_replace('{文章标题}', $result, $moban);
    $moban = preg_replace_callback('/\{文章标题插词\}/', function () use ($result) {
        return $result;
    }, $moban);
    $moban = str_replace('{文章内容}', $bdbody, $moban);
    $moban = str_replace('{关键词}', encodeValue($randomKeyword), $moban);
    // 多次替换{随机关键词}
    while (strpos($moban, '{随机关键词}') !== false) {
        $randomFile = $files[array_rand($files)];
        $randomKeyword2 = basename($randomFile, ".txt");
        $moban = preg_replace('/{随机关键词}/', encodeValue($randomKeyword2), $moban, 1);
    }
} else {
$moban = str_replace('{关键词}', $selectedKeyword, $moban);
    $moban = preg_replace_callback('/\{随机关键词\}/', function () use ($keywordLines) {
        return trim($keywordLines[array_rand($keywordLines)]);
    }, $moban);

    // 将$xwtitle分割为数组
    $titleArray = preg_split('//u', $xwtitle, -1, PREG_SPLIT_NO_EMPTY);
    // 获取数组长度
    $titleLength = count($titleArray);
    // 随机插入位置
    $insertPosition = mt_rand(0, $titleLength);
    // 在指定位置插入$selectedKeyword
    array_splice($titleArray, $insertPosition, 0, $selectedKeyword);
    // 拼接标题字符串
    $result = implode('', $titleArray);

    $moban = str_replace('{文章标题}', $xwtitle, $moban);
    $moban = str_replace('{文章标题插词}', $result, $moban);
    $moban = str_replace('{新闻标题插词}', $result, $moban);
    $moban = str_replace('{文章内容}', $xwbody, $moban);
}

if ($zmtitleSwitch == 1) {
    $moban = str_replace('{文章标题}', encodeValue($xwtitle), $moban);
    $moban = str_replace('{文章标题插词}', encodeValue($result), $moban);
    $moban = str_replace('{新闻标题插词}', encodeValue($result), $moban);
} else {
    $moban = str_replace('{文章标题插词}', $result, $moban);
    $moban = str_replace('{新闻标题插词}', $result, $moban);
    $moban = str_replace('{文章内容}', $xwbody, $moban);
}
// 引入拼音转换类库以及文件操作类库
require_once __DIR__ . '/data/pinyin.php';

// 获取 data 目录下所有的 txt 文件
$dir = 'data/juzi/';
$files = scandir($dir);
$txtFiles = array_filter($files, function($file) {
    return pathinfo($file, PATHINFO_EXTENSION) === 'txt';
});

// 循环生成10个带拼音的句子
for ($i = 1; $i <= 10; $i++) {
    // 随机选取一个 txt 文件，并读取其中的一行中文
    $filename = $dir . $txtFiles[array_rand($txtFiles)];
    $line = '';
    if (($handle = fopen($filename, 'r')) !== false) {
        $randomLineNum = rand(0, count(file($filename)) - 1); // 随机选取一行
        while (($row = fgets($handle)) !== false) {
            if (--$randomLineNum < 0) {
                $line = trim($row);
                break;
            }
        }
        fclose($handle);
    }

    // 去除字符串中的空格和空字符
    $line = preg_replace('/[\s　]+/u', '', $line);

    // 将中文转换为带拼音的格式
    $pyLine = '';
    $pyLine1 = '';
    for ($j = 0; $j < mb_strlen($line); $j++) {
        $char = mb_substr($line, $j, 1);
        $pinyin = Pinyin::getPinyin($char, 'UTF-8');
        if (!empty($pinyin)) {
            $pyLine .= $pinyin;
            $pyLine1 .= $char . '(' . $pinyin . ')';
        } else {
            $pyLine .= $char;
            $pyLine1 .= $char;
        }
    }

    // 替换模板中的占位符{拼音内容}为转换后的拼音内容
    $moban = str_replace('{拼音内容}', $pyLine, $moban);
    $moban = str_replace('{拼音内容2}', $pyLine1, $moban);
}



//繁体功能
if ($fantiSwitch == 1) {
    // 使用 HanziConvert 类进行简繁体转换
    $moban = HanziConvert::convert($moban, true);
} else {
}

$context = stream_context_create([
    'http' => [
        'timeout' => 0.5, // 设置超时时间为500毫秒
    ],
]);
if ($xgcwitch == 1) {
$xgurl = "https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&wd=";
if ($ybdwitch == 1) {
    $xgurl .= urlencode($randomKeyword);
} else {
    $xgurl .= urlencode($selectedKeyword);
}
    
    
    $json_data = @file_get_contents($xgurl, false, $context);

    if ($json_data !== false) {
        $xgdata = json_decode($json_data, true);
        $jieda = "";

        if (isset($xgdata['g'])) {
            foreach ($xgdata['g'] as $i => $xgitem) {
                if ($i < 3) { // 最多显示3组内容
                    $jieda .= "<p>第" . ($i + 1) . " ".$randombiaoqing . encodeValue($xgitem['q']) . $randomHotWord . "</p>";
                }
            }
        }
        $moban = preg_replace('/(<p>)(.*?)(<\/p>)/', '${1}' . $jieda . '${2}${3}', $moban, 1);
    } else {
        $moban = preg_replace('/(<p>)(.*?)(<\/p>)/', '', $moban, 1);
    }
}

// 缓存开关为1时，生成缓存文件
if ($cacheSwitch == 1) {
    $cacheFolder = 'cache/';
    if (!file_exists($cacheFolder)) {
        mkdir($cacheFolder, 0777, true);
    }

    // 使用md5命名缓存文件
    $cacheName = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    $cacheFile = $cacheFolder . $cacheName;

    // 检查缓存文件是否存在
    if (file_exists($cacheFile)) {
        // 如果缓存文件存在，则直接读取并输出缓存内容
        echo file_get_contents($cacheFile);
        exit;
    } else {
        // 缓存文件不存在，将模板内容写入缓存文件
        file_put_contents($cacheFile, $moban);
    }
}

echo $moban;
?>