<?php

/**
 * @id 42
 * @name HTTP状态码查询
 * @version 1.0.0
 * @description 输入网址即可查询HTTP状态码，支持常见状态码的详细检测和解释说明
 * @price 0
 * @type 工具
 * @width 460
 * @height 480
 * @thumbnail /img/id42.png
 */

$plugin_config = <<<EOT
[config_params]
[/config_params]

[Plugin Instructions]
HTTP状态码查询工具，输入网址即可检测网站的HTTP状态码。
支持常见状态码：200(成功)、301(永久重定向)、302(临时重定向)、404(页面不存在)、500(服务器错误)等。
查询结果会显示状态码、状态描述以及详细解释。
[/Plugin Instructions]
EOT;

$config = array();
if (preg_match('/\[config_params\](.*?)\[\/config_params\]/s', $plugin_config, $matches)) {
    $lines = explode("\n", $matches[1]);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || strpos($line, '=') === false) continue;
        list($key, $value) = explode('=', $line, 2);
        $key = trim($key);
        $value = trim($value);
        if ($key !== '') {
            $config[$key] = $value;
        }
    }
}

function get_http_status_code($url)
{
    $url = trim($url);
    if (empty($url)) return false;

    // 不再自动添加协议头，由用户输入

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => false, // 不跟随重定向，获取原始状态码
        CURLOPT_MAXREDIRS => 0,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        CURLOPT_PROXY => '', // 清空代理设置
        CURLOPT_PROXYTYPE => CURLPROXY_HTTP
    ]);

    $response = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    return $status_code > 0 ? $status_code : false;
}

function get_status_code_description($code)
{
    $status_codes = [
        100 => 'Continue',
        101 => 'Switching Protocols',
        102 => 'Processing',
        103 => 'Early Hints',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        207 => 'Multi-Status',
        208 => 'Already Reported',
        226 => 'IM Used',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        307 => 'Temporary Redirect',
        308 => 'Permanent Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Payload Too Large',
        414 => 'URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Range Not Satisfiable',
        417 => 'Expectation Failed',
        418 => 'Im a teapot',
        421 => 'Misdirected Request',
        422 => 'Unprocessable Entity',
        423 => 'Locked',
        424 => 'Failed Dependency',
        425 => 'Too Early',
        426 => 'Upgrade Required',
        428 => 'Precondition Required',
        429 => 'Too Many Requests',
        431 => 'Request Header Fields Too Large',
        451 => 'Unavailable For Legal Reasons',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        506 => 'Variant Also Negotiates',
        507 => 'Insufficient Storage',
        508 => 'Loop Detected',
        510 => 'Not Extended',
        511 => 'Network Authentication Required'
    ];

    return isset($status_codes[$code]) ? $status_codes[$code] : 'Unknown Status Code';
}

function get_status_code_explanation($code)
{
    $explanations = [
        200 => '请求成功，服务器已成功处理了请求。',
        301 => '请求的资源已被永久移动到新位置。',
        302 => '请求的资源临时被移动到新位置。',
        404 => '请求的资源不存在。',
        500 => '服务器内部错误，无法完成请求。',
        403 => '服务器拒绝请求，没有访问权限。',
        401 => '请求需要身份验证。',
        400 => '请求参数错误或格式不正确。',
        503 => '服务器暂时不可用，通常是因为过载或维护。',
        504 => '网关超时，服务器没有及时收到上游服务器的响应。'
    ];

    return isset($explanations[$code]) ? $explanations[$code] : '暂无详细解释。';
}

function qk_http_status($cfg)
{
    return '';
}

$plugin_instructions = '';
if (preg_match('/\[Plugin Instructions\](.*?)\[\/Plugin Instructions\]/s', $plugin_config, $matches)) {
    $plugin_instructions = trim($matches[1]);
}

if (isset($_POST['plugin']) || isset($_GET['plugin'])) {
?>
    <!DOCTYPE html>
    <html>

    <head>
        <meta charset="UTF-8">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                background: #fff;
                padding: 20px;
            }

            .form-group {
                margin-bottom: 16px;
            }

            .form-label {
                display: block;
                font-size: 13px;
                color: #333;
                margin-bottom: 6px;
                font-weight: 500;
            }

            input[type="text"] {
                width: 100%;
                height: 38px;
                padding: 0 12px;
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                font-size: 14px;
                transition: border-color .2s;
            }

            input[type="text"]:focus {
                outline: none;
                border-color: #2196F3;
            }

            .btn-check {
                width: 100%;
                height: 40px;
                background: #2196F3;
                color: #fff;
                border: none;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: background .2s;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .btn-check:hover {
                background: #1976d2;
            }

            .result-container {
                margin-top: 20px;
                padding: 16px;
                border-radius: 6px;

                display: none;
            }

            .result-title {
                font-size: 14px;
                font-weight: 500;
                color: #333;
                margin-bottom: 12px;
            }

            .result-item {
                margin-bottom: 8px;
                font-size: 13px;
            }

            .result-label {
                color: #666;
                display: inline-block;
                width: 80px;
            }

            .result-value {
                color: #333;
                font-weight: 500;
            }

            .status-code {
                display: inline-block;
                padding: 2px 8px;
                border-radius: 10px;
                font-size: 12px;
                font-weight: 500;
                margin-left: 8px;
            }

            .status-2xx {
                background: #e8f5e8;
                color: #2e7d32;
            }

            .status-3xx {
                background: #e3f2fd;
                color: #1565c0;
            }

            .status-4xx {
                background: #fff3e0;
                color: #ef6c00;
            }

            .status-5xx {
                background: #ffebee;
                color: #c62828;
            }

            .status-error {
                background: #ffebee;
                color: #c62828;
            }



            .hint {
                font-size: 11px;
                color: #999;
                margin-top: 4px;
            }

            .loading-container {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 40px 0;
            }

            .loading {
                display: inline-block;
                width: 40px;
                height: 40px;
                border: 4px solid #f3f3f3;
                border-top: 4px solid #4CAF50;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-bottom: 15px;
            }

            .loading-text {
                font-size: 14px;
                color: #666;
            }

            @keyframes spin {
                0% {
                    transform: rotate(0deg);
                }

                100% {
                    transform: rotate(360deg);
                }
            }

            .btn-check {
                width: 100%;
                height: 40px;
                background: #4CAF50;
                color: #fff;
                border: none;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: background .2s;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .btn-check:hover {
                background: #45a049;
            }

            .btn-check.loading {
                background: #81c784;
                cursor: not-allowed;
            }

            .result-container {
                margin-top: 20px;
                padding: 16px;
                border-radius: 6px;
                background: #f1f8e9;
                display: block;
                border: 1px solid #c8e6c9;
            }

            .explanation {
                margin-top: 16px;
                padding: 16px;
                background: #ffffff;
                border-radius: 4px;
                border-left: 3px solid #9e9e9e;
                font-size: 13px;
                color: #333;
                line-height: 1.6;
            }

            .explanation ul {
                margin: 12px 0;
                padding-left: 20px;
            }

            .explanation li {
                margin-bottom: 8px;
                list-style-type: none;
                position: relative;
                padding-left: 20px;
            }

            .explanation li::before {
                content: '';
                position: absolute;
                left: 0;
                top: 6px;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background: #4CAF50;
            }

            .explanation p {
                margin: 12px 0;
            }

            .explanation code {
                background: #f1f1f1;
                padding: 2px 4px;
                border-radius: 3px;
                font-family: monospace;
                font-size: 12px;
            }

            /* 自定义滚动条 */
            .result-container {
                max-height: 300px;
                overflow-y: auto;
            }

            .result-container::-webkit-scrollbar {
                width: 6px;
            }

            .result-container::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 3px;
            }

            .result-container::-webkit-scrollbar-thumb {
                background: #4CAF50;
                border-radius: 3px;
            }

            .result-container::-webkit-scrollbar-thumb:hover {
                background: #45a049;
            }
        </style>
    </head>

    <body>
        <form id="checkForm">
            <div class="form-group">
                <label class="form-label">网址</label>
                <input type="text" name="url" id="urlInput" placeholder="请输入网址，例如：www.example.com">
                <div class="hint">支持HTTP和HTTPS协议，自动补全协议头</div>
            </div>
            <button type="button" class="btn-check" id="checkBtn">查询状态码</button>
        </form>

        <div class="result-container" id="resultContainer">
            <div class="result-title">使用说明</div>
            <div class="explanation">
                <p><strong>支持的状态码：</strong></p>
                <ul>
                    <li>200 - OK（请求成功）</li>
                    <li>301 - Moved Permanently（永久重定向）</li>
                    <li>302 - Found（临时重定向）</li>
                    <li>400 - Bad Request（请求参数错误）</li>
                    <li>401 - Unauthorized（需要身份验证）</li>
                    <li>403 - Forbidden（禁止访问）</li>
                    <li>404 - Not Found（资源不存在）</li>
                    <li>500 - Internal Server Error（服务器内部错误）</li>
                    <li>503 - Service Unavailable（服务不可用）</li>
                    <li>504 - Gateway Timeout（网关超时）</li>
                    <li>其他状态码（会显示为Unknown Status Code）</li>
                </ul>
                <p><strong>域名输入规范：</strong></p>
                <ul>
                    <li>直接输入域名：如 <code>example.com</code></li>
                    <li>带协议头输入：如 <code>http://example.com</code> 或 <code>https://example.com</code></li>
                    <li>支持带路径输入：如 <code>example.com/path</code></li>
                </ul>
                <p><strong>使用方法：</strong></p>
                <ul>
                    <li>在上方输入框中输入网址</li>
                    <li>点击「查询状态码」按钮</li>
                    <li>等待查询完成，查看结果</li>
                </ul>
            </div>
        </div>

        <script>
            window.callParentToast = function(msg, opts) {
                window.parent.postMessage({
                    type: 'toast',
                    func: 'showToast',
                    message: msg,
                    options: opts || {}
                }, window.parent.location.origin);
            };

            var qkDefaultTitle = document.title ? String(document.title) : '';
            if (!qkDefaultTitle) {
                qkDefaultTitle = 'HTTP状态码查询';
                document.title = qkDefaultTitle;
            }

            var qkTitleTimer = null;

            function setTempTitle(t) {
                if (qkTitleTimer) clearTimeout(qkTitleTimer);
                document.title = String(t || qkDefaultTitle || '');
                qkTitleTimer = setTimeout(function() {
                    document.title = qkDefaultTitle;
                }, 1000);
            }

            function performCheck(url, fallbackUrl = null) {
                // 显示加载动画在结果区域
                var resultContainer = document.getElementById('resultContainer');
                resultContainer.innerHTML = '<div class="loading-container"><div class="loading"></div><div class="loading-text">查询中...</div></div>';
                resultContainer.style.display = 'block';

                var checkBtn = document.getElementById('checkBtn');
                checkBtn.disabled = true;

                fetch('/admin/Plugin.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'action=check_http_code&url=' + encodeURIComponent(url)
                    })
                    .then(function(r) {
                        return r.json();
                    })
                    .then(function(data) {
                        checkBtn.disabled = false;

                        var resultContainer = document.getElementById('resultContainer');

                        if (data.success) {
                            resultContainer.innerHTML = `
                                <div class="result-title">查询结果</div>
                                <div class="result-item">
                                    <span class="result-label">网址：</span>
                                    <span class="result-value">${url}</span>
                                </div>
                                <div class="result-item">
                                    <span class="result-label">状态码：</span>
                                    <span class="result-value">${data.status_code}</span>
                                </div>
                                <div class="result-item">
                                    <span class="result-label">状态描述：</span>
                                    <span class="result-value"></span>
                                </div>
                                <div class="explanation"></div>
                            `;

                            var resultDescription = resultContainer.querySelector('.result-value:nth-child(2)');
                            var resultExplanation = resultContainer.querySelector('.explanation');

                            var statusClass = 'status-2xx';
                            if (data.status_code >= 300 && data.status_code < 400) {
                                statusClass = 'status-3xx';
                            } else if (data.status_code >= 400 && data.status_code < 500) {
                                statusClass = 'status-4xx';
                            } else if (data.status_code >= 500) {
                                statusClass = 'status-5xx';
                            }

                            var statusText = '';
                            var explanation = '';
                            switch (data.status_code) {
                                case 200:
                                    statusText = 'OK';
                                    explanation = '请求成功，服务器已成功处理了请求。';
                                    break;
                                case 301:
                                    statusText = 'Moved Permanently';
                                    explanation = '请求的资源已被永久移动到新位置。';
                                    break;
                                case 302:
                                    statusText = 'Found';
                                    explanation = '请求的资源临时被移动到新位置。';
                                    break;
                                case 404:
                                    statusText = 'Not Found';
                                    explanation = '请求的资源不存在。';
                                    break;
                                case 500:
                                    statusText = 'Internal Server Error';
                                    explanation = '服务器内部错误，无法完成请求。';
                                    break;
                                case 403:
                                    statusText = 'Forbidden';
                                    explanation = '服务器拒绝请求，没有访问权限。';
                                    break;
                                case 401:
                                    statusText = 'Unauthorized';
                                    explanation = '请求需要身份验证。';
                                    break;
                                case 400:
                                    statusText = 'Bad Request';
                                    explanation = '请求参数错误或格式不正确。';
                                    break;
                                case 503:
                                    statusText = 'Service Unavailable';
                                    explanation = '服务器暂时不可用，通常是因为过载或维护。';
                                    break;
                                case 504:
                                    statusText = 'Gateway Timeout';
                                    explanation = '网关超时，服务器没有及时收到上游服务器的响应。';
                                    break;
                                default:
                                    statusText = 'Unknown Status Code';
                                    explanation = '暂无详细解释。';
                            }

                            resultDescription.innerHTML = statusText + '<span class="status-code ' + statusClass + '">' + data.status_code + '</span>';
                            resultExplanation.textContent = explanation;
                        } else {
                            // 如果有备用URL，尝试备用URL
                            if (fallbackUrl) {
                                performCheck(fallbackUrl);
                            } else {
                                // 处理域名不存在的情况
                                resultContainer.innerHTML = `
                                    <div class="result-title">查询结果</div>
                                    <div class="result-item">
                                        <span class="result-label">网址：</span>
                                        <span class="result-value">${url}</span>
                                    </div>
                                    <div class="result-item">
                                        <span class="result-label">状态码：</span>
                                        <span class="result-value">Error</span>
                                    </div>
                                    <div class="result-item">
                                        <span class="result-label">状态描述：</span>
                                        <span class="result-value">Domain Not Found<span class="status-code status-error">Error</span></span>
                                    </div>
                                    <div class="explanation">${data.message || '域名不存在或无法访问'}</div>
                                `;
                            }
                        }
                    })
                    .catch(function() {
                        checkBtn.disabled = false;

                        // 如果有备用URL，尝试备用URL
                        if (fallbackUrl) {
                            performCheck(fallbackUrl);
                        } else {
                            // 处理网络错误
                            var resultContainer = document.getElementById('resultContainer');
                            resultContainer.innerHTML = `
                                <div class="result-title">查询结果</div>
                                <div class="result-item">
                                    <span class="result-label">网址：</span>
                                    <span class="result-value">${url}</span>
                                </div>
                                <div class="result-item">
                                    <span class="result-label">状态码：</span>
                                    <span class="result-value">Error</span>
                                </div>
                                <div class="result-item">
                                    <span class="result-label">状态描述：</span>
                                    <span class="result-value">Network Error<span class="status-code status-error">Error</span></span>
                                </div>
                                <div class="explanation">网络错误，请检查网络连接后重试</div>
                            `;
                        }
                    });
            }

            document.getElementById('checkBtn').addEventListener('click', function() {
                var url = document.getElementById('urlInput').value.trim();
                if (!url) {
                    callParentToast('请输入网址', {
                        type: 'warning'
                    });
                    return;
                }

                // 自动处理协议头
                if (!preg_match(/^https?:\/\//i, url)) {
                    // 先尝试HTTP
                    var httpUrl = 'http://' + url;
                    // 再尝试HTTPS
                    var httpsUrl = 'https://' + url;
                    // 先查询HTTP
                    performCheck(httpUrl, httpsUrl);
                    return;
                }

                // 已有协议头，直接查询
                performCheck(url);
            });

            // 正则表达式函数
            function preg_match(pattern, string) {
                var regex = new RegExp(pattern);
                return regex.test(string);
            }
        </script>
    </body>

    </html>
<?php
}

if (!isset($_POST['plugin'])) {
    echo qk_http_status($config);
}
?>