<?php
error_reporting(0);
include '/www/wwwroot/gx/zhuanma/pz.php';
include '/www/wwwroot/gx/zhuanma/userads.php';
header('HTTP/1.1 200 OK');

// 初始化可能未定义的变量
$kuo_jia = $kuo_jia ?? "0";
$ascii_jia = $ascii_jia ?? "0";
$cache = $cache ?? "0";
$wzmk = '';
$wzsy = '';
define('DIR', dirname(__FILE__));
$category = basename(dirname(DIR));

// ==================== 工具函数 ====================
function randKey($len)
{
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $str = '';
    for ($i = 0; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $charsLen)];
    }
    return $str;
}

function rarray_rand($arr)
{
    if (!is_array($arr) || empty($arr)) {
        return 0;
    }
    return mt_rand(0, count($arr) - 1);
}

function varray_rand($arr)
{
    if (!is_array($arr) || empty($arr)) {
        return '';
    }
    return $arr[rarray_rand($arr)];
}

function get_folder_files($folder)
{
    if (!is_dir($folder)) return [];
    $files = scandir($folder);
    return array_values(array_diff($files, ['.', '..']));
}

function cut_string($str, $cut_len, $f)
{
    if (empty($str)) return '';
    $len = mb_strlen($str, 'utf-8');
    $content = '';
    for ($i = 0; $i < ceil($len / $cut_len); $i++) {
        $qzw = mb_substr($str, $cut_len * $i, $cut_len, 'utf-8');
        $zfbfd = "“”’‘；：、|、？。》，《【】）（！~·";
        if (preg_match('/^[\x7f-\xff]+$/', $qzw) && stripos($zfbfd, $qzw) === false) {
            $qzw = substr($qzw, 0, -3) . $f;
        }
        $content .= $qzw;
    }
    return trim($content);
}

/**
 * 生成符合真实ICP备案号格式的虚拟备案号
 */
function getFixedIcpByUrl($siteUrl) {
    $host = parse_url($siteUrl, PHP_URL_HOST);
    if (!$host) {
        $host = preg_replace('#^https?://#', '', $siteUrl);
        $host = explode('/', $host)[0];
    }
    
    $hash = crc32($host);
    $absHash = abs($hash);
    
    $provinces = ['京','津','沪','渝','冀','豫','云','辽','黑','湘','皖','鲁','新','苏','浙','赣','鄂','桂','甘','晋','蒙','陕','吉','闽','贵','粤','青','藏','川','宁','琼'];
    $province = $provinces[$absHash % count($provinces)];
    
    $currentYear = (int)date('Y');
    $year = 2010 + ($absHash % ($currentYear - 2009));
    $yearStr = sprintf("%04d", $year);
    
    $rand5 = $absHash % 100000;
    $sequenceStr = '0' . sprintf("%05d", $rand5);
    
    $mainId = $yearStr . $sequenceStr;
    return $province . "ICP备" . $mainId . "号";
}

/**
 * 根据网站地址生成固定且唯一的公安网安备案号
 */
function getPublicSecurityIcpNumber($siteUrl) {
    $host = parse_url($siteUrl, PHP_URL_HOST);
    if (!$host) {
        $host = preg_replace('#^https?://#', '', $siteUrl);
        $host = explode('/', $host)[0];
    }
    
    $hash = crc32($host);
    $absHash = abs($hash);
    
    $areaCodeMap = [
        '京' => '110000', '津' => '120000', '沪' => '310000', '渝' => '500000',
        '冀' => '130000', '豫' => '410000', '云' => '530000', '辽' => '210000',
        '黑' => '230000', '湘' => '430000', '皖' => '340000', '鲁' => '370000',
        '新' => '650000', '苏' => '320000', '浙' => '330000', '赣' => '360000',
        '鄂' => '420000', '桂' => '450000', '甘' => '620000', '晋' => '140000',
        '蒙' => '150000', '陕' => '610000', '吉' => '220000', '闽' => '350000',
        '贵' => '520000', '粤' => '440000', '青' => '630000', '藏' => '540000',
        '川' => '510000', '宁' => '640000', '琼' => '460000',
    ];
    
    $provinces = array_keys($areaCodeMap);
    $province = $provinces[$absHash % count($provinces)];
    $areaCode = $areaCodeMap[$province];
    
    $standardBit = '02';
    $sequence = ($absHash % 1000000);
    $sequenceStr = sprintf("%06d", $sequence);
    
    $fullNumber = $areaCode . $standardBit . $sequenceStr;
    
    return $province . "公网安备" . $fullNumber . "号";
}

// ==================== 获取搜索关键字 ====================
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword'], '/') : '';

// 检查是否提交了表单
$isFormSubmitted = isset($_GET['keyword']);

// 如果表单已提交且关键词不为空，则重定向
if ($isFormSubmitted && !empty($keyword)) {
    $redirectUrl = '/key/' . urlencode($keyword) . '/';
    if ($_SERVER['REQUEST_URI'] !== $redirectUrl) {
        header('Location: ' . $redirectUrl);
        exit;
    }
}

// ==================== 初始化文件缓存容器 ====================
$fileCache = [];

// ==================== 优化的文件读取函数（带静态缓存） ====================
function get_file_lines_cached($file_path, &$cache) {
    if (!is_file($file_path)) return [];
    if (!isset($cache[$file_path])) {
        $cache[$file_path] = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    }
    return $cache[$file_path];
}

// ==================== 加载juzi文件（只读一次） ====================
$wenku_list = get_folder_files('/www/wwwroot/gx/key/juzi/');
$selected_juzi_file = varray_rand($wenku_list);
$juzi_file_path = '/www/wwwroot/gx/key/juzi/' . $selected_juzi_file;
$juzi_lines = get_file_lines_cached($juzi_file_path, $fileCache);
$juzi = $bak_juzi = $juzi_lines;
$btjuzi = $juzi_lines;

// ==================== 加载句子块（按分类） ====================
$block_lines = [];
$site_type = $category;
$block_dir = '/www/wwwroot/gx/key/blocks/' . $site_type;
if (is_dir($block_dir)) {
    $block_files = glob($block_dir . '/block_*.txt');
    if (!empty($block_files)) {
        $selected_block_file = $block_files[array_rand($block_files)];
        $block_lines = file($selected_block_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    }
}

// ==================== 加载key文件 ====================
$key_list = get_folder_files(DIR . '/yanlong/data/key/');
$selected_key_file = varray_rand($key_list);
$key_file_path = DIR . '/yanlong/data/key/' . $selected_key_file;
$key_lines = get_file_lines_cached($key_file_path, $fileCache);
$kygjc1s = $key_lines;
$bak_key = $key_lines;

// ==================== 加载xsm文件（当前分类） ====================
$xsm_list = get_folder_files('/www/wwwroot/gx/key/'.$category.'/');
$selected_xsm_file = varray_rand($xsm_list);
$xsm_file_path = '/www/wwwroot/gx/key/'.$category.'/' . $selected_xsm_file;
$xsm_lines = get_file_lines_cached($xsm_file_path, $fileCache);
$sjxsms = $xsm_lines;

// ==================== 加载zz文件 ====================
$xszz_list = get_folder_files(DIR . '/yanlong/data/zz/');
$selected_zz_file = varray_rand($xszz_list);
$zz_file_path = DIR . '/yanlong/data/zz/' . $selected_zz_file;
$zz_lines = get_file_lines_cached($zz_file_path, $fileCache);
$sjxszzs = $zz_lines;

// ==================== 加载zj文件 ====================
$zj_list = get_folder_files(DIR . '/yanlong/data/zj/');
$selected_zj_file = varray_rand($zj_list);
$zj_file_path = DIR . '/yanlong/data/zj/' . $selected_zj_file;
$zj_lines = get_file_lines_cached($zj_file_path, $fileCache);
$zjs = $zj_lines;

// ==================== 其他文件加载 ====================
$image_list = get_folder_files(DIR . '/uploads/images/');
$image_list_small = get_folder_files(DIR . '/xiaoimages/');
$titlemxs = get_file_lines_cached(DIR . '/yanlong/data/title.txt', $fileCache);
$wzmcs = get_file_lines_cached(DIR . '/yanlong/data/wzmc.txt', $fileCache);
$wzdzs = get_file_lines_cached(DIR . '/yanlong/data/wzdz.txt', $fileCache);
$fbts = get_file_lines_cached(DIR . '/yanlong/data/fbt.txt', $fileCache);
$descriptions = get_file_lines_cached(DIR . '/yanlong/data/description.txt', $fileCache);
$jss = get_file_lines_cached(DIR . '/yanlong/data/js.txt', $fileCache);
$links = get_file_lines_cached(DIR . '/yanlong/data/link.txt', $fileCache);
$ascii_sz = get_file_lines_cached(DIR . '/yanlong/data/ascii.txt', $fileCache);

// ==================== 加载模板 ====================
$domain = preg_replace("/^www\./", "", $_SERVER["HTTP_HOST"] ?? ""); $host = "www." . $domain;
$host_hash = abs(crc32($host));
$template_idx = $host_hash % 6 + 1;
$templateFile = '/www/wwwroot/gx/muban/' . $template_idx . '/yl_shouye.html';
$moban = file_get_contents($templateFile);

// ==================== 替换基础变量 ====================
$site_name = trim(varray_rand($wzmcs));
$wangzhi = trim(varray_rand($wzdzs));
$moban = str_replace('<标题>', trim(varray_rand($titlemxs)), $moban);
$moban = str_replace('<网站名称>', $site_name, $moban);
$moban = str_replace('<网站地址>', $wangzhi, $moban);
$moban = str_replace('<副标题>', trim(varray_rand($fbts)), $moban);
$moban = str_replace('<描述>', trim(varray_rand($descriptions)), $moban);
$moban = str_replace('<js>', trim(varray_rand($jss)), $moban);

// ==================== 替换外链 ====================
$link_count = substr_count($moban, '<外链>');
for ($lk = 0; $lk < $link_count; $lk++) {
    $moban = preg_replace('/<外链>/', trim(varray_rand($links)), $moban, 1);
}

// ==================== 替换小说类型 ====================
$xslx_file = '/www/wwwroot/gx/fenlei/' . $category . '/xslx.txt';
if (is_file($xslx_file)) {
    $xslx_lines = file($xslx_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $xslx_lines = array_map('trim', $xslx_lines);
    
    preg_match_all('/<小说类型(\d+)>/', $moban, $matches);
    $maxNum = max(array_merge([0], $matches[1]));
    $lineCount = count($xslx_lines);
    
    for ($i = 1; $i <= $maxNum; $i++) {
        $index = ($i - 1) % $lineCount;
        $moban = str_replace("<小说类型{$i}>", $xslx_lines[$index], $moban);
    }
}

// ==================== 生成文章模块 ====================
$para_count = mt_rand(2, 3);
$wzmk = '';
for ($i = 0; $i < $para_count; $i++) {
    $wzmk .= "<p><句子></p>\r\n";
}
$moban = str_replace('<文章模块>', $wzmk, $moban);

// ==================== 生成首页文章模块 ====================
$home_para_count = mt_rand(2, 3);
$wzsy = '';
for ($i = 0; $i < $home_para_count; $i++) {
    $wzsy .= "<句子>";
}
$moban = str_replace('<首页文章模块>', $wzsy, $moban);

// ==================== 替换随机关键词 ====================
$kygjc1_count = substr_count($moban, '<随机关键词>');
for ($ksp = 0; $ksp < $kygjc1_count; $ksp++) {
    $moban = preg_replace('/<随机关键词>/', trim(varray_rand($kygjc1s)), $moban, 1);
}

// ==================== 替换固定关键词1-13 ====================
for ($i = 1; $i <= 13; $i++) {
    $gjc = trim(varray_rand($kygjc1s));
    $moban = str_replace("<关键词{$i}>", $gjc, $moban);
}

// ==================== 替换小说名 ====================
$sjxsm_count = substr_count($moban, '<随机小说名>');
for ($sjmp = 0; $sjmp < $sjxsm_count; $sjmp++) {
    $moban = preg_replace('/<随机小说名>/', trim(varray_rand($sjxsms)), $moban, 1);
}
for ($i = 1; $i <= 106; $i++) {
    $xsm = trim(varray_rand($sjxsms));
    $moban = str_replace("<小说名{$i}>", $xsm, $moban);
}

// ==================== 替换作者名 ====================
$sjxszz_count = substr_count($moban, '<随机作者>');
for ($sjmp = 0; $sjmp < $sjxszz_count; $sjmp++) {
    $moban = preg_replace('/<随机作者>/', trim(varray_rand($sjxszzs)), $moban, 1);
}
for ($i = 1; $i <= 106; $i++) {
    $zzm = trim(varray_rand($sjxszzs));
    $moban = str_replace("<作者名{$i}>", $zzm, $moban);
}

// ==================== 替换章节 ====================
$zj_count = substr_count($moban, '<随机章节>');
for ($zjp = 0; $zjp < $zj_count; $zjp++) {
    $moban = preg_replace('/<随机章节>/', trim(varray_rand($zjs)), $moban, 1);
}
for ($i = 1; $i <= 14; $i++) {
    $zj = trim(varray_rand($zjs));
    $moban = str_replace("<章节{$i}>", $zj, $moban);
}

// ==================== 替换句子 ====================
$wk = substr_count($moban, '<句子>');
// 优先使用句子块，降级到单句
if (!empty($block_lines)) {
    shuffle($block_lines);
}
for ($wi = 0; $wi < $wk; $wi++) {
    if (!empty($block_lines) && $wi < count($block_lines)) {
        $gdjuzi = trim($block_lines[$wi % count($block_lines)]);
    } else {
        $gdjuzi = trim(varray_rand($juzi));
    }
    if ($kuo_jia == "1") {
        $gdjuzi = cut_string($gdjuzi, 3, '】【');
    }
    if ($ascii_jia == "1") {
        $gdjuzi = cut_string($gdjuzi, mt_rand(5, 15), '<ascii>');
    }
    $moban = preg_replace('/<句子>/', $gdjuzi, $moban, 1);
    $moban = preg_replace('/<句子a>/', $gdjuzi, $moban, 1);
}

// ==================== 替换ASCII字符 ====================
$asciiz = substr_count($moban, '<ascii>');
for ($sp = 0; $sp < $asciiz; $sp++) {
    $moban = preg_replace('/<ascii>/', trim(varray_rand($ascii_sz)), $moban, 1);
}

// ==================== 从网站地址中提取域名中间的标识 ====================
if (preg_match('/www\.([^\.]+)\./', $wangzhi, $matches)) {
    $zhujue = $matches[1];
} else {
    $zhujue = 'woaini';
}

// ==================== 替换干扰码（基于域名固定） ====================
$ganraoma_count = substr_count($moban, '<干扰码>');
$seed = abs(crc32($wangzhi));
mt_srand($seed);
for ($i = 0; $i < $ganraoma_count; $i++) {
    $ganraoma = $zhujue . '-' . mt_rand(10000, 99999);
    $moban = preg_replace('/<干扰码>/', $ganraoma, $moban, 1);
}
mt_srand();

// ==================== 替换随机图片 ====================
$tupian5 = substr_count($moban, '<随机图片>');
for ($tui = 0; $tui < $tupian5; $tui++) {
    $moban = preg_replace('/<随机图片>/', '/uploads/images/' . varray_rand($image_list), $moban, 1);
}

// ==================== 替换随机小图 ====================
$xiaotu5 = substr_count($moban, '<随机小图>');
for ($tui = 0; $tui < $xiaotu5; $tui++) {
    $moban = preg_replace('/<随机小图>/', '/xiaoimages/' . varray_rand($image_list_small), $moban, 1);
}

// ==================== 替换时间相关标记 ====================
for ($i = 0; $i < 40; $i++) {
    $moban = preg_replace('/<随机时钟>/', date('Y-m-d H:i:s', time() - $i * 360), $moban, 1);
}
$moban = str_replace('<时钟>', date('G:i:s'), $moban);
$moban = str_replace('<年>', date('y'), $moban);
$moban = str_replace('<月>', date('m'), $moban);
$moban = str_replace('<日>', date('d'), $moban);
$moban = str_replace('<发布时间>', date('Y-m-d'), $moban);

$sj5 = substr_count($moban, '<随机时间>');
for ($i = 0; $i < $sj5; $i++) {
    $moban = preg_replace('/<随机时间>/', date('m-d', strtotime('-' . mt_rand(1, 2) . ' day')), $moban, 1);
}

// ==================== 替换随机字符和数字 ====================
$zf1 = substr_count($moban, '<随机字符>');
for ($ii = 0; $ii < $zf1; $ii++) {
    $moban = preg_replace('/<随机字符>/', randKey(mt_rand(5,8)), $moban, 1);
}
for ($i = 1; $i <= 9; $i++) {
    $ri5 = substr_count($moban, "<随机数字{$i}>");
    for ($j = 0; $j < $ri5; $j++) {
        $max = (int)str_repeat('9', $i);
        $moban = preg_replace("/<随机数字{$i}>/", mt_rand(1, $max), $moban, 1);
    }
}

// ==================== ICP备案号 + 公安备案号（同步显示/隐藏） ====================
include '/www/wwwroot/gx/zhuanma/icp_config.php';
if ($icp_enabled && ($host_hash % 100 < $icp_rate)) {
    $icpNumber = getFixedIcpByUrl($wangzhi);
    $publicSecurityNumber = getPublicSecurityIcpNumber($wangzhi);
    $moban = str_replace('<ICP备案号>', $icpNumber, $moban);
    $moban = str_replace('<公安网安备案号>', $publicSecurityNumber, $moban);
} else {
    $moban = str_replace('<ICP备案号>', '无', $moban);
    $moban = str_replace('<公安网安备案号>', '无', $moban);
}

// ==================== 替换当前域名和URL ====================
$yuming = $_SERVER['HTTP_HOST'] ?? '';
$url_dq = $_SERVER['REQUEST_URI'] ?? '';
$moban = str_replace('<当前域名>', $yuming, $moban);
$moban = str_replace('<当前url>', $url_dq, $moban);

// ==================== 输出 ====================
if ($cache == "2") {
    echo $moban;
    exit;
}

error_reporting(E_ERROR);
set_time_limit(0);
date_default_timezone_set('PRC');

echo $moban;
?>