<?php
// ✅ 使用绝对路径（请根据你的实际路径修改！）
$dir = '/www/wwwroot/download.softblog.cn/常用的一些工具'; // ← 改成你的真实目录

// 安全限制：只允许下载该目录下的文件
function sanitizePath($baseDir, $filePath) {
    $realBase = realpath($baseDir);
    $realPath = realpath($filePath);
    if ($realPath === false || strpos($realPath, $realBase) !== 0) {
        return false;
    }
    return $realPath;
}

// 处理下载请求
if (isset($_GET['download'])) {
    $filename = basename($_GET['download']);
    $filepath = $dir . '/' . $filename;

    // 安全校验
    if (!file_exists($filepath) || !is_file($filepath)) {
        http_response_code(404);
        exit('File not found.');
    }

    if (sanitizePath($dir, $filepath) === false) {
        http_response_code(403);
        exit('Forbidden.');
    }

    // ✅ 关键修复：解决大文件下载失败
    set_time_limit(0); // 取消脚本执行时间限制
    if (ob_get_level()) {
        ob_end_clean(); // 清除并关闭输出缓冲
    }

    // 发送文件头
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    // 更兼容的中文文件名处理
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (preg_match('/MSIE|Trident/', $ua)) {
        $dispositionFilename = rawurlencode($filename);
    } else {
        $dispositionFilename = '"' . addcslashes($filename, '"\\') . '"';
    }
    header('Content-Disposition: attachment; filename=' . $dispositionFilename . '; filename*=UTF-8\'\'' . rawurlencode($filename));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filepath));
    header('Connection: close');

    // 流式输出文件
    readfile($filepath);
    exit;
}

// 列出文件
$files = [];
if (is_dir($dir)) {
    $iterator = new DirectoryIterator($dir);
    foreach ($iterator as $fileInfo) {
        if ($fileInfo->isFile()) {
            $files[] = [
                'name' => $fileInfo->getFilename(),
                'size' => $fileInfo->getSize(),
                'mtime' => $fileInfo->getMTime()
            ];
        }
    }
    usort($files, fn($a, $b) => strcasecmp($a['name'], $b['name']));
} else {
    die("Directory '$dir' does not exist. Please check the path in \$dir.");
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>文件下载列表</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
        h1 { color: #333; }
        table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background-color: #4CAF50; color: white; }
        tr:hover { background-color: #f9f9f9; }
        a { color: #1E88E5; text-decoration: none; }
        a:hover { text-decoration: underline; }
        .size { color: #666; font-size: 0.9em; }
        .time { color: #888; font-size: 0.9em; }
    </style>
</head>
<body>
    <h1>📁 文件列表</h1>
    <?php if (empty($files)): ?>
        <p>该目录下没有文件。</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>文件名</th>
                    <th>大小</th>
                    <th>修改时间</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($files as $file): 
                    $size = $file['size'];
                    $humanSize = $size >= 1073741824 ? round($size / 1073741824, 2) . ' GB'
                                : ($size >= 1048576 ? round($size / 1048576, 2) . ' MB'
                                : ($size >= 1024 ? round($size / 1024, 2) . ' KB'
                                : $size . ' B'));
                ?>
                <tr>
                    <td><a href="?download=<?= urlencode($file['name']) ?>"><?= htmlspecialchars($file['name']) ?></a></td>
                    <td class="size"><?= $humanSize ?></td>
                    <td class="time"><?= date('Y-m-d H:i:s', $file['mtime']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</body>
</html>