<?php
// 功能：网站路由文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。


// 优先处理文章发布和编辑请求，避免URL重写导致的问题
if (isset($_POST['publish_article']) || isset($_POST['edit_article'])) {
    // 直接包含 ajaxx.php 文件处理文章发布和编辑
    if (file_exists(__DIR__ . '/admin/ajaxx.php')) {
        include_once __DIR__ . '/admin/ajaxx.php';
        exit;
    }
}

if (isset($_GET['plugin_id']) && $_GET['plugin_id'] === '37') {
    $plugin_file = __DIR__ . '/admin/Plugin/37_comment.php';
    if (file_exists($plugin_file)) {
        include_once $plugin_file;
        exit;
    }
}

// 优先使用IIS的HTTP_X_ORIGINAL_URL，其次使用PATH_INFO，最后使用REQUEST_URI
function getRequestUri()
{
    if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
        return $_SERVER['HTTP_X_ORIGINAL_URL'];
    } elseif (isset($_SERVER['PATH_INFO'])) {
        return $_SERVER['PATH_INFO'];
    } else {
        return isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    }
}

$__qk_uri = getRequestUri();
if ($__qk_uri === '/comment.php' || $__qk_uri === '/comment_min.php') {
    header('Content-Type: text/html; charset=utf-8');
    $GLOBALS['comment_post_id'] = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($GLOBALS['comment_post_id'] <= 0) $GLOBALS['comment_post_id'] = 1;
    $GLOBALS['comment_content_type'] = isset($_GET['type']) ? preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['type']) : 'post';
    if ($__qk_uri === '/comment.php') {
        include __DIR__ . '/templates/comment.php';
    } else {
        include __DIR__ . '/templates/comment_min.php';
    }
    exit;
}

if (preg_match('/\.qkcms$/i', $__qk_uri)) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied');
}

if (preg_match('/^\/admin\/Plugin\//i', $__qk_uri)) {
    if ($__qk_uri === '/admin/Plugin/36_cart.php' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && in_array($_POST['action'], ['get_cart_items', 'sync_cart', 'check_cart_status'], true)) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        include_once __DIR__ . '/admin/Plugin/36_cart.php';
        exit;
    }
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied');
}

// 检查是否需要重定向index.php到根目录
if ($__qk_uri === '/index.php') {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: /');
    exit();
}

session_start();

require_once 'common.php';

$qk_guest_page_cache_enabled = false;
$qk_shared_page_cache_enabled = false;
$qk_page_cache_scope = '';

// 清除现有的输出缓冲
while (ob_get_length() > 0) {
    ob_end_clean();
}
// 对所有页面应用removeApStyleFromBody函数，包括前端、后台和维护页面
ob_start('removeApStyleFromBody');

// 授权验证（放在 ob_start 之后，确保输出不会被清除）
require_once 'license.php';
qk_license_verify();

function checkPhpEnvironment()
{
    $errors = array();

    if (version_compare(PHP_VERSION, '7.0.0', '<')) {
        array_push($errors, "PHP版本过低，需要PHP 7.0或更高版本");
    }

    $required_extensions = array('mysqli', 'session', 'json');
    foreach ($required_extensions as $ext) {
        if (!extension_loaded($ext)) {
            array_push($errors, "缺少必要的PHP扩展: $ext");
        }
    }

    $required_dirs = array('templates', 'uploads');
    foreach ($required_dirs as $dir) {
        $full_path = __DIR__ . '/' . $dir;
        if (!is_dir($full_path) && !mkdir($full_path, 0755, true)) {
            array_push($errors, "无法创建或访问必要目录: $dir");
        }
    }

    return $errors;
}

// 统一的错误页面样式处理
function getErrorPageHeader($title)
{
    return <<<HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>$title</title>
    <link rel="stylesheet" href="/assets/css/ts_common.css">
</head>
HTML;
}

function showErrorPage($title, $heading, $message, $options = [])
{
    $default_options = [
        'icon' => '⚠️',
        'show_retry' => false,
        'additional_html' => ''
    ];
    $options = array_merge($default_options, $options);
    $retry_button = $options['show_retry'] ? '<button class="retry-btn" onclick="window.location.reload()">重新检查</button>' : '';
    $error_icon = $options['icon'];
    $additional_html = $options['additional_html'];

    echo getErrorPageHeader($title);
    echo <<<HTML

<body>
    <div class="error-container">
        <div class="error-icon">$error_icon</div>
        <h1>$heading</h1>
        <p>$message</p>
        $additional_html
        $retry_button
    </div>
</body>
</html>
HTML;
    exit;
}

$env_errors = checkPhpEnvironment();
if (!empty($env_errors)) {
    $error_list_html = '<div class="error-list">';
    foreach ($env_errors as $error) {
        $error_list_html .= '<div class="error-item">' . htmlspecialchars($error) . '</div>';
    }
    $error_list_html .= '</div>';

    $php_version = PHP_VERSION;
    $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? htmlspecialchars($_SERVER['SERVER_SOFTWARE']) : '未知';
    $os = PHP_OS;

    $env_info_html = <<<HTML
<div class="environment-info">
    <p><strong>当前环境信息：</strong></p>
    <p>PHP版本: $php_version</p>
	<p>操作系统: $os</p>
   
    
</div>
HTML;

    showErrorPage(
        '系统环境错误',
        '系统环境检查失败',
        '',
        [
            'icon' => '⚙️',
            'show_retry' => true,
            'additional_html' => $error_list_html . $env_info_html
        ]
    );
}

define('QKCMS_TAG_PARSER_INITIALIZED', true);

function safeInclude($file_path)
{
    if (!file_exists($file_path) || !is_readable($file_path)) {
        return false;
    }

    $ext = pathinfo($file_path, PATHINFO_EXTENSION);
    if (strtolower($ext) !== 'php') {
        return false;
    }

    include_once $file_path;
    return true;
}

function removeApStyleFromBody($buffer)
{
    // 移除body标签中的ap-style属性
    $buffer = preg_replace('/<body([^>]*?)\s+ap-style(?:\s*=\s*["\'].*?["\'])?/i', '<body$1', $buffer);
    // 移除body标签中不需要的logged-in类
    $buffer = preg_replace('/<body([^>]*?)\s+class=("|\')([^"\']*)logged-in([^"\']*)("|\')/i', '<body$1 class=$2$3$4$5>', $buffer);
    // 如果class属性为空，移除它
    $buffer = preg_replace('/<body([^>]*?)\s+class=("|\')\2/i', '<body$1', $buffer);
    // 移除可能存在的独立ap-style字符串
    $buffer = str_replace('ap-style', '', $buffer);

    if (isset($GLOBALS['qkcms_license_dialog_html']) && is_string($GLOBALS['qkcms_license_dialog_html']) && $GLOBALS['qkcms_license_dialog_html'] !== '') {
        $dialog = $GLOBALS['qkcms_license_dialog_html'];
        if (strpos($buffer, 'id="qkcms-license-dialog"') === false) {
            if (stripos($buffer, '</body>') !== false) {
                $buffer = preg_replace('/<\/body>/i', $dialog . '</body>', $buffer, 1);
            } else {
                $buffer .= $dialog;
            }
        }
        $GLOBALS['qkcms_license_dialog_html'] = '';
    }

    return $buffer;
}

function qk_get_current_template_id()
{
    if (isset($_GET['software_id']) && is_numeric($_GET['software_id'])) return intval($_GET['software_id']);
    if (isset($_GET['category_id']) && is_numeric($_GET['category_id'])) return intval($_GET['category_id']);
    if (isset($_GET['cid']) && is_numeric($_GET['cid'])) return intval($_GET['cid']);
    if (isset($_GET['cat_id']) && is_numeric($_GET['cat_id'])) return intval($_GET['cat_id']);
    if (isset($_GET['id']) && is_numeric($_GET['id'])) return intval($_GET['id']);
    return 0;
}

function qk_render_home_topics_tab($order)
{
    global $conn;
    $allowed_orders = array('latest', 'comment', 'hot');
    $order = strtolower((string)$order);
    if (!in_array($order, $allowed_orders, true)) {
        $order = 'latest';
    }

    if ((!isset($conn) || !($conn instanceof mysqli) || $conn->connect_error) && function_exists('get_db_connection')) {
        $conn = get_db_connection();
    }

    if (file_exists('templates/tplrdr.php')) {
        include_once 'templates/tplrdr.php';
    }

    $template_path = 'templates/home_topics_tab.php';
    if (!file_exists($template_path)) {
        $content = '{qkcms:articles row=20 col=1 property=0 order=' . $order . ' category_id=-1 titlelen=34 description_len=90 page=1}
<div class="topic-item fade-in">
  <a href="{url}" class="topic-title">
    <div class="article-thumbnail-container">
      <img src="{thumbnail}" alt="{title}" class="article-thumbnail">
    </div>
  </a>
  <div class="topic-content">
    <div class="topic-header-row">
      <div class="topic-meta">
        <a href="/Member_id{author_id}.php" class="topic-author" target="_blank">{author}</a>
        <span class="topic-time">{date_only}</span>
      </div>
      <div class="topic-tags">
        <a href="{cat_url}"><span class="topic-tag">{category}</span></a>
      </div>
    </div>
    <a href="{url}" class="topic-title">{property} {title}</a>
    <p>描述: {description}</p>
    <div class="topic-footer">
      <div class="topic-stats">
        <span class="topic-stat"><span class="icon view"></span> {views}</span>
        <span class="topic-stat"><span class="icon message"></span> {comments}</span>
        <span class="topic-stat"><span class="icon like"></span> {like_count}</span>
      </div>
    </div>
  </div>
</div>
{/qkcms:articles}';
    } else {
        $qk_home_tab_order = $order;
        ob_start();
        include $template_path;
        $content = ob_get_clean();
    }

    if (function_exists('qkcms_tag_parser')) {
        $parsed_content = qkcms_tag_parser($content, qk_get_current_template_id());
        return $parsed_content;
    }
    if (function_exists('processTemplateContent')) {
        $processed_content = processTemplateContent($content, qk_get_current_template_id());
        return $processed_content;
    }
    return $content;
}

if (isset($_GET['ajax_home_topics']) && $_GET['ajax_home_topics'] === '1') {
    header('Content-Type: application/json; charset=UTF-8');
    $html = qk_render_home_topics_tab(isset($_GET['order']) ? $_GET['order'] : 'latest');
    echo json_encode(array(
        'success' => $html !== '',
        'html' => $html
    ), JSON_UNESCAPED_UNICODE);
    exit;
}

function renderTemplate($template_name, $check_templates_dir = true)
{
    if (empty($template_name) || !is_string($template_name)) {
        $template_name = 'index';
    }
    $fallback_template = '';

    // 处理栏目列表页面的模板选择
    if ($template_name === 'list') {
        $category_id = 0;
        $catgroup_id = 0;
        if (isset($_GET['software_id']) && is_numeric($_GET['software_id'])) {
            $category_id = intval($_GET['software_id']);
        } else if (isset($_GET['category_id']) && is_numeric($_GET['category_id'])) {
            $category_id = intval($_GET['category_id']);
        } else if (isset($_GET['cid']) && is_numeric($_GET['cid'])) {
            $category_id = intval($_GET['cid']);
        } else if (isset($_GET['cat_id']) && is_numeric($_GET['cat_id'])) {
            $category_id = intval($_GET['cat_id']);
        } else if (isset($_GET['id']) && is_numeric($_GET['id'])) {
            $category_id = intval($_GET['id']);
        }
        if (isset($_GET['catgroup_id']) && is_numeric($_GET['catgroup_id'])) {
            $catgroup_id = intval($_GET['catgroup_id']);
        }

        if ($category_id > 0 && isset($GLOBALS['conn'])) {
            $fallback_template = 'list.html';
            try {
                $stmt = $GLOBALS['conn']->prepare("SELECT template FROM categories WHERE id = ? LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param("i", $category_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $row = $result->fetch_assoc()) {
                        if (!empty($row['template'])) {
                            $template_name = $row['template'];
                        }
                    }
                    $stmt->close();
                }
            } catch (Exception $e) {
                // 出错时使用默认模板
            }
        }
        if ($category_id <= 0 && $catgroup_id > 0 && isset($GLOBALS['conn'])) {
            $fallback_template = 'catgroup.html';
            try {
                $catgroup_table = '';
                $rt = @$GLOBALS['conn']->query("SHOW TABLES LIKE 'catgroup'");
                if ($rt && $rt->num_rows > 0) $catgroup_table = 'catgroup';
                if ($rt) $rt->close();
                if ($catgroup_table === '') {
                    $rt2 = @$GLOBALS['conn']->query("SHOW TABLES LIKE 'qkcms_catgroup'");
                    if ($rt2 && $rt2->num_rows > 0) $catgroup_table = 'qkcms_catgroup';
                    if ($rt2) $rt2->close();
                }
                if ($catgroup_table !== '') {
                    $stmt = $GLOBALS['conn']->prepare("SELECT * FROM `{$catgroup_table}` WHERE id = ? LIMIT 1");
                    if ($stmt) {
                        $stmt->bind_param("i", $catgroup_id);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        if ($result && $row = $result->fetch_assoc()) {
                            if (isset($row['template']) && !empty($row['template'])) {
                                $template_name = $row['template'];
                            } else {
                                $template_name = 'catgroup.html';
                            }
                        }
                        $stmt->close();
                    }
                }
            } catch (Exception $e) {
                // 出错时使用默认模板
            }
        }
    }

    // 处理主页模板选择
    if ($template_name === 'index' && isset($GLOBALS['conn'])) {
        try {
            $stmt = $GLOBALS['conn']->prepare("SELECT home_template FROM settings WHERE id = 1 LIMIT 1");
            if ($stmt) {
                $stmt->execute();
                $result = $stmt->get_result();
                if ($result && $row = $result->fetch_assoc()) {
                    if (!empty($row['home_template'])) {
                        $template_name = $row['home_template'];
                    }
                }
                $stmt->close();
            }
        } catch (Exception $e) {
            // 出错时使用默认模板
        }
    }

    // 处理文章页面的模板选择
    if ($template_name === 'post') {
        $post_id = 0;
        if (isset($_GET['id']) && is_numeric($_GET['id'])) {
            $post_id = intval($_GET['id']);
        } else if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
            $post_id = intval($_GET['post_id']);
        }

        if ($post_id > 0 && isset($GLOBALS['conn'])) {
            try {
                $stmt = $GLOBALS['conn']->prepare("SELECT template FROM posts WHERE id = ? LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param("i", $post_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $row = $result->fetch_assoc()) {
                        if (!empty($row['template'])) {
                            $template_name = $row['template'];
                        }
                    }
                    $stmt->close();
                }
            } catch (Exception $e) {
                // 出错时使用默认模板
            }
        }
    }

    // 处理商品页面的模板选择
    if ($template_name === 'goods') {
        $goods_id = 0;
        if (isset($_GET['id']) && is_numeric($_GET['id'])) {
            $goods_id = intval($_GET['id']);
        }

        if ($goods_id > 0 && isset($GLOBALS['conn'])) {
            try {
                $stmt = $GLOBALS['conn']->prepare("SELECT template FROM goods WHERE id = ? LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param("i", $goods_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $row = $result->fetch_assoc()) {
                        if (!empty($row['template'])) {
                            $template_name = $row['template'];
                        }
                    }
                    $stmt->close();
                }
            } catch (Exception $e) {
                // 出错时使用默认模板
            }
        }
    }

    // 检查是否是首页模板（包括index.php和index.html）
    $is_index_template = $template_name === 'index' || $template_name === 'index.php' || $template_name === 'index.html';

    $paths = [];
    $paths[] = $template_name;

    // 智能路径查找：优先查找自定义模板，再查找默认模板
    if ($check_templates_dir && strpos($template_name, 'templates/') === false) {
        // 优先查找自定义模板目录 templates/skin/
        $paths[] = "templates/skin/{$template_name}";
        // 然后查找默认模板目录 templates/
        $paths[] = "templates/{$template_name}";
    }

    $has_extension = strpos($template_name, '.') !== false;
    if (!$has_extension) {
        $paths = array_merge($paths, [
            "{$template_name}.php",
            "{$template_name}.html"
        ]);
        if ($check_templates_dir) {
            // 优先查找自定义模板目录 templates/skin/
            $paths = array_merge($paths, [
                "templates/skin/{$template_name}.php",
                "templates/skin/{$template_name}.html"
            ]);
            // 然后查找默认模板目录 templates/
            $paths = array_merge($paths, [
                "templates/{$template_name}.php",
                "templates/{$template_name}.html"
            ]);
        }
    } else if ($is_index_template) {
        // 如果是首页模板且带扩展名，确保也能查找默认模板目录
        if ($check_templates_dir && strpos($template_name, 'templates/') === false) {
            $paths[] = "templates/{$template_name}";
        }
    }
    if ($is_index_template && $check_templates_dir) {
        // 先检查templates/index.php是否存在
        $index_path = "templates/index.php";
        if (file_exists($index_path)) {
            array_unshift($paths, $index_path);
        } else {
            // 如果index.php不存在，检查index.html
            $index_html_path = "templates/index.html";
            if (file_exists($index_html_path)) {
                array_unshift($paths, $index_html_path);
            }
        }
        $paths = array_unique($paths);
    }

    $paths = array_unique($paths);
    foreach ($paths as $path) {
        if (file_exists($path) && is_file($path)) {
            if (file_exists('templates/tplrdr.php')) {
                include_once 'templates/tplrdr.php';
            }

            $ext = pathinfo($path, PATHINFO_EXTENSION);
            ob_start();
            // 对所有模板文件都使用include来处理，这样HTML文件中的PHP代码也能被执行
            include_once $path;
            $content = ob_get_clean();

            $current_id = 0;
            if (isset($_GET['software_id']) && is_numeric($_GET['software_id'])) {
                $current_id = intval($_GET['software_id']);
            } else if (isset($_GET['category_id']) && is_numeric($_GET['category_id'])) {
                $current_id = intval($_GET['category_id']);
            } else if (isset($_GET['cid']) && is_numeric($_GET['cid'])) {
                $current_id = intval($_GET['cid']);
            } else if (isset($_GET['cat_id']) && is_numeric($_GET['cat_id'])) {
                $current_id = intval($_GET['cat_id']);
            } else if (isset($_GET['id']) && is_numeric($_GET['id'])) {
                $current_id = intval($_GET['id']);
            }

            if (function_exists('qkcms_tag_parser')) {
                $processed_content = qkcms_tag_parser($content, $current_id);
            } else if (function_exists('processTemplateContent')) {
                $processed_content = processTemplateContent($content, $current_id);
            } else {
                $processed_content = $content;
            }

            // 将主题CSS插入到</head>标签之前
            global $themeCss;
            if (!empty($themeCss) && strpos($processed_content, '</head>') !== false) {
                $processed_content = preg_replace('/<\/head>/i', '<style>' . $themeCss . '</style></head>', $processed_content);
            }


            $processed_content = removeApStyleFromBody($processed_content);
            $processed_content = parse_plugin_tags($processed_content);


            echo $processed_content;
            return;
        }
    }

    // 顶级栏目/栏目模板不存在时做合理回退
    if ($fallback_template && $fallback_template !== $template_name) {
        return renderTemplate($fallback_template, $check_templates_dir);
    }

    echo "{$template_name} 页面不存在";
}

// 检查ID是否存在于数据库
function idExistsInDatabase($table, $id_field, $id)
{
    global $conn;

    // 如果连接不存在或无效，直接返回true避免错误（保守处理）
    if (!isset($conn) || !($conn instanceof mysqli) || $conn->connect_error) {
        return true;
    }

    try {
        // 使用预处理语句防止SQL注入
        $stmt = $conn->prepare("SELECT 1 FROM $table WHERE $id_field = ? LIMIT 1");
        if (!$stmt) {
            return true; // 预处理失败时保守处理
        }

        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->store_result();

        $exists = $stmt->num_rows > 0;
        $stmt->close();

        return $exists;
    } catch (Exception $e) {
        // 发生异常时保守处理，返回true
        return true;
    }
}

function qk_match_catgroup_custom_url($conn, $customCandidates)
{
    if (!$conn || !($conn instanceof mysqli) || $conn->connect_error || empty($customCandidates)) {
        return 0;
    }
    $catgroup_table = '';
    $rt = @$conn->query("SHOW TABLES LIKE 'catgroup'");
    if ($rt && $rt->num_rows > 0) {
        $catgroup_table = 'catgroup';
    }
    if ($rt) $rt->close();
    if ($catgroup_table === '') {
        $rt2 = @$conn->query("SHOW TABLES LIKE 'qkcms_catgroup'");
        if ($rt2 && $rt2->num_rows > 0) {
            $catgroup_table = 'qkcms_catgroup';
        }
        if ($rt2) $rt2->close();
    }
    if ($catgroup_table === '') return 0;

    foreach ($customCandidates as $custom_url) {
        $stmt = $conn->prepare("SELECT id FROM `{$catgroup_table}` WHERE custom_url = ? LIMIT 1");
        if (!$stmt) continue;
        $stmt->bind_param('s', $custom_url);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result && $row = $result->fetch_assoc()) {
            $stmt->close();
            return intval($row['id']);
        }
        $stmt->close();
    }
    return 0;
}

function qk_get_current_host_name()
{
    $host = isset($_SERVER['HTTP_HOST']) ? strtolower(trim((string)$_SERVER['HTTP_HOST'])) : '';
    $host = preg_replace('/:\d+$/', '', $host);
    return trim($host);
}

function qk_parse_bind_domain_list($bindDomain)
{
    if (!is_string($bindDomain) || trim($bindDomain) === '') return array();
    $raw = str_replace(['，', ';', "\r", "\n", "\t"], [',', ',', ',', ',', ','], $bindDomain);
    $parts = explode(',', $raw);
    $hosts = array();
    foreach ($parts as $part) {
        $host = strtolower(trim($part));
        if ($host === '') continue;
        if (strpos($host, '://') !== false) {
            $parsed = parse_url($host, PHP_URL_HOST);
            $host = is_string($parsed) ? strtolower(trim($parsed)) : '';
        }
        if ($host === '') continue;
        $host = preg_replace('/[\/\?#].*$/', '', $host);
        $host = preg_replace('/:\d+$/', '', $host);
        $host = trim($host, '.');
        if ($host !== '') $hosts[$host] = $host;
    }
    return array_values($hosts);
}

function qk_get_primary_bind_domain($bindDomain)
{
    $list = qk_parse_bind_domain_list($bindDomain);
    return !empty($list) ? $list[0] : '';
}

function qk_get_post_id_by_custom_url_and_host($conn, $customUrl, $host)
{
    if (!$conn || !($conn instanceof mysqli) || $conn->connect_error || !is_string($customUrl) || trim($customUrl) === '') {
        return 0;
    }
    $host = strtolower(trim((string)$host));
    $sql = "SELECT id FROM posts WHERE custom_url = ? AND status = 1 AND (bind_domain IS NULL OR bind_domain = '' OR FIND_IN_SET(?, REPLACE(REPLACE(LOWER(bind_domain), ' ', ''), ';', ',')) > 0) LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return 0;
    $stmt->bind_param('ss', $customUrl, $host);
    $stmt->execute();
    $result = $stmt->get_result();
    $id = 0;
    if ($result && $row = $result->fetch_assoc()) {
        $id = intval($row['id'] ?? 0);
    }
    $stmt->close();
    return $id;
}

function qk_get_post_id_for_host_root($conn, $host)
{
    if (!$conn || !($conn instanceof mysqli) || $conn->connect_error || $host === '') return 0;
    $host = strtolower(trim((string)$host));
    $sql = "SELECT id FROM posts WHERE status = 1 AND bind_domain IS NOT NULL AND bind_domain != '' AND FIND_IN_SET(?, REPLACE(REPLACE(LOWER(bind_domain), ' ', ''), ';', ',')) > 0 ORDER BY id ASC LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return 0;
    $stmt->bind_param('s', $host);
    $stmt->execute();
    $result = $stmt->get_result();
    $id = 0;
    if ($result && $row = $result->fetch_assoc()) {
        $id = intval($row['id'] ?? 0);
    }
    $stmt->close();
    return $id;
}

function qk_redirect_post_to_primary_bind_domain($conn, $postId)
{
    $postId = intval($postId);
    if ($postId <= 0 || !$conn || !($conn instanceof mysqli) || $conn->connect_error) return;
    $stmt = $conn->prepare("SELECT bind_domain FROM posts WHERE id = ? AND status = 1 LIMIT 1");
    if (!$stmt) return;
    $stmt->bind_param('i', $postId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();
    if (!$row || !isset($row['bind_domain'])) return;
    $targetHost = qk_get_primary_bind_domain((string)$row['bind_domain']);
    if ($targetHost === '') return;
    $currentHost = qk_get_current_host_name();
    $requestUri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '/';
    if ($requestUri === '') $requestUri = '/';
    $requestPath = parse_url($requestUri, PHP_URL_PATH);
    if (!is_string($requestPath) || $requestPath === '') $requestPath = '/';
    if ($currentHost === $targetHost && $requestPath === '/') return;
    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $scheme . '://' . $targetHost . '/');
    exit;
}

function getSafeRouteParam()
{
    $route = 'index';
    // 优先使用IIS的HTTP_X_ORIGINAL_URL（URL Rewrite模块设置）
    if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
        $requestUri = $_SERVER['HTTP_X_ORIGINAL_URL'];
    }
    // 其次使用PATH_INFO
    elseif (isset($_SERVER['PATH_INFO'])) {
        $requestUri = $_SERVER['PATH_INFO'];
    }
    // 最后使用REQUEST_URI
    else {
        $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    }

    // 直接使用requestUri，避免parse_url在处理中文时的问题
    // 移除查询参数部分
    $pathParts = $requestUri;
    if (strpos($pathParts, '?') !== false) {
        $pathParts = substr($pathParts, 0, strpos($pathParts, '?'));
    }
    $rawPathForCustom = urldecode($pathParts);
    $hasTrailingSlash = (substr($rawPathForCustom, -1) === '/');
    $pathParts = trim($pathParts, '/');
    // 对路径进行URL解码，确保中文能正确显示
    $pathParts = urldecode($pathParts);
    $currentHost = qk_get_current_host_name();

    if (empty($pathParts) || $pathParts === '' || $pathParts === '/') {
        $conn = get_db_connection();
        if ($conn) {
            $postId = qk_get_post_id_for_host_root($conn, $currentHost);
            if ($postId > 0) {
                $_GET['id'] = $postId;
                return 'post';
            }
        }
        return 'index';
    }

    if (isset($_GET['action'])) {
        if ($_GET['action'] == 'logout') {
            return 'login';
        }
        $route = $_GET['action'];
    } else if (preg_match('/^post_id([0-9]+)(_comments([0-9]+)|_ctpage([0-9]+))?\.(php|html)$/i', $pathParts, $matches)) {
        $post_id = $matches[1];
        $_GET['id'] = $post_id;

        // 如果有评论页码，设置page参数
        if (isset($matches[3]) && !empty($matches[3])) {
            $_GET['page'] = $matches[3];
        } else if (isset($matches[4]) && !empty($matches[4])) {
            $_GET['page'] = $matches[4];
        }

        // 检查文章ID是否存在
        if (idExistsInDatabase('posts', 'id', $post_id)) {
            // 检查文章是否有自定义URL/绑定域名，如果有则301重定向到规范地址
            $conn = get_db_connection();
            if ($conn) {
                $sql = "SELECT custom_url, bind_domain FROM posts WHERE id = ? LIMIT 1";
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $stmt->bind_param('i', $post_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $row = $result->fetch_assoc()) {
                        $custom_url = isset($row['custom_url']) ? trim((string)$row['custom_url']) : '';
                        $currentHost = qk_get_current_host_name();
                        $targetHost = qk_get_primary_bind_domain(isset($row['bind_domain']) ? (string)$row['bind_domain'] : '');
                        if ($targetHost !== '') {
                            $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
                            header('HTTP/1.1 301 Moved Permanently');
                            header('Location: ' . $scheme . '://' . $targetHost . '/');
                            exit;
                        }
                        if ($custom_url !== '') {
                            $redirect_path = '/' . ltrim($custom_url, '/');
                            if (isset($_GET['page']) && $_GET['page'] > 1) {
                                $redirect_path .= '?page=' . $_GET['page'];
                            }
                            header('HTTP/1.1 301 Moved Permanently');
                            header('Location: ' . $redirect_path);
                            exit;
                        }
                    }
                    $stmt->close();
                }
            }
            $route = 'post';
        } else {
            $route = '404'; // 文章不存在，返回404
        }
    } else if (preg_match('/^goods_id([0-9]+)\.(php|html)$/i', $pathParts, $matches)) {
        $goods_id = $matches[1];
        $_GET['id'] = $goods_id;

        // 检查商品ID是否存在
        if (idExistsInDatabase('goods', 'id', $goods_id)) {
            // 检查商品是否有自定义URL，如果有则301重定向
            $conn = get_db_connection();
            if ($conn) {
                $sql = "SELECT custom_url FROM goods WHERE id = ? AND custom_url IS NOT NULL AND custom_url != '' LIMIT 1";
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $stmt->bind_param('i', $goods_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $row = $result->fetch_assoc()) {
                        // 有自定义URL，301重定向
                        $custom_url = $row['custom_url'];
                        $redirect_url = '/' . $custom_url;
                        header('HTTP/1.1 301 Moved Permanently');
                        header('Location: ' . $redirect_url);
                        exit;
                    }
                    $stmt->close();
                }
            }
            $route = 'goods';
        } else {
            $route = '404'; // 商品不存在，返回404
        }
    } else if ($pathParts !== '' && (strpos($pathParts, '/') !== false || $hasTrailingSlash)) {
        $matched = false;
        $customCandidates = array();
        $basePath = trim((string)$pathParts);
        $basePath = str_replace('\\', '/', $basePath);
        $basePath = preg_replace('#/+#', '/', $basePath);
        $basePath = trim($basePath, '/');
        $isSingleSegmentPath = ($basePath !== '' && strpos($basePath, '/') === false);
        if ($basePath !== '') {
            $customCandidates[] = $basePath;
            $customCandidates[] = $basePath . '/';
            if (preg_match('/\.(html|php)$/i', $basePath)) {
                $customCandidates[] = '/' . $basePath;
            } else {
                $customCandidates[] = '/' . $basePath . '/';
                $customCandidates[] = '/' . $basePath;
            }
            $customCandidates[] = $basePath . '.html';
            $customCandidates[] = '/' . $basePath . '.html';
        }
        $customCandidates = array_values(array_unique(array_filter($customCandidates)));
        $conn = get_db_connection();
        if ($conn && !empty($customCandidates)) {
            if ($isSingleSegmentPath) {
                $catgroup_id = qk_match_catgroup_custom_url($conn, $customCandidates);
                if ($catgroup_id > 0) {
                    $_GET['catgroup_id'] = $catgroup_id;
                    $route = 'list';
                    $matched = true;
                }
            }
            foreach ($customCandidates as $custom_url) {
                if ($matched) break;
                $stmt = $conn->prepare("SELECT id FROM categories WHERE custom_url = ? LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param('s', $custom_url);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $row = $result->fetch_assoc()) {
                        $_GET['software_id'] = $row['id'];
                        $route = 'list';
                        $matched = true;
                    }
                    $stmt->close();
                    if ($matched) break;
                }
            }
            if (!$matched) {
                foreach ($customCandidates as $custom_url) {
                    $post_id = qk_get_post_id_by_custom_url_and_host($conn, $custom_url, $currentHost);
                    if ($post_id > 0) {
                        $_GET['id'] = $post_id;
                        $route = 'post';
                        $matched = true;
                        break;
                    }
                }
            }
            if (!$matched) {
                foreach ($customCandidates as $custom_url) {
                    $stmt = $conn->prepare("SELECT id FROM goods WHERE custom_url = ? AND status = 1 LIMIT 1");
                    if ($stmt) {
                        $stmt->bind_param('s', $custom_url);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        if ($result && $row = $result->fetch_assoc()) {
                            $_GET['id'] = $row['id'];
                            $route = 'goods';
                            $matched = true;
                        }
                        $stmt->close();
                        if ($matched) break;
                    }
                }
            }
            if (!$matched) {
                $catgroup_id = qk_match_catgroup_custom_url($conn, $customCandidates);
                if ($catgroup_id > 0) {
                    $_GET['catgroup_id'] = $catgroup_id;
                    $route = 'list';
                    $matched = true;
                }
            }
        }
        if (!$matched) {
            $route = '404';
        }
    } else if (preg_match('/^[a-zA-Z0-9_-]+$/', $pathParts)) {
        $matched = false;
        $basePath = trim((string)$pathParts);
        $customCandidates = array(
            $basePath,
            $basePath . '/',
            '/' . $basePath,
            '/' . $basePath . '/'
        );
        $customCandidates = array_values(array_unique(array_filter($customCandidates)));
        $conn = get_db_connection();

        // 先检查分类自定义URL
        if ($conn) {
            $category_id_found = 0;
            $stmt = $conn->prepare("SELECT id, custom_url FROM categories LIMIT 100");
            if ($stmt) {
                $stmt->execute();
                $result = $stmt->get_result();
                if ($result) {
                    while ($row = $result->fetch_assoc()) {
                        $db_custom_url = trim((string)$row['custom_url']);
                        $db_custom_url_no_slash = ltrim($db_custom_url, '/');
                        if ($db_custom_url === $basePath || $db_custom_url_no_slash === $basePath) {
                            $category_id_found = intval($row['id']);
                            break;
                        }
                    }
                    $result->free();
                }
                $stmt->close();
            }

            if ($category_id_found > 0) {
                $_GET['software_id'] = $category_id_found;
                $route = 'list';
                $matched = true;
            }
        }

        // 再检查顶级栏目自定义URL
        if (!$matched) {
            $catgroup_id = qk_match_catgroup_custom_url($conn, $customCandidates);
            if ($catgroup_id > 0) {
                $_GET['catgroup_id'] = $catgroup_id;
                $route = 'list';
                $matched = true;
            }
        }

        if (!$matched) {
            $route = $pathParts;
        }
    } else if (preg_match('/^([a-zA-Z0-9_-]+)\.(html|php)$/i', $pathParts, $matches) && !preg_match('/^list_id[0-9]+/', $matches[1]) && !preg_match('/^Member_id[0-9]+/', $matches[1]) && !preg_match('/^cg_id[0-9]+$/i', $matches[1])) {
        // 自定义URL路由 - 优先检查栏目自定义URL，再检查文章自定义URL
        // 排除 list_idXXX 格式（这是默认分类URL格式）和 Member_idXXX 格式（用户中心URL格式）
        $custom_url = $matches[1] . '.' . $matches[2];
        $matched = false;

        // 先检查是否是分类自定义URL
        $conn = get_db_connection();
        if ($conn) {
            $category_id_found = 0;
            $custom_url_no_ext = preg_replace('/\.(html|php)$/i', '', $custom_url);
            $stmt = $conn->prepare("SELECT id, custom_url FROM categories LIMIT 100");
            if ($stmt) {
                $stmt->execute();
                $result = $stmt->get_result();
                if ($result) {
                    while ($row = $result->fetch_assoc()) {
                        $db_custom_url = trim((string)$row['custom_url']);
                        if ($db_custom_url === $custom_url || $db_custom_url === $custom_url_no_ext || 
                            ltrim($db_custom_url, '/') === $custom_url_no_ext) {
                            $category_id_found = intval($row['id']);
                            break;
                        }
                    }
                    $result->free();
                }
                $stmt->close();
            }

            if ($category_id_found > 0) {
                $_GET['software_id'] = $category_id_found;
                $route = 'list';
                $matched = true;
            } else {
                // 不是分类自定义URL，检查是否是文章自定义URL
                $post_id = qk_get_post_id_by_custom_url_and_host($conn, $custom_url, $currentHost);
                if ($post_id > 0) {
                    $_GET['id'] = $post_id;
                    $route = 'post';
                    $matched = true;
                }

                // 不是文章自定义URL，检查是否是商品自定义URL
                if (!$matched) {
                    $stmt = $conn->prepare("SELECT id FROM goods WHERE custom_url = ? AND status = 1 LIMIT 1");
                    if ($stmt) {
                        $stmt->bind_param('s', $custom_url);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        if ($result && $row = $result->fetch_assoc()) {
                            $_GET['id'] = $row['id'];
                            $route = 'goods';
                            $matched = true;
                        }
                        $stmt->close();
                    }
                }

                if (!$matched) {
                    $catgroup_id = qk_match_catgroup_custom_url($conn, array($custom_url));
                    if ($catgroup_id > 0) {
                        $_GET['catgroup_id'] = $catgroup_id;
                        $route = 'list';
                        $matched = true;
                    }
                }
            }
        }

        // 如果没有匹配到自定义URL，设置为路径名作为路由（如index, login等）
        if (!$matched) {
            $route = $matches[1];
        }
    } else if (preg_match('/^cg_id([0-9]+)\.html$/i', $pathParts, $matches)) {
        $catgroup_id = intval($matches[1]);
        $_GET['catgroup_id'] = $catgroup_id;
        $route = 'list';
    } else if (preg_match('/^list_id([0-9]+)(_page([0-9]+))?\.(php|html)$/i', $pathParts, $matches)) {
        $category_id = $matches[1];
        $_GET['software_id'] = $category_id;

        // 如果有页码，设置page参数
        if (isset($matches[3]) && !empty($matches[3])) {
            $_GET['page'] = $matches[3];
        }

        // 检查分类ID是否存在
        if (idExistsInDatabase('categories', 'id', $category_id)) {
            $route = 'list';
        } else {
            $route = '404'; // 分类不存在，返回404
        }
    } else if (preg_match('/^index_page([0-9]+)\.(php|html)$/i', $pathParts, $matches)) {
        // 首页带分页，提取页码
        $_GET['page'] = $matches[1];
        $route = 'index';
    } else if (preg_match('/^category_page([0-9]+)\.(php|html)$/i', $pathParts, $matches)) {
        // 分类页面带分页，提取页码
        $_GET['page'] = $matches[1];
        $route = 'category';
    } else if (preg_match('/^tag_index\.html$/i', $pathParts)) {
        // tag首页，直接使用tag_index模板
        $route = 'tag_index';
    } else if (preg_match('/^tag_([^_]+)_page([0-9]+)\.html$/i', $pathParts, $matches)) {
        // tag页面带分页，提取tag和页码
        // 处理URL编码，避免双重解码
        $tag = $matches[1];
        // 如果包含%XX格式的编码字符，进行一次解码
        if (preg_match('/%[0-9A-F]{2}/i', $tag)) {
            $tag = urldecode($tag);
        }
        $_GET['tag'] = $tag;
        $_GET['page'] = $matches[2];
        $route = 'tag';
    } else if (preg_match('/^tag_([^\.]+)\.html$/i', $pathParts, $matches)) {
        // 处理URL编码，避免双重解码
        $tag = $matches[1];
        // 如果包含%XX格式的编码字符，进行一次解码
        if (preg_match('/%[0-9A-F]{2}/i', $tag)) {
            $tag = urldecode($tag);
        }
        $_GET['tag'] = $tag;
        $route = 'tag';
    } else if (preg_match('/^search_([^_]+)_page([0-9]+)\.html$/i', $pathParts, $matches)) {
        // 搜索页面带分页，提取搜索词和页码
        // 处理URL编码，避免双重解码
        $searchTerm = $matches[1];
        // 如果包含%XX格式的编码字符，进行一次解码
        if (preg_match('/%[0-9A-F]{2}/i', $searchTerm)) {
            $searchTerm = urldecode($searchTerm);
        }
        $_GET['search'] = $searchTerm;
        $_GET['page'] = $matches[2];
        $route = 'search';
    } else if (preg_match('/^search_([^\.]+)\.html$/i', $pathParts, $matches)) {
        // 搜索页面，提取搜索词
        // 处理URL编码，避免双重解码
        $searchTerm = $matches[1];
        // 如果包含%XX格式的编码字符，进行一次解码
        if (preg_match('/%[0-9A-F]{2}/i', $searchTerm)) {
            $searchTerm = urldecode($searchTerm);
        }
        $_GET['search'] = $searchTerm;
        $route = 'search';
    } else if (preg_match('/^Member_id([0-9]+)_(post|comment|shop)\.html$/i', $pathParts, $matches)) {
        // 用户中心不同内容页面，提取用户ID和内容类型
        $user_id = $matches[1];
        $content_type = $matches[2];
        $_GET['id'] = $user_id;

        // 根据内容类型设置tab参数
        switch ($content_type) {
            case 'post':
                $_GET['tab'] = 'latest'; // 文章默认显示最新
                break;
            case 'comment':
                $_GET['tab'] = 'comment';
                break;
            case 'shop':
                $_GET['tab'] = 'product';
                break;
        }

        // 检查用户ID是否存在
        if (idExistsInDatabase('users', 'id', $user_id)) {
            $route = 'member';
        } else {
            $route = '404'; // 用户不存在，返回404
        }
    } else if (preg_match('/^Member_id([0-9]+)\.html$/i', $pathParts, $matches)) {
        // 用户中心页面，提取用户ID
        $user_id = $matches[1];
        $_GET['id'] = $user_id;

        // 检查用户ID是否存在
        if (idExistsInDatabase('users', 'id', $user_id)) {
            $route = 'member';
        } else {
            $route = '404'; // 用户不存在，返回404
        }
    } else if (preg_match('/^([a-zA-Z0-9_-]+)\.(html|php)$/i', $pathParts, $matches)) {
        // 自定义URL匹配 - 查询数据库（放在其他特定规则之后）
        $custom_url_html = $matches[1] . '.html';
        $custom_url_php = $matches[1] . '.php';
        // 排除已知的系统路由
        if (!in_array($matches[1], array('index', 'login', 'register', 'member', 'tag', 'search', 'category', 'list', 'post', 'publish'))) {
            $conn = get_db_connection();
            if ($conn) {
                // 同时查询 .html 和 .php 后缀
                $sql = "SELECT id FROM posts WHERE (custom_url = ? OR custom_url = ?) AND status = 1 AND (bind_domain IS NULL OR bind_domain = '' OR FIND_IN_SET(?, REPLACE(REPLACE(LOWER(bind_domain), ' ', ''), ';', ',')) > 0) LIMIT 1";
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $stmt->bind_param('sss', $custom_url_html, $custom_url_php, $currentHost);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $row = $result->fetch_assoc()) {
                        $_GET['id'] = $row['id'];
                        $route = 'post';
                    }
                    $stmt->close();
                }
            }
        }
        // 如果没有匹配到自定义URL，保持原有逻辑
        if (!isset($route) || $route === 'index') {
            $route = $matches[1];
        }
    } else if (strpos($pathParts, 'post.php') !== false) {
        $route = 'post';
        if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
            $post_id = $_GET['post_id'];
            $_GET['id'] = $post_id;

            // 检查文章ID是否存在
            if (!idExistsInDatabase('posts', 'id', $post_id)) {
                $route = '404';
            }
        }
    } else {
        $segments = explode('/', $pathParts);
        $firstSegment = isset($segments[0]) ? $segments[0] : '';

        if (!empty($firstSegment)) {
            if (strpos($firstSegment, '.php') !== false) {
                $firstSegment = str_replace('.php', '', $firstSegment);
            }
            if (strpos($firstSegment, '.html') !== false) {
                $firstSegment = str_replace('.html', '', $firstSegment);
            }
            $route = $firstSegment;

            if (count($segments) > 1 && is_numeric($segments[1])) {
                $_GET['id'] = $segments[1];

                // 如果是文章或列表页面，检查ID是否存在
                if ($route === 'post' && !idExistsInDatabase('posts', 'id', $segments[1])) {
                    $route = '404';
                } else if ($route === 'list' && !idExistsInDatabase('categories', 'id', $segments[1])) {
                    $route = '404';
                }
            }
        }
    }

    $segments = explode('/', $pathParts);
    $firstSegment = isset($segments[0]) ? $segments[0] : '';
    $hasSubPath = count($segments) > 1;

    $route = preg_replace('/[^a-zA-Z0-9_]/', '', $route);

    if ($route === 'admin' && $hasSubPath) {
        $adminFilePath = __DIR__ . '/admin/' . $segments[1] . '.php';
        if (!file_exists($adminFilePath)) {
            return '404';
        }
    }

    $allowedActions = ['index', 'list', 'login', 'logout', 'post_id', 'post', 'admin', '404', 'aa', 'about', 'contact', 'tag', 'tag_index', 'search', 'category', 'member', 'recharge', 'payapi', 'goods', 'publish', 'tpltool'];
    if (!in_array($route, $allowedActions)) {
        $route = '404';
    }

    return $route;
}

// 使用getRequestUri()函数获取URL路径，兼容IIS环境
$requestUri = getRequestUri();
$pathParts = parse_url($requestUri, PHP_URL_PATH);

if (strpos($pathParts, '.php') !== false && strpos($pathParts, '.html') === false) {
    // 排除admin目录、login.php recharge.php install.php post.php generator.php的重定向
    if ((strpos($requestUri, 'admin/') === false && strpos($pathParts, '/login.php') === false && strpos($pathParts, '/payapi.php') === false && strpos($pathParts, '/recharge.php') === false && strpos($pathParts, '/install.php') === false && strpos($pathParts, '/post.php') === false && strpos($pathParts, '/generator.php') === false) && !isset($_POST['action']) && !isset($_POST['publish_article']) && !isset($_POST['edit_article'])) {
        if (preg_match('/post_id([0-9]+)\.php$/i', $pathParts, $matches)) {
            $htmlUrl = '/post_id' . $matches[1] . '.html';
        } else if (preg_match('/list_id([0-9]+)(_page([0-9]+))?\.php$/i', $pathParts, $matches)) {
            if (isset($matches[3]) && !empty($matches[3])) {
                $htmlUrl = '/list_id' . $matches[1] . '_page' . $matches[3] . '.html';
            } else {
                $htmlUrl = '/list_id' . $matches[1] . '.html';
            }
        } else if (preg_match('/post\.php\?(id|post_id)=([0-9]+)/i', $requestUri, $matches)) {
            $htmlUrl = '/post_id' . $matches[2] . '.html';
        } else if (preg_match('/list\.php\?software_id=([0-9]+)(&page=([0-9]+))?/i', $requestUri, $matches)) {
            if (isset($matches[3]) && !empty($matches[3])) {
                $htmlUrl = '/list_id' . $matches[1] . '_page' . $matches[3] . '.html';
            } else {
                $htmlUrl = '/list_id' . $matches[1] . '.html';
            }
        } else if ($pathParts === '/index.php') {
            $htmlUrl = '/index.html';
        } else {
            // 检查是否是自定义URL（.php后缀），如果是则不重定向
            $check_url = basename($pathParts);
            $conn = get_db_connection();
            $is_custom_url = false;
            if ($conn) {
                $stmt = $conn->prepare("SELECT id FROM categories WHERE custom_url = ? LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param('s', $check_url);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result && $result->fetch_assoc()) {
                        $is_custom_url = true;
                    }
                    $stmt->close();
                }
                if (!$is_custom_url) {
                    $post_id = qk_get_post_id_by_custom_url_and_host($conn, $check_url, qk_get_current_host_name());
                    if ($post_id > 0) {
                        $is_custom_url = true;
                    }
                }
            }

            if (!$is_custom_url) {
                $htmlUrl = str_replace('.php', '.html', $pathParts);
            }
        }

        if (isset($htmlUrl)) {
            header('HTTP/1.1 301 Moved Permanently');
            header('Location: ' . $htmlUrl);
            exit;
        }
    }
}

if (isset($_POST['action']) && !empty($_POST['action'])) {
    // 处理不同页面的AJAX请求
    $requestUri = getRequestUri();

    // 处理充值订单创建请求
    if ($_POST['action'] === 'create_order' && strpos($requestUri, 'recharge') !== false) {
        if (file_exists('templates/recharge.php')) {
            include_once 'templates/recharge.php';
            exit;
        }
    }
    // 处理文章编辑和发布参数设置请求
    elseif ($_POST['action'] === 'set_article_params') {
        if (file_exists('admin/admin.php')) {
            include_once 'admin/admin.php';
            exit;
        }
    }
    // 处理投稿页面AJAX请求
    elseif (strpos($requestUri, 'publish') !== false) {
        if (file_exists('templates/publish.php')) {
            include_once 'templates/publish.php';
            exit;
        }
    }
    // 处理个人介绍保存请求
    elseif (strpos($requestUri, 'Member') !== false || $_POST['action'] === 'update_bio') {
        if (file_exists('templates/member.php')) {
            include_once 'templates/member.php';
            exit;
        }
    }
    // 处理文章相关请求
    elseif (file_exists('templates/post.php')) {
        include_once 'templates/post.php';
        exit;
    }
}

$action = getSafeRouteParam();

if (empty($action) || $action === '') {
    $action = 'index';
}

global $conn, $db_error;
try {
    if (!isset($db_error)) {
        $db_error = null;
    }

    $conn = get_db_connection();

    $is_db_error = !empty($db_error);
    $is_conn_invalid = !isset($conn) || $conn === false ||
        ($conn instanceof mysqli && $conn->connect_error);

    if ($is_db_error || $is_conn_invalid) {
        $error_msg = !empty($db_error) ? $db_error : '数据库连接失败';

        echo getErrorPageHeader('系统错误 - 数据库连接失败');
        echo '<body>';
        echo '<div class="error-container">';
        echo '<div class="error-icon">⚠️</div>';
        echo '<h1>数据库连接失败</h1>';
        echo '<p>系统无法连接到数据库，请检查以下事项：</p>';
        echo '<ul class="checklist">';
        echo '<li>MySQL 服务是否已启动</li>';
        echo '<li>数据库用户名和密码是否正确</li>';
        echo '<li>数据库名称是否存在</li>';
        echo '<li>服务器网络连接是否正常</li>';
        echo '</ul>';
        echo '<div class="progress-container">';
        echo '<div class="progress-bar" id="progressBar"></div>';
        echo '</div>';
        echo '<button class="retry-btn" onclick="retryConnection()">重试连接</button>';
        echo '<script>';
        echo 'function retryConnection() {';
        echo 'const progressBar = document.getElementById("progressBar");';
        echo 'let progress = 0;';
        echo 'const interval = setInterval(() => {';
        echo 'progress += 1;';
        echo 'progressBar.style.width = progress + "%";';
        echo 'if (progress >= 100) {';
        echo 'clearInterval(interval);';
        echo 'window.location.reload();';
        echo '}';
        echo '}, 20);';
        echo '}';
        echo '</script>';
        echo '</div>';
        echo '</body>';
        echo '</html>';
        exit;
    }
} catch (Exception $e) {
    showErrorPage(
        '错误 - QKCMS',
        '系统错误',
        '发生了未预期的系统错误。错误信息: ' . htmlspecialchars($e->getMessage()),
        [
            'icon' => '⚙️',
            'additional_html' => '<p>请联系管理员进行处理。</p>'
        ]
    );
}

if ($action === 'post' && isset($_GET['id']) && is_numeric($_GET['id']) && isset($conn) && $conn && !isset($conn->connect_error)) {
    qk_redirect_post_to_primary_bind_domain($conn, intval($_GET['id']));
}

if ($action === 'admin') {
    $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    $pathParts = parse_url($requestUri, PHP_URL_PATH);
    $segments = explode('/', trim($pathParts, '/'));
    $hasSubPath = count($segments) > 1;

    if (!hasPermission('admin')) {
        header('Location: /login');
        exit;
    }

    if ($hasSubPath && $segments[0] === 'admin') {
        $subPage = $segments[1];
        $subPage = str_replace(['.php', '.html'], '', $subPage);
        $subPage = preg_replace('/[^a-zA-Z0-9_]/', '', $subPage);

        $adminFilePath = 'admin/' . $subPage . '.php';
        if (safeInclude($adminFilePath)) {
            exit;
        } else {
            showErrorPage(
                '页面不存在',
                '页面未找到',
                "请求的后台页面不存在",
                ['icon' => '🔍']
            );
        }
    } else {
        if (!safeInclude('admin/admin.php')) {
            showErrorPage(
                '页面不存在',
                '页面未找到',
                "后台页面不存在",
                ['icon' => '🔍']
            );
        }
        exit;
    }
}

$is_admin_page = in_array($action, ['admin', 'login', 'register', 'logout', 'ajax']);
$is_frontend_page = !$is_admin_page;

// 检查网站状态，非管理员页面且网站暂停访问时直接显示关闭原因
if ($is_frontend_page) {
    $siteSettings = getSettings($conn);

    // 如果网站状态为暂停访问，直接显示关闭原因
    if (isset($siteSettings['status']) && $siteSettings['status'] == 1) {
        $close_reason = isset($siteSettings['close_reason']) ? $siteSettings['close_reason'] : '网站正在维护中，暂时无法访问';

        // 清除所有输出缓冲区，确保只显示关闭提示
        while (ob_get_length() > 0) {
            ob_end_clean();
        }

        // 先处理关闭原因，防止XSS攻击
        $safe_close_reason = htmlspecialchars($close_reason);

        // 直接输出关闭提示HTML，不渲染任何其他内容
        echo <<<HTML
<!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 {
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            text-align: center;
            color: #333;
        }
        
        .maintenance-container {
            background-color: #ffffff;
            padding: 40px 30px;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            width: 90%;
            transform: translateY(0);
            transition: transform 0.3s ease;
        }
        
        .maintenance-container:hover {
            transform: translateY(-5px);
        }
        
        .maintenance-icon {
            font-size: 3rem;
            margin-bottom: 20px;
            display: block;
        }
        
        h1 {
            color: #4a5568;
            margin-bottom: 15px;
            font-size: 1.8rem;
            font-weight: 700;
            letter-spacing: -0.5px;
        }
        
        p {
            color: #718096;
            font-size: 1rem;
            line-height: 1.6;
            font-weight: 400;
        }
      
    </style>
</head>
<body>
    <div class="maintenance-container">
        <span class="maintenance-icon">🔧</span>
        <h1>网站维护中</h1>
        <p>$safe_close_reason</p>
    </div>
</body>
</html>
HTML;
        exit;
    }
}

if ($is_frontend_page) {
    $qk_page_cache_scope = qk_get_page_cache_scope($action, $__qk_uri, $_GET);
    $qk_guest_page_cache_enabled = qk_can_use_guest_page_cache($action, $__qk_uri, $_GET);
    $qk_shared_page_cache_enabled = qk_can_use_shared_page_cache($action, $__qk_uri, $_GET);

    if ($qk_guest_page_cache_enabled || $qk_shared_page_cache_enabled) {
        $qk_cached_page = $qk_guest_page_cache_enabled
            ? qk_read_guest_page_cache($action, $__qk_uri, $_GET)
            : qk_read_shared_page_cache($action, $__qk_uri, $_GET);
        if ($qk_cached_page !== '') {
            if (!$qk_guest_page_cache_enabled) {
                $qk_cached_page = qk_prepare_shared_page_cache_output($qk_cached_page, $action);
            }
            while (ob_get_length() > 0) {
                ob_end_clean();
            }
            header('Content-Type: text/html; charset=utf-8');
            header('X-QK-Page-Cache: ' . ($qk_guest_page_cache_enabled ? 'HIT' : 'HIT-SHARED'));
            if ($qk_page_cache_scope !== '') {
                header('X-QK-Page-Cache-Scope: ' . $qk_page_cache_scope);
            }
            if ($qk_page_cache_scope === 'home') {
                header('X-QK-Home-Cache: ' . ($qk_guest_page_cache_enabled ? 'HIT' : 'HIT-SHARED'));
            }
            echo $qk_cached_page;
            exit;
        }
    }
}

global $siteSettings;
global $themeCss;
if ($is_frontend_page) {
    // $siteSettings 已经在上面获取过了

    function generateThemeCss($settings)
    {
        $primaryColor = isset($settings['primary_color']) ? $settings['primary_color'] : '#7c3aed';

        $hexColor = ltrim($primaryColor, '#');
        $r = hexdec(substr($hexColor, 0, 2));
        $g = hexdec(substr($hexColor, 2, 2));
        $b = hexdec(substr($hexColor, 4, 2));

        function calculateColorVariant($color, $amount)
        {
            $hex = ltrim($color, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));

            $r = max(0, min(255, $r + $amount));
            $g = max(0, min(255, $g + $amount));
            $b = max(0, min(255, $b + $amount));

            return '#' . sprintf('%02x%02x%02x', $r, $g, $b);
        }

        $primaryLight = calculateColorVariant($primaryColor, 51);
        $primaryDark = calculateColorVariant($primaryColor, -51);
        $css = "
        :root {
          --primary: {$primaryColor};
          --primary-light: {$primaryLight};
          --primary-dark: {$primaryDark};
          --primary-opacity-10: rgba({$r}, {$g}, {$b}, 0.1);
          --primary-opacity-20: rgba({$r}, {$g}, {$b}, 0.2);
          --primary-color: {$primaryColor};
        }";

        return $css;
    }

    $themeCss = generateThemeCss($siteSettings);
}

if ($is_frontend_page) {

    if ($action === 'post' && isset($_GET['id']) && is_numeric($_GET['id'])) {
        $post_id = intval($_GET['id']);
        $should_count = true;
        if (function_exists('qk_should_count_post_view')) {
            $should_count = qk_should_count_post_view($post_id, 86400);
        }
        if ($should_count) {
            execute_query($conn, "UPDATE posts SET views = views + 1 WHERE id = ?", array($post_id));
        }
    }

    // 记录用户访问文章的行为
    if ($action === 'post' && isset($_GET['id']) && is_numeric($_GET['id'])) {
        $article_id = intval($_GET['id']);
        record_article_visit($article_id);
    }

    if (file_exists('templates/tplrdr.php')) {
        include_once 'templates/tplrdr.php';

        if (function_exists('qkcms_init_tag_parser')) {
            $current_id = 0;
            if (isset($_GET['software_id']) && is_numeric($_GET['software_id'])) {
                $current_id = intval($_GET['software_id']);
            } else if (isset($_GET['category_id']) && is_numeric($_GET['category_id'])) {
                $current_id = intval($_GET['category_id']);
            } else if (isset($_GET['cid']) && is_numeric($_GET['cid'])) {
                $current_id = intval($_GET['cid']);
            } else if (isset($_GET['cat_id']) && is_numeric($_GET['cat_id'])) {
                $current_id = intval($_GET['cat_id']);
            } else if (isset($_GET['id']) && is_numeric($_GET['id'])) {
                $current_id = intval($_GET['id']);
            }

            qkcms_init_tag_parser($current_id);
        }
    }

    // 主题CSS已在renderTemplate函数中插入到<head>标签内，不再需要这里直接输出
    // 检查是否是POST请求的逻辑已整合到模板渲染流程中

    $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    $pathParts = parse_url($requestUri, PHP_URL_PATH);

    // 特殊处理404路由，确保使用已存在的404.htm页面
    if ($action === '404') {
        // 设置正确的HTTP状态码
        header('HTTP/1.1 404 Not Found');
        // 直接渲染404.htm页面
        if (file_exists('404.htm')) {
            $content = file_get_contents('404.htm');
            echo $content;
        } else {
            renderTemplate($action, true);
        }
    } else {
        renderTemplate($action, true);
    }
} else {
    // 修改路径引用，login.php现在位于admin目录下
    if ($action === 'login') {
        if (!safeInclude("admin/{$action}.php")) {
            showErrorPage(
                '页面不存在',
                '页面未找到',
                "登录页面不存在",
                ['icon' => '🔍']
            );
        }
    } else {
        if (!safeInclude("templates/{$action}.php")) {
            showErrorPage(
                '页面不存在',
                '页面未找到',
                "{$action}页面不存在",
                ['icon' => '🔍']
            );
        }
    }
}

if (isset($conn) && $conn instanceof mysqli && !$conn->connect_error) {
    close_db_connection($conn);
}

if ($qk_guest_page_cache_enabled && ob_get_length() > 0) {
    $qk_page_output = ob_get_contents();
    if ($qk_page_output !== false && $qk_page_output !== '') {
        $qk_page_output = removeApStyleFromBody($qk_page_output);
        qk_write_guest_page_cache($qk_page_output, $action, $__qk_uri, $_GET);
        ob_end_clean();
        header('X-QK-Page-Cache: MISS');
        if ($qk_page_cache_scope !== '') {
            header('X-QK-Page-Cache-Scope: ' . $qk_page_cache_scope);
        }
        if ($qk_page_cache_scope === 'home') {
            header('X-QK-Home-Cache: MISS');
        }
        echo $qk_page_output;
        exit;
    }
}

if (ob_get_length() > 0) {
    ob_end_flush();
}
