<?php
/**
 * 帝国CMS下载中转页 - 极简透传方案
 * 零正则、零解析、直接透传帝国返回的任何内容
 * 区分学兔兔资源（代理下载）和非学兔兔外链（直接跳转）
 */
error_reporting(0);
set_time_limit(0);
while (ob_get_level()) ob_end_clean();

// ==================== 基础配置 ====================

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host     = $_SERVER['HTTP_HOST'] ?? '';

// ==================== 参数解析 ====================

$classid  = $_GET['classid']  ?? '';
$id       = $_GET['id']       ?? '';
$pathid   = $_GET['pathid']   ?? '1';
$url      = $_GET['url']      ?? '';
$step     = $_GET['step']     ?? '';
$download = $_GET['download']  ?? '';

// ==================== 模式A：直接下载（?url=）====================

if (!empty($url) && empty($step) && empty($download)) {
    goto do_download;
}

// ==================== 模式B：帝国参数模式（classid + id）====================

if (!empty($classid) && !empty($id)) {

    $task_id = md5("$classid-$id-$pathid-" . ($_SERVER['HTTP_COOKIE'] ?? ''));
    $cache_file = sys_get_temp_dir() . '/d_task_' . $task_id . '.json';
    $cached = null;
    if (file_exists($cache_file)) {
        $cached = json_decode(file_get_contents($cache_file), true);
    }

    // --------------------------------------------------
    // B1：iframe 下载模式（供前端 <iframe> 静默调用）
    // --------------------------------------------------
    if ($download === '1') {
        if ($cached && $cached['status'] === 'ready' && !empty($cached['url']) && (time() - $cached['time']) < 300) {
            $url = $cached['url'];
            goto do_download;
        }
        header('Content-Type: text/html; charset=utf-8');
        echo '<p style="font-family:sans-serif;color:#999;text-align:center;padding:20px;">下载准备中，请稍候...</p>';
        exit;
    }

    // --------------------------------------------------
    // B2：AJAX 轮询
    // --------------------------------------------------
    if ($step === 'poll') {
        header('Content-Type: application/json');

        if (!$cached) {
            echo json_encode(['status' => 'processing']);
            exit;
        }

        if ($cached['status'] === 'ready' && !empty($cached['url'])) {
            echo json_encode([
                'status' => 'ready',
                'classid' => $classid,
                'id'      => $id,
                'pathid'  => $pathid
            ]);
        } elseif ($cached['status'] === 'external' && !empty($cached['url'])) {
            echo json_encode([
                'status' => 'external',
                'url'    => $cached['url']
            ]);
        } elseif ($cached['status'] === 'error') {
            echo json_encode([
                'status' => 'error',
                'msg'    => $cached['msg'] ?? '获取失败'
            ]);
        } else {
            echo json_encode(['status' => 'processing']);
        }
        exit;
    }

    // ==================================================
    // B3：同步请求帝国，透传返回内容
    // ==================================================

    // 3.1 优先读取有效缓存（5分钟）
    if ($cached && (time() - $cached['time']) < 300) {

        // 学兔兔资源已就绪 → 进入代理下载
        if ($cached['status'] === 'ready' && !empty($cached['url'])) {
            $url = $cached['url'];
            goto do_download;
        }

        // 非学兔兔外链 → 直接跳转
        if ($cached['status'] === 'external' && !empty($cached['url'])) {
            header("Location: " . $cached['url']);
            exit;
        }

        // 错误
        if ($cached['status'] === 'error') {
            show_error_page('下载失败', $cached['msg'] ?? '文件不存在或已下架');
            exit;
        }
    }

    // 3.2 无有效缓存：同步请求帝国下载系统
    $empire_url = "$protocol://$host/e/DownSys/GetDown?classid=$classid&id=$id&pathid=$pathid";

    $ch = curl_init($empire_url);
    curl_setopt_array($ch, [
        CURLOPT_FOLLOWLOCATION => true,     // 跟随帝国所有跳转
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => true,      // 获取响应头
        CURLOPT_NOBODY         => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_COOKIE         => $_SERVER['HTTP_COOKIE'] ?? '',
        CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0',
        CURLOPT_REFERER        => "$protocol://$host/down/$classid-$id.html",
    ]);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $final_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);  // 最终到达的URL
    curl_close($ch);

    // 分离响应头和响应体
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);

    // ========== 【极简透传】分析HTTP状态码和最终URL ==========

    // 未登录 / 权限不足 → 帝国会302到登录页或提示页
    // 我们透传帝国的最终返回：如果是HTML提示页就echo，如果是跳转就header
    if ($http_code == 301 || $http_code == 302) {
        // 帝国返回跳转头 → 直接透传跳转
        if (preg_match('/Location:\s*(.+?)\r?\n/i', $header, $m)) {
            header("Location: " . trim($m[1]));
            exit;
        }
    }

    // 如果最终URL是帝国内部页面（非下载地址），说明是提示页
    // 透传HTML内容
    if (stripos($final_url, '/e/') !== false || stripos($final_url, '/down/') !== false) {
        // 透传帝国的HTML提示页（未登录提示、权限不足提示等）
        // 修正相对路径
        $body = str_replace('href="/', 'href="' . $protocol . '://' . $host . '/', $body);
        $body = str_replace('src="/', 'src="' . $protocol . '://' . $host . '/', $body);
        echo $body;
        exit;
    }

    // ========== 拿到真实下载地址 ==========
    // 此时 $final_url 就是帝国最终跳转到的下载地址
    $real_url = $final_url;

    // ========== 【关键】分辨学兔兔 vs 非学兔兔 ==========
    $decoded = urldecode($real_url);

    // 非学兔兔域名（百度网盘等外链）→ 直接跳转，不做代理
    if (!preg_match('#^https?://[^/]*\.bzfxw\.com/#i', $decoded)) {
        file_put_contents($cache_file, json_encode([
            'status' => 'external',
            'url'    => $real_url,
            'time'   => time()
        ]));
        header("Location: " . $real_url);
        exit;
    }

    // ==========================================
    // 学兔兔资源：输出准备页面，后台验真
    // ==========================================

    file_put_contents($cache_file, json_encode([
        'status' => 'processing',
        'time'   => time()
    ]));

    output_prepare_html($task_id, $classid, $id, $pathid);

    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    }

    // 后台验证文件存在性
    $verify = verify_file_exists($real_url);

    if ($verify['status'] === 'ready') {
        file_put_contents($cache_file, json_encode([
            'status' => 'ready',
            'url'    => $real_url,
            'time'   => time()
        ]));
    } else {
        file_put_contents($cache_file, json_encode([
            'status' => 'error',
            'msg'    => $verify['msg'] ?? '文件不存在或已下架',
            'time'   => time()
        ]));
    }
    exit;
}

die('缺少下载参数');

// ==================== 下载执行逻辑 ====================
do_download:

if (empty($url)) die('缺少下载地址');

$decoded = urldecode($url);

// ========== 【关键】分辨学兔兔 vs 非学兔兔 ==========
// 非学兔兔域名：直接 302 跳转（百度网盘等外链）
if (!preg_match('#^https?://[^/]*\.bzfxw\.com/#i', $decoded)) {
    header("Location: $url");
    exit;
}

// 学兔兔代理下载
$filename = preg_replace('#[/\\\\:*?"<>|]#', '_', basename($decoded)) ?: 'download_' . time();

$parsed = parse_url($url);
if ($parsed === false) die('URL解析失败');

$scheme = $parsed['scheme'] ?? 'http';
$host   = $parsed['host']   ?? '';
$path   = $parsed['path']   ?? '';

// 对路径中的中文/特殊字符进行编码
$path_segments = explode('/', $path);
$encoded_segments = [];
foreach ($path_segments as $segment) {
    if ($segment === '') {
        $encoded_segments[] = $segment;
        continue;
    }
    $encoded_segments[] = rawurlencode(urldecode($segment));
}
$encoded_path = implode('/', $encoded_segments);
$final_url = "$scheme://$host$encoded_path";
if (!empty($parsed['query'])) $final_url .= '?' . $parsed['query'];

// 下载前验证（HEAD 请求）
$ch_check = curl_init($final_url);
curl_setopt_array($ch_check, [
    CURLOPT_NOBODY         => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_HTTPHEADER     => [
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Referer: https://www.bzfxw.com/',
    ],
]);
curl_exec($ch_check);
$check_code = curl_getinfo($ch_check, CURLINFO_HTTP_CODE);
$check_type = curl_getinfo($ch_check, CURLINFO_CONTENT_TYPE);
$check_size = curl_getinfo($ch_check, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch_check);

if ($check_code != 200 || ($check_type && stripos($check_type, 'text/html') !== false) || ($check_size !== -1 && $check_size < 1)) {
    show_error_page('下载失败', '文件不存在或已下架');
    exit;
}

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('X-Accel-Buffering: no');

if ($check_size > 0) {
    header('Content-Length: ' . (int)$check_size);
}

flush();

$ch = curl_init($final_url);
curl_setopt_array($ch, [
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_TIMEOUT        => 0,
    CURLOPT_CONNECTTIMEOUT => 30,
    CURLOPT_HTTPHEADER     => [
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Referer: https://www.bzfxw.com/',
    ],
    CURLOPT_WRITEFUNCTION  => function($c, $data) {
        echo $data;
        if (ob_get_level()) ob_flush();
        flush();
        return strlen($data);
    },
]);

curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($code != 200) {
    http_response_code(502);
    die("下载失败，HTTP $code");
}

// ==================== 辅助函数 ====================

function output_prepare_html($task_id, $classid, $id, $pathid) {
    echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>准备下载...</title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box;font-family:"Microsoft YaHei",sans-serif;}
        body{display:flex;justify-content:center;align-items:center;height:100vh;background:#f5f5f5;}
        .box{background:#fff;padding:40px 50px;border-radius:8px;box-shadow:0 2px 12px rgba(0,0,0,0.08);text-align:center;max-width:420px;width:90%;}
        .spinner{width:36px;height:36px;border:3px solid #f0f0f0;border-top-color:#3498db;border-radius:50%;animation:spin .8s linear infinite;margin:0 auto 18px;}
        @keyframes spin{to{transform:rotate(360deg);}}
        h2{font-size:18px;color:#333;margin-bottom:8px;font-weight:600;}
        p{font-size:14px;color:#888;line-height:1.6;}
        .success{color:#27ae60;display:none;}
        .error{color:#e74c3c;display:none;}
        .btn{display:inline-block;margin-top:15px;padding:6px 20px;background:#3498db;color:#fff;text-decoration:none;border-radius:4px;font-size:13px;}
        .btn:hover{background:#2980b9;}
        .hidden-frame{display:none;}
    </style>
</head>
<body>
    <div class="box" id="box">
        <div class="spinner" id="spinner"></div>
        <h2 id="title">正在准备下载...</h2>
        <p id="status">正在获取文件地址，请稍候</p>
        <p class="success" id="success">
            下载已开始，请查看浏览器下载列表<br>
            <small style="color:#999;">此窗口将在 <span id="countdown">3</span> 秒后自动关闭</small>
        </p>
        <p class="error" id="error"></p>
        <a href="javascript:window.close()" class="btn" id="closeBtn" style="display:none;">关闭窗口</a>
    </div>
    <iframe id="dlFrame" class="hidden-frame"></iframe>
    <script>
        var taskId = "' . $task_id . '";
        var classid = "' . $classid . '";
        var id = "' . $id . '";
        var pathid = "' . $pathid . '";
        var checkCount = 0;
        var maxCheck = 60;

        function startDownload() {
            var dlUrl = "/d.php?classid=" + classid + "&id=" + id + "&pathid=" + pathid + "&download=1";
            document.getElementById("dlFrame").src = dlUrl;
            document.getElementById("spinner").style.display = "none";
            document.getElementById("title").innerText = "下载已开始";
            document.getElementById("status").style.display = "none";
            document.getElementById("success").style.display = "block";
            var sec = 3;
            var timer = setInterval(function() {
                sec--;
                document.getElementById("countdown").innerText = sec;
                if (sec <= 0) {
                    clearInterval(timer);
                    if (window.opener) window.close();
                    else if (window.history.length > 1) window.history.back();
                    else document.getElementById("closeBtn").style.display = "inline-block";
                }
            }, 1000);
        }

        function openExternal(url) {
            document.getElementById("spinner").style.display = "none";
            document.getElementById("title").innerText = "正在跳转";
            document.getElementById("status").innerText = "即将打开外部页面...";
            window.location.href = url;
        }

        function showError(msg) {
            document.getElementById("spinner").style.display = "none";
            document.getElementById("title").innerText = "获取失败";
            document.getElementById("status").style.display = "none";
            document.getElementById("error").innerText = msg;
            document.getElementById("error").style.display = "block";
            document.getElementById("closeBtn").style.display = "inline-block";
        }

        function checkStatus() {
            checkCount++;
            if (checkCount > maxCheck) {
                showError("获取文件地址超时，请刷新重试");
                return;
            }
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "/d.php?classid=" + classid + "&id=" + id + "&pathid=" + pathid + "&step=poll&task=" + taskId, true);
            xhr.timeout = 5000;
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        var resp = JSON.parse(xhr.responseText);

                        if (resp.status === "external" && resp.url) {
                            openExternal(resp.url);
                            return;
                        }

                        if (resp.status === "ready") {
                            startDownload();
                            return;
                        }

                        if (resp.status === "error") {
                            showError(resp.msg || "文件不存在或已下架");
                            return;
                        }
                    } catch(e) {}
                }
                setTimeout(checkStatus, 500);
            };
            xhr.ontimeout = xhr.onerror = function() {
                setTimeout(checkStatus, 500);
            };
            xhr.send();
        }

        checkStatus();
    </script>
</body>
</html>';
}

function show_error_page($title, $msg) {
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>' . htmlspecialchars($title) . '</title>
    <style>
        body{font-family:"Microsoft YaHei",sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#f5f5f5;}
        .box{background:#fff;padding:40px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1);text-align:center;max-width:400px;}
        h2{color:#e74c3c;font-size:20px;margin-bottom:12px;}
        p{color:#666;font-size:14px;line-height:1.8;}
    </style>
</head>
<body>
    <div class="box">
        <h2>' . htmlspecialchars($title) . '</h2>
        <p>' . $msg . '</p>
    </div>
</body>
</html>';
}

function verify_file_exists($url) {
    $parsed = parse_url($url);
    if ($parsed === false) {
        return ['status' => 'error', 'msg' => 'URL解析失败'];
    }

    $scheme = $parsed['scheme'] ?? 'http';
    $host   = $parsed['host']   ?? '';
    $path   = $parsed['path']   ?? '';

    $path_segments = explode('/', $path);
    $encoded_segments = [];
    foreach ($path_segments as $segment) {
        if ($segment === '') {
            $encoded_segments[] = $segment;
            continue;
        }
        $encoded_segments[] = rawurlencode(urldecode($segment));
    }
    $encoded_path = implode('/', $encoded_segments);
    $final_url = "$scheme://$host$encoded_path";
    if (!empty($parsed['query'])) $final_url .= '?' . $parsed['query'];

    $ch = curl_init($final_url);
    curl_setopt_array($ch, [
        CURLOPT_NOBODY         => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer: https://www.bzfxw.com/',
        ],
    ]);
    curl_exec($ch);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $file_size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    curl_close($ch);

    if ($http_code != 200) {
        return ['status' => 'error', 'msg' => '文件不存在或已下架（服务器返回 HTTP ' . $http_code . '）'];
    }

    if ($content_type && stripos($content_type, 'text/html') !== false) {
        return ['status' => 'error', 'msg' => '文件不存在或链接已失效'];
    }

    if ($file_size !== -1 && $file_size < 1) {
        return ['status' => 'error', 'msg' => '文件内容为空或已损坏'];
    }

    return ['status' => 'ready', 'url' => $url];
}