<?php
//error_reporting(E_ALL);
// 设置在页面上显示错误（生产环境千万不要打开）
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);


ini_set('display_errors', 'Off');//禁止输出错误
ob_start();

// ★ 剥掉 ?spm 之类的tracking参数，统一URL
if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
    $_SERVER['REQUEST_URI'] = strtok($_SERVER['REQUEST_URI'], '?');
}

// 开始时间和内存使用
$start_time = microtime(true);
$start_memory = memory_get_usage();


include 'core/main.php';
include 'core/function.php';
//屏蔽gfw
include 'tz/gfw.php';

if (strpos($user_agent, 'Baiduspider-render/2.0') === false) {
    include 'clczz/spider.php';
}

// sendSpiderLog();
//取主域名
$url =$_SERVER['HTTP_HOST'];
preg_match('/[\w][\w-]*\.(?:com\.cn|net\.cn|org\.cn|sh\.cn|gs\.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|today|company|gold|run|life|fit|space|archi|black|Lotto|pink|ski|icu|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|cx|shop|xyz|me|fun|store|ltd|pro|xin|vip|site|online|club|work|top|icu|cn|edu|net|org|gov|cc|biz|tech|cfd|info|sale)(\/|$)/isU', $url, $match);
$zym = $match[0];
$host = $_SERVER['HTTP_HOST'];

// ★ 按根域名选模板：先取 data/templates/类型/根域名/*.html，没有就用 data/templates/类型/*.html 兜底
if (!function_exists('tpl_pick')) {
    function tpl_pick($zym, $sub) {
        $zym = strtolower(trim($zym, "/ \t"));
        if ($zym !== '' && strpos($zym, '..') === false) {
            $files = glob("data/templates/$sub/$zym/*.html");
            if ($files) return $files[array_rand($files)];
        }
        $files = glob("data/templates/$sub/*.html");
        return $files ? $files[array_rand($files)] : '';
    }
}
//判断缓存文件存在
$dir = "cache/$zym/";
$danzhandir = "zhanqun/$zym/$host/"; // 设置域名目录路径
$dzconfigFile = $danzhandir . "spider_num.txt"; // 配置文件路径

$cachefile = $dir . sha1($_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"]) . '.cache';
if (file_exists($cachefile)) {
    $moban = file_get_contents($cachefile);
    if ($缓存压缩 || substr($moban, 0, 2) === "\x1f\x8b") {
        $moban = gzdecode($moban);//gzip解压
    }
    include 'core/dongtai.php';
    $head_url = './data/templates/head.html';
    $head_html = file_get_contents($head_url);
    echo $head_html.$moban;
    exit;
}
// 检查并创建目录
if (!is_dir($danzhandir)) {
    mkdir($danzhandir, 0777, true); // 递归创建目录，并设置权限
}

// 检查配置文件是否存在
$spider_num = 0;
// 如果文件不存在，创建并初始化为 0
if (!file_exists($dzconfigFile)) {
    file_put_contents($dzconfigFile, "0");
    $spider_num = 0;
} else {
    // 获取 User-Agent
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

    // 判断是否不是 "Baiduspider-render/2.0"
    if (strpos($user_agent, 'Baiduspider-render/2.0') === false) {
        $fp = fopen($dzconfigFile, "c+");
        if ($fp) {
            if (flock($fp, LOCK_EX)) {
                // 避免 filesize 为 0 时 fread 失败
                clearstatcache(true, $dzconfigFile);
                $size = filesize($dzconfigFile);
                if ($size > 0) {
                    $spider_num = (int)fread($fp, $size);
                }
                $spider_num++; // 自增

                ftruncate($fp, 0);
                rewind($fp);
                fwrite($fp, (string)$spider_num);
                fflush($fp);
                flock($fp, LOCK_UN);
            }
            fclose($fp);
        } else {
            // 如果文件打开失败，保证 $spider_num 不变
            $spider_num = 0;
        }
    } else {
        // Baiduspider-render/2.0 不计数
        clearstatcache(true, $dzconfigFile);
        $spider_num = (int)file_get_contents($dzconfigFile);
    }
}

// 没有缓存，生成页面
$randomFile = tpl_pick($zym, 'index');
$moban = file_get_contents($randomFile);

include 'core/config.php';

//处理动态标签
include 'core/dongtai.php';

$head_url = './data/templates/head.html';
$head_html = file_get_contents($head_url);

echo $head_html.$moban;


// 结束时间和内存使用
$execution_time = (microtime(true) - $start_time) * 1000; // 毫秒
$peak_memory = (memory_get_peak_usage() - $start_memory) / (1024 * 1024); // MB

$current_url = "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

$time_log = sprintf(
    "<!-- 脚本执行时间：%.2f ms 内存使用：%.2f MB --> %s\n",
    $execution_time,
    $peak_memory,
    $current_url
);
$log_file = fopen("time_log.txt", "a");
fwrite($log_file, $time_log);
fclose($log_file);
ob_end_flush();
exit;
?>