<?php
      
require 'vendor/autoload.php';
use Jaybizzle\CrawlerDetect\CrawlerDetect;
use Detection\MobileDetect;
/**
 * 搜索引擎蜘蛛日志记录器（PHP 8.5 优化版）
 * 仅当检测到国内搜索引擎蜘蛛时才写日志
 */
function zhizhu(): void
{
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $time = date('Y-m-d H:i:s');

    // 判断协议
    $protocol = (
        ($_SERVER['HTTPS'] ?? 'off') === 'on'
        || ($_SERVER['SERVER_PORT'] ?? 80) == 443
    ) ? 'https://' : 'http://';

    $host = $_SERVER['HTTP_HOST'] ?? '';
    $path = $_SERVER['REQUEST_URI'] ?? '/';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

    $url = $protocol . $host . $path;

    // 支持识别的搜索引擎蜘蛛
    $engines = [
        'baidu'  => 'Baiduspider',
        'sogou'  => 'Sogou',
        '360'    => '360Spider',
        'shenma' => 'YisouSpider',
        'google' => 'Googlebot',
    ];

    $engine_name = null;
    $ua_lower = strtolower($user_agent);

    foreach ($engines as $name => $identifier) {
        if (str_contains($ua_lower, strtolower($identifier))) {
            $engine_name = $name;
            break;
        }
    }

    // 非蜘蛛直接退出
    if ($engine_name === null) {
        return;
    }

    // 静态资源不记录
    if (preg_match('/\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|map)(\?.*)?$/i', $path)) {
        return;
    }

    // ==========================
    // 按日期建立日志目录
    // ==========================
    $date = date('Y-m-d');
    $logDir = __DIR__ . '/spider/' . $date;

    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }

    // ==========================
    // 3MB 自动分卷
    // ==========================
    $maxSize = 3 * 1024 * 1024; // 3MB
    $index = 1;

    while (true) {
        $filename = "{$logDir}/{$engine_name}_{$index}.txt";

        if (!file_exists($filename)) {
            break;
        }

        clearstatcache(true, $filename);

        if (filesize($filename) < $maxSize) {
            break;
        }

        $index++;
    }

    // 日志内容
    $log_entry = "{$ip}\t{$time}\t{$url}\t{$user_agent}\n";

    // 写入日志（追加 + 文件锁）
    file_put_contents(
        $filename,
        $log_entry,
        FILE_APPEND | LOCK_EX
    );
}
// ====================== 执行 ======================
zhizhu();
 include('baidu/index.php');  // 修改为你的具体文件路径，例如 /sogou/special.php
        
         exit;  // 包含后退出，防止执行后续代码
