<?php
// ========================
// 配置
// ========================
$PASSWORD_HASH = "$2y$10$8L94iiL0Vl9vNEh0Jcoaq.MXPn0FyR7HKJFfiDGEobHQw4Sdd7QA2"; // 登录密码
session_start();

// ========================
// 登录
// ========================


// ========================
// 注销
// ========================
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// ========================
// 当前路径
// ========================
$defaultDir = __DIR__; // 默认当前目录
$path = isset($_GET['path']) ? realpath($_GET['path']) : realpath($defaultDir);

// 确保路径存在
if ($path === false || !is_dir($path)) {
    die("无效路径！");
}

// ========================
// 编辑文件
// ========================
if (isset($_GET['edit'])) {
    $fileToEdit = realpath($path . '/' . $_GET['edit']);
    if ($fileToEdit && is_file($fileToEdit)) {
        if (isset($_POST['save'])) {
            file_put_contents($fileToEdit, $_POST['content']);
            $msg = "文件已保存！";
        }
        $content = file_get_contents($fileToEdit);
        ?>
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head><meta charset="UTF-8"><title>编辑文件</title></head>
        <body>
            <h2>编辑文件：<?php echo htmlspecialchars(basename($fileToEdit)); ?></h2>
            <?php if(!empty($msg)) echo "<p style='color:green;'>$msg</p>"; ?>
            <form method="post">
                <textarea name="content" rows="25" cols="100"><?php echo htmlspecialchars($content); ?></textarea><br>
                <button type="submit" name="save" value="1">保存</button>
            </form>
            <p><a href="?path=<?php echo urlencode($path); ?>">返回</a></p>
        </body>
        </html>
        <?php
        exit;
    } else {
        die("无法编辑此文件！");
    }
}

// ========================
// 上传文件 (覆盖同名文件)
// ========================
if (isset($_FILES['file'])) {
    if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $uploadName = basename($_FILES['file']['name']);
        $target = rtrim($path, '/') . '/' . $uploadName;

        if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
            $msg = "上传成功！（已保存为 " . htmlspecialchars($uploadName) . "）";
        } else {
            $msg = "无法移动上传文件，请检查目标目录的写入权限";
        }
    } else {
        $msg = "上传失败，错误代码：" . $_FILES['file']['error'];
    }
}


// ========================
// 删除文件
// ========================
if (isset($_GET['delete'])) {
    $target = realpath($path . '/' . $_GET['delete']);
    if ($target && is_file($target)) {
        unlink($target);
        $msg = "文件已删除！";
    }
}

// ========================
// 列出文件
// ========================
$files = scandir($path);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>文件管理器</title>
</head>
<body>
    <h2>文件管理器</h2>
    <?php if(!empty($msg)) echo "<p style='color:green;'>$msg</p>"; ?>
    <p><a href="?logout=1">退出登录</a></p>

    <!-- 面包屑导航 -->
    <p>
        当前位置：
        <?php
        $parts = explode('/', trim($path, '/'));
        $breadcrumb = '';
        echo '<a href="?path=/">/</a>';
        foreach ($parts as $part) {
            $breadcrumb .= '/' . $part;
            echo '/<a href="?path='.urlencode($breadcrumb).'">'.htmlspecialchars($part).'</a>';
        }
        ?>
    </p>

    <!-- 上传 -->
    <form method="post" enctype="multipart/form-data">
        上传文件：<input type="file" name="file">
        <button type="submit">上传（覆盖）</button>
    </form>

    <table border="1" cellpadding="5" cellspacing="0">
        <tr><th>名称</th><th>操作</th></tr>
        <?php
        // 返回上一级
        if ($path !== "/") {
            $parent = dirname($path);
            echo "<tr><td><a href='?path=".urlencode($parent)."'>⬆ 返回上一级</a></td><td></td></tr>";
        }

        foreach ($files as $f) {
            if ($f === '.' || $f === '..') continue;
            $full = $path . '/' . $f;

            if (is_dir($full)) {
                echo "<tr>
                        <td>📁 <a href='?path=".urlencode($full)."'>".$f."</a></td>
                        <td>—</td>
                      </tr>";
            } else {
                echo "<tr>
                        <td>📄 ".$f."</td>
                        <td>
                            <a href='?path=".urlencode($path)."&edit=".urlencode($f)."'>编辑</a> |
                            <a href='?path=".urlencode($path)."&delete=".urlencode($f)."' onclick='return confirm(\"确定删除此文件？\")'>删除</a>
                        </td>
                      </tr>";
            }
        }
        ?>
    </table>
</body>
</html>