<?php
/**
* 核心函数库
*/
function get_base_url() {
    global $config;

    if (!empty($config['site']['weburl'])) {
        return rtrim($config['site']['weburl'], '/');
    }

    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domain = $_SERVER['HTTP_HOST'];

    return $protocol . $domain;
}

// 存储配置到全局变量
$GLOBALS['config'] = $config;
$GLOBALS['base_url'] = get_base_url();

// 错误报告设置 - 修改：根据配置设置错误报告
$error_config = $config['error'] ?? [];
$display_errors = $error_config['display_errors'] ?? false;
$log_errors = $error_config['log_errors'] ?? true;
$error_reporting = $error_config['error_reporting'] ?? 'E_ALL & ~E_NOTICE';

// 设置错误报告级别
switch ($error_reporting) {
    case '0':
        error_reporting(0);
        break;
    case 'E_ALL & ~E_NOTICE':
        error_reporting(E_ALL & ~E_NOTICE);
        break;
    case 'E_ALL':
        error_reporting(E_ALL);
        break;
    case 'E_ERROR | E_WARNING | E_PARSE':
        error_reporting(E_ERROR | E_WARNING | E_PARSE);
        break;
    default:
        error_reporting(E_ALL & ~E_NOTICE);
}

ini_set('display_errors', $display_errors ? '1' : '0');
ini_set('log_errors', $log_errors ? '1' : '0');
ini_set('error_log', BASE_PATH . '/logs/error.log');

// 创建必要目录
$required_dirs = [CACHE_PATH, UPLOAD_PATH, BASE_PATH . '/logs', CACHE_PATH . '/templates_c', CACHE_PATH . '/smarty_cache', INCLUDE_PATH . '/smarty_configs'];
foreach ($required_dirs as $dir) {
    if (!file_exists($dir)) {
        @mkdir($dir, 0755, true);
        @chmod($dir, 0755);
    }
}

// 安全头设置
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');

// 初始化Smarty
function init_smarty() {
    if (!class_exists('Smarty')) {
        require_once BASE_PATH . '/vendor/autoload.php';
    }

    $smarty = new Smarty\Smarty();

    // 设置Smarty目录
    $smarty->setTemplateDir(TEMPLATE_PATH);
    $compile_dir = CACHE_PATH . '/templates_c';
    $cache_dir = CACHE_PATH . '/smarty_cache';
    $config_dir = INCLUDE_PATH . '/smarty_configs';

    $smarty->setCompileDir($compile_dir);
    $smarty->setCacheDir($cache_dir);
    $smarty->setConfigDir($config_dir);

    // Smarty配置
    $smarty->setCaching(Smarty\Smarty::CACHING_OFF);
    $smarty->setCacheLifetime(120);
    $smarty->setDebugging(false);
    $smarty->setCompileCheck(true);
    $smarty->setForceCompile(false);

    // 安全设置
    $smarty->setEscapeHtml(true);

    // 注册自定义函数
    $smarty->registerPlugin('function', 'build_url', 'smarty_build_url');
    $smarty->registerPlugin('function', 'truncate', 'smarty_truncate');
    $smarty->registerPlugin('modifier', 'date_format', 'smarty_date_format');
    $smarty->registerPlugin('modifier', 'safe_html', 'smarty_safe_html');
    $smarty->registerPlugin('function', 'resource_url', 'smarty_resource_url');
    $smarty->registerPlugin('function', 'display_ad', 'smarty_display_ad');
    $smarty->registerPlugin('function', 'display_custom_data', 'smarty_display_custom_data');

    return $smarty;
}

// Smarty自定义函数
function smarty_build_url($params, $smarty) {
    return build_url($params);
}

function smarty_truncate($params, $smarty) {
    $text = $params['text'] ?? '';
    $length = $params['length'] ?? 200;
    $suffix = $params['suffix'] ?? '...';

    return truncate($text, $length, $suffix);
}

function smarty_date_format($timestamp, $format = 'Y-m-d H:i') {
    return date($format, $timestamp);
}

function smarty_safe_html($text) {
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

function smarty_resource_url($params, $smarty) {
    $path = $params['path'] ?? '';
    return resource_url($path);
}

function smarty_display_ad($params, $smarty) {
    $position = $params['position'] ?? '';
    return display_ad($position);
}

function smarty_display_custom_data($params, $smarty) {
    $position = $params['position'] ?? '';
    $page_type = $params['page_type'] ?? 'index';
    return display_custom_data_by_position($position, $page_type);
}

// 检查IP是否在允许列表中
function is_allowed_ip() {
    global $config;
    $client_ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $security_config = $config['security'] ?? [];
    $allowed_ips = $security_config['cron_allow_ips'] ?? [];

    // 如果没有设置白名单，默认允许所有IP访问
    if (empty($allowed_ips)) {
        return true;
    }

    return in_array($client_ip, $allowed_ips);
}

// 安全过滤函数
function safe_input($data) {
    if (is_array($data)) {
        return array_map('safe_input', $data);
    }
    
    $data = trim($data);
    
    // 防止SQL注入
    if (isset($GLOBALS['config']['security']['sql_injection_protection']) && $GLOBALS['config']['security']['sql_injection_protection']) {
        $data = addslashes($data);
    }
    
    // 防止XSS攻击
    if (isset($GLOBALS['config']['security']['xss_protection']) && $GLOBALS['config']['security']['xss_protection']) {
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    }
    
    return $data;
}

function safe_sql($data) {
    if (is_array($data)) {
        return array_map('safe_sql', $data);
    }
    return addslashes(trim($data));
}

// 错误处理函数 - 修改：根据配置决定是否显示和记录错误
function error_handler($errno, $errstr, $errfile, $errline) {
    global $config;

    // 检查错误是否在错误报告级别内
    if (!(error_reporting() & $errno)) {
        return false;
    }

    $error_config = $config['error'] ?? [];
    $display_errors = $error_config['display_errors'] ?? false;
    $log_errors = $error_config['log_errors'] ?? true;

    $error_types = [
        E_ERROR => 'Error',
        E_WARNING => 'Warning',
        E_PARSE => 'Parse Error',
        E_NOTICE => 'Notice',
        E_USER_ERROR => 'User Error',
        E_USER_WARNING => 'User Warning',
        E_USER_NOTICE => 'User Notice'
    ];

    $error_type = $error_types[$errno] ?? 'Unknown Error';
    $message = "$error_type: $errstr in $errfile on line $errline";

    // 记录错误日志
    if ($log_errors) {
        error_log($message);
    }

    // 显示错误信息
    if ($display_errors) {
        echo "<div style='color: red; padding: 10px; margin: 10px; border: 1px solid red;'>$message</div>";
    }

    return true;
}

function exception_handler($exception) {
    global $config;

    $error_config = $config['error'] ?? [];
    $display_errors = $error_config['display_errors'] ?? false;
    $log_errors = $error_config['log_errors'] ?? true;

    $message = "Uncaught Exception: " . $exception->getMessage() . " in " . $exception->getFile() . " on line " . $exception->getLine();

    // 记录异常日志
    if ($log_errors) {
        error_log($message);
    }

    try {
        if (function_exists('init_smarty')) {
            $smarty = init_smarty();
            $data = [
                'error_code' => 500,
                'error_message' => '服务器内部错误',
                'site_name' => $GLOBALS['config']['site']['name'] ?? '网站',
                'config' => $GLOBALS['config'] ?? []
            ];

            $smarty->assign($data);
            $smarty->display('error.tpl');
        } else {
            // 根据配置决定是否显示详细错误
            if ($display_errors) {
                echo "<h1>Error 500</h1><p>服务器内部错误</p>";
                echo "<pre>" . $exception->getMessage() . "</pre>";
            } else {
                echo "<h1>Error 500</h1><p>服务器内部错误</p>";
            }
        }
    } catch (Exception $e) {
        if ($display_errors) {
            echo "<h1>Error 500</h1><p>服务器内部错误</p>";
            echo "<pre>" . $e->getMessage() . "</pre>";
        } else {
            echo "<h1>Error 500</h1><p>服务器内部错误</p>";
        }
    }

    exit;
}

// 注册错误处理函数
set_error_handler('error_handler');
set_exception_handler('exception_handler');

/**
* 错误页面显示
*/
function display_error($code, $message = '') {
    global $config;

    $error_config = $config['error'] ?? [];
    $display_errors = $error_config['display_errors'] ?? false;

    $error_messages = [
        400 => '请求参数错误',
        401 => '未授权访问',
        403 => '禁止访问',
        404 => '页面不存在',
        500 => '服务器内部错误',
        503 => '服务暂时不可用'
    ];

    $error_message = $message ?: ($error_messages[$code] ?? '未知错误');

    http_response_code($code);

    try {
        if (function_exists('init_smarty')) {
            $smarty = init_smarty();
            $data = [
                'error_code' => $code,
                'error_message' => $error_message,
                'site_name' => $GLOBALS['config']['site']['name'] ?? '网站',
                'config' => $GLOBALS['config'] ?? []
            ];

            $smarty->assign($data);
            $smarty->display('error.tpl');
        } else {
            echo "<h1>Error $code</h1><p>$error_message</p>";
        }
    } catch (Exception $e) {
        echo "<h1>Error $code</h1><p>$error_message</p>";
    }
    exit;
}

/**
* URL处理函数 - 重构版本，完全独立生成URL
*/
function build_url($params = []) {
    $config = $GLOBALS['config'] ?? [];
    $base_url = $GLOBALS['base_url'] ?? '';
    $url_config = $config['url'] ?? [];
    $url_rules = $url_config['rules'] ?? [];
    $separator = $url_config['separator'] ?? '/';
    $suffix = $url_config['suffix'] ?? '.html';

    // 搜索功能强制使用动态URL，不再支持伪静态
    if (isset($params['mod']) && $params['mod'] === 'search') {
        $url = $base_url . '/index.php?mod=search';
        if (isset($params['keyword'])) {
            $url .= '&keyword=' . urlencode($params['keyword']);
        }
        if (isset($params['page']) && $params['page'] > 1) {
            $url .= '&page=' . $params['page'];
        }
        return $url;
    }

    // 动态URL模式
    if (!($url_config['rewrite'] ?? false)) {
        $url = $base_url . '/index.php?';
        $query_params = [];

        // 确保mod参数在最前面
        if (isset($params['mod'])) {
            $query_params[] = 'mod=' . urlencode($params['mod']);
            unset($params['mod']);
        }

        foreach ($params as $key => $value) {
            if (!empty($value) || $value === 0) {
                $query_params[] = $key . '=' . urlencode($value);
            }
        }
        return $url . implode('&', $query_params);
    }

    // 伪静态URL模式
    $mod = $params['mod'] ?? 'index';

    switch ($mod) {
        case 'index':
            if (isset($params['page']) && $params['page'] > 1) {
                return $base_url . $separator . ($url_rules['page'] ?? 'page') . $separator . $params['page'] . $suffix;
            } else {
                return $base_url . $separator . 'index' . $suffix;
            }
            break;

        case 'category':
            $cate_id = $params['cate'] ?? 0;
            if ($cate_id <= 0) {
                return build_url(['mod' => 'index']);
            }

            // 获取分类别名
            $category = get_category($cate_id);

            if (isset($params['page']) && $params['page'] > 1) {
                return $base_url . $separator . ($url_rules['category'] ?? 'category') . $separator . $cate_id . $separator . ($url_rules['page'] ?? 'page') . $separator . $params['page'] . $suffix;
            } else {
                return $base_url . $separator . ($url_rules['category'] ?? 'category') . $separator . $cate_id . $suffix;
            }
            break;

        case 'post':
            $post_id = $params['id'] ?? 0;
            if ($post_id <= 0) {
                return build_url(['mod' => 'index']);
            }
            return $base_url . $separator . ($url_rules['post'] ?? 'post') . $separator . $post_id . $suffix;
            break;

        case 'author':
            $author_id = $params['author'] ?? 0;
            if ($author_id <= 0) {
                return build_url(['mod' => 'index']);
            }

            if (isset($params['page']) && $params['page'] > 1) {
                return $base_url . $separator . ($url_rules['author'] ?? 'author') . $separator . $author_id . $separator . ($url_rules['page'] ?? 'page') . $separator . $params['page'] . $suffix;
            } else {
                return $base_url . $separator . ($url_rules['author'] ?? 'author') . $separator . $author_id . $suffix;
            }
            break;

        case 'update_cache':
            return $base_url . $separator . 'update-cache';
            break;

        default:
            return build_url(['mod' => 'index']);
    }
}

/**
* 伪静态URL解析 - 修复版本
*/
function parse_rewrite_url() {
    $config = $GLOBALS['config'] ?? [];

    // 如果是动态URL模式，直接返回
    if (!($config['url']['rewrite'] ?? false)) {
        return;
    }

    $request_uri = $_SERVER['REQUEST_URI'];

    // 移除查询字符串
    $path = parse_url($request_uri, PHP_URL_PATH);
    $path = trim($path, '/');

    // 处理特殊路由
    if ($path === 'update-cache') {
        $_GET['mod'] = 'update_cache';
        return;
    }

    // 处理首页
    if ($path === '' || $path === 'index' . ($config['url']['suffix'] ?? '.html')) {
        $_GET['mod'] = 'index';
        return;
    }

    $url_config = $config['url'] ?? [];
    $url_rules = $url_config['rules'] ?? [];
    $separator = $url_config['separator'] ?? '/';
    $suffix = $url_config['suffix'] ?? '.html';

    // 处理分页首页
    if (preg_match('/^' . ($url_rules['page'] ?? 'page') . '\/(\d+)' . preg_quote($suffix) . '$/', $path, $matches)) {
        $_GET['mod'] = 'index';
        $_GET['page'] = intval($matches[1]);
        return;
    }

    // 处理分类页面 - 支持别名和ID
    $category_pattern = '/^' . ($url_rules['category'] ?? 'category') . '\/([^\/]+)' . preg_quote($suffix) . '$/';
    if (preg_match($category_pattern, $path, $matches)) {
        $category_part = $matches[1] ?? '';
        if (!empty($category_part)) {
            // 检查是否是数字ID
            if (is_numeric($category_part)) {
                $_GET['mod'] = 'category';
                $_GET['cate'] = intval($category_part);
            } else {
                // 通过别名查找分类
                $_GET['mod'] = 'category';
                $_GET['alias'] = $category_part;
            }
            return;
        }
    }

    // 处理分类分页
    $category_page_pattern = '/^' . ($url_rules['category'] ?? 'category') . '\/([^\/]+)\/' . ($url_rules['page'] ?? 'page') . '\/(\d+)' . preg_quote($suffix) . '$/';
    if (preg_match($category_page_pattern, $path, $matches)) {
        $category_part = $matches[1] ?? '';
        $page_num = $matches[2] ?? 1;
        if (!empty($category_part)) {
            if (is_numeric($category_part)) {
                $_GET['mod'] = 'category';
                $_GET['cate'] = intval($category_part);
                $_GET['page'] = intval($page_num);
            } else {
                $_GET['mod'] = 'category';
                $_GET['alias'] = $category_part;
                $_GET['page'] = intval($page_num);
            }
            return;
        }
    }

    // 处理文章页面
    $post_pattern = '/^' . ($url_rules['post'] ?? 'post') . '\/(\d+)' . preg_quote($suffix) . '$/';
    if (preg_match($post_pattern, $path, $matches)) {
        $_GET['mod'] = 'post';
        $_GET['id'] = intval($matches[1]);
        return;
    }

    // 处理作者页面
    $author_pattern = '/^' . ($url_rules['author'] ?? 'author') . '\/(\d+)' . preg_quote($suffix) . '$/';
    if (preg_match($author_pattern, $path, $matches)) {
        $_GET['mod'] = 'author';
        $_GET['author'] = intval($matches[1]);
        return;
    }

    // 处理作者分页
    $author_page_pattern = '/^' . ($url_rules['author'] ?? 'author') . '\/(\d+)\/' . ($url_rules['page'] ?? 'page') . '\/(\d+)' . preg_quote($suffix) . '$/';
    if (preg_match($author_page_pattern, $path, $matches)) {
        $_GET['mod'] = 'author';
        $_GET['author'] = intval($matches[1]);
        $_GET['page'] = intval($matches[2]);
        return;
    }
    // 如果没有匹配任何规则，让通用规则处理
    // 不要在这里显示404，让程序处理
}

/**
* 文本处理函数
*/
function truncate($text, $length = 200, $suffix = '...') {
    $text = strip_tags($text);

    if (mb_strlen($text, 'UTF-8') > $length) {
        $text = mb_substr($text, 0, $length, 'UTF-8') . $suffix;
    }
    return $text;
}

/**
* 数据获取函数
*/
function get_category($cate_id) {
    $categories = get_categories();
    if ($categories['code'] == 200 && isset($categories['data']['categories'])) {
        foreach ($categories['data']['categories'] as $category) {
            if ($category['id'] == $cate_id) {
                return $category;
            }
        }
    }
    return null;
}

function get_category_by_alias($alias) {
    $categories = get_categories();
    if ($categories['code'] == 200 && isset($categories['data']['categories'])) {
        foreach ($categories['data']['categories'] as $category) {
            if (($category['alias'] ?? '') == $alias) {
                return $category;
            }
        }
    }
    return null;
}

/**
* 数据处理函数 - 修复版本
*/
function process_posts_for_template($posts) {
    if (!is_array($posts)) {
        return [];
    }

    foreach ($posts as &$post) {
        if (!empty($post['tags'])) {
            $post['tags_array'] = array_filter(array_map('trim', explode(',', $post['tags'])));
        } else {
            $post['tags_array'] = [];
        }

        $post['create_time_formatted'] = date('Y-m-d H:i', $post['create_time']);
        if ($post['update_time'] != $post['create_time']) {
            $post['update_time_formatted'] = date('Y-m-d H:i', $post['update_time']);
        }

        // 修复：列表页内容去除HTML标签
        if (isset($post['content'])) {
            $post['content'] = strip_tags($post['content']);
        }
    }
    return $posts;
}

/**
* 预处理分页数据 - 优化：使用配置控制显示的页码数量
*/
function preprocess_pagination(&$pagination) {
    if ($pagination && is_array($pagination)) {
        $pagination['page_prev'] = $pagination['page'] - 1;
        $pagination['page_next'] = $pagination['page'] + 1;

        // 获取配置中的分页显示数量
        $display_config = $GLOBALS['config']['display'] ?? [];
        $list_pagination_count = $display_config['pagination_pages_count'] ?? 5;
        $current_page = $pagination['page'];
        $total_pages = $pagination['total_pages'];
        $display_pages = [];

        if ($total_pages <= $list_pagination_count) {
            // 如果总页数小于等于配置数量，显示所有页码
            for ($i = 1; $i <= $total_pages; $i++) {
                $display_pages[] = $i;
            }
        } else {
            // 如果总页数大于配置数量，显示当前页前后的页码
            $half = floor($list_pagination_count / 2);
            $start_page = max(1, $current_page - $half);
            $end_page = min($total_pages, $current_page + $half);

            // 确保显示指定数量的页码
            if ($end_page - $start_page < $list_pagination_count - 1) {
                if ($start_page == 1) {
                    $end_page = min($total_pages, $start_page + $list_pagination_count - 1);
                } else {
                    $start_page = max(1, $end_page - $list_pagination_count + 1);
                }
            }

            for ($i = $start_page; $i <= $end_page; $i++) {
                $display_pages[] = $i;
            }
        }

        $pagination['display_pages'] = $display_pages;
    }
}

/**
* 获取公用数据（用于所有页面） - 修复版本
*/
function get_common_data() {
    $data = [];

    // 获取分类数据
    $categories_result = safe_api_call('get_categories', [], ['categories' => []]);
    $data['all_categories'] = $categories_result['categories'] ?? [];

    // 获取文章总数
    $total_result = safe_api_call('get_total_posts', [], ['total_posts' => 0]);
    $data['total_posts'] = $total_result['total_posts'] ?? 0;

    // 获取显示设置
    $display_config = $GLOBALS['config']['display'] ?? [];
    $hot_posts_count = $display_config['hot_posts_count'] ?? 5;
    $hot_posts_days = $display_config['hot_posts_days'] ?? 7;
    $random_posts_count = $display_config['random_posts_count'] ?? 5;
    $announcements_count = $display_config['announcements_count'] ?? 5;

    // 修复：正确处理热门文章数据结构 - 确保全局可用，应用时间范围设置
    $hot_result = get_hotlists(1, $hot_posts_count, 0, $hot_posts_days);
    if ($hot_result['code'] == 200) {
        $data['hot_posts'] = process_posts_for_template($hot_result['data'] ?? []);
    } else {
        $data['hot_posts'] = [];
    }

    // 修复：正确处理随机文章数据结构 - 确保全局可用，应用数量设置
    $random_result = get_randomlists(1, $random_posts_count);
    if ($random_result['code'] == 200) {
        $data['random_posts'] = process_posts_for_template($random_result['data'] ?? []);
    } else {
        $data['random_posts'] = [];
    }

    // 获取友情链接
    $data['friend_links'] = $GLOBALS['config']['friend_links'] ?? [];

    // 获取网站公告 - 应用数量设置
    $announcements = $GLOBALS['config']['announcements'] ?? [];
    $data['announcements'] = array_slice($announcements, 0, $announcements_count);

    return $data;
}

/**
* 获取指定文章ID列表
*/
function get_specific_posts($post_ids, $limit = 10) {
    if (empty($post_ids)) {
        return [];
    }

    $posts = [];
    $id_array = array_map('intval', explode(',', $post_ids));
    $id_array = array_slice($id_array, 0, $limit);

    foreach ($id_array as $post_id) {
        if ($post_id > 0) {
            $result = get_post($post_id);
            if ($result['code'] == 200 && isset($result['data'])) {
                $posts[] = $result['data'];
            }
        }
    }

    return process_posts_for_template($posts);
}

/**
* 获取自定义数据
*/
function get_custom_data($page_type = 'index') {
    global $config;
    $custom_data = [];

    if (isset($config['custom_data']) && is_array($config['custom_data'])) {
        foreach ($config['custom_data'] as $var_name => $data_config) {
            // 检查是否在当前页面显示
            if (in_array('all', $data_config['pages']) || in_array($page_type, $data_config['pages'])) {
                $data = [];

                switch ($data_config['data_type']) {
                    case 'posts':
                        $result = get_lists(1, $data_config['data_count'], 0, $data_config['order']);
                        if ($result['code'] == 200) {
                            $data = process_posts_for_template($result['data']);
                        }
                        break;

                    case 'hot_posts':
                        $result = get_hotlists(1, $data_config['data_count']);
                        if ($result['code'] == 200) {
                            $data = process_posts_for_template($result['data']);
                        }
                        break;

                    case 'random_posts':
                        $result = get_randomlists(1, $data_config['data_count']);
                        if ($result['code'] == 200) {
                            $data = process_posts_for_template($result['data']);
                        }
                        break;

                    case 'specific_posts':
                        if (isset($data_config['post_ids'])) {
                            $data = get_specific_posts($data_config['post_ids'], $data_config['data_count']);
                        }
                        break;

                    case 'categories':
                        $result = get_categories();
                        if ($result['code'] == 200 && isset($result['data']['categories'])) {
                            $data = array_slice($result['data']['categories'], 0, $data_config['data_count']);
                        }
                        break;
                }

                $custom_data[$var_name] = [
                    'data' => $data,
                    'config' => $data_config
                ];
            }
        }
    }

    return $custom_data;
}

/**
* 按位置获取自定义数据
*/
function get_custom_data_by_position($position, $page_type = 'index') {
    $all_custom_data = get_custom_data($page_type);
    $position_data = [];

    foreach ($all_custom_data as $var_name => $item) {
        if (($item['config']['position'] ?? 'sidebar') === $position) {
            $position_data[$var_name] = $item;
        }
    }

    return $position_data;
}

/**
* 显示指定位置的自定义数据
*/
function display_custom_data_by_position($position, $page_type = 'index') {
    $custom_data = get_custom_data_by_position($position, $page_type);
    $output = '';

    if (!empty($custom_data)) {
        foreach ($custom_data as $var_name => $item) {
            $data = $item['data'];
            $config = $item['config'];

            if (!empty($data)) {
                $output .= '<div class="custom-data-widget custom-data-' . $var_name . '">';
                $output .= '<div class="widget-title">' . htmlspecialchars($config['name']) . '</div>';
                $output .= '<div class="widget-content">';

                if ($config['data_type'] === 'categories') {
                    $output .= '<ul class="category-list">';
                    foreach ($data as $category) {
                        $output .= '<li class="category-item">';
                        $output .= '<a href="' . build_url(['mod' => 'category', 'cate' => $category['id']]) . '">';
                        $output .= htmlspecialchars($category['name']);
                        $output .= '<span class="category-count">' . ($category['count'] ?? 0) . '</span>';
                        $output .= '</a></li>';
                    }
                    $output .= '</ul>';
                } else {
                    $output .= '<div class="post-list">';
                    foreach ($data as $post) {
                        $output .= '<div class="post-item">';
                        $output .= '<a href="' . build_url(['mod' => 'post', 'id' => $post['id']]) . '" class="post-link">';
                        $output .= '<h5>' . htmlspecialchars($post['title']) . '</h5>';
                        $output .= '<div class="post-meta">';
                        $output .= '<span>' . ($post['create_time_formatted'] ?? '') . '</span>';
                        $output .= '<span>' . ($post['views'] ?? 0) . ' 阅读</span>';
                        $output .= '</div>';
                        $output .= '</a>';
                        $output .= '</div>';
                    }
                    $output .= '</div>';
                }

                $output .= '</div></div>';
            }
        }
    }

    return $output;
}

/**
* 获取限制数量的分类（仅用于导航栏）
*/
function get_limited_categories($limit = 10) {
    $categories = get_categories();
    if ($categories['code'] == 200 && isset($categories['data']['categories'])) {
        return array_slice($categories['data']['categories'], 0, $limit);
    }
    return [];
}

/**
* 获取所有分类（用于侧边栏等）
*/
function get_all_categories() {
    $categories = get_categories();
    if ($categories['code'] == 200 && isset($categories['data']['categories'])) {
        return $categories['data']['categories'];
    }
    return [];
}

/**
* 安全检查函数
*/
function check_csrf_token() {
    $config = $GLOBALS['config'] ?? [];
    $security_config = $config['security'] ?? [];
    
    if (($security_config['csrf_protection'] ?? false) && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $token = $_POST['csrf_token'] ?? '';
        if (!$token || $token !== ($_SESSION['csrf_token'] ?? '')) {
            display_error(403, 'CSRF令牌验证失败');
        }
    }
}

function generate_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
* 性能优化函数
*/
function gzip_compress($content) {
    $config = $GLOBALS['config'] ?? [];
    $performance_config = $config['performance'] ?? [];
    
    if (($performance_config['gzip_compression'] ?? false) && !headers_sent()) {
        if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
            header('Content-Encoding: gzip');
            return gzencode($content, 9);
        }
    }
    return $content;
}

function set_browser_cache() {
    $config = $GLOBALS['config'] ?? [];
    $performance_config = $config['performance'] ?? [];
    
    if (($performance_config['browser_caching'] ?? false) && !headers_sent()) {
        header('Cache-Control: public, max-age=3600');
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
    }
}

/**
* 安全的API数据获取
*/
function safe_api_call($callback, $params = [], $default = []) {
    try {
        if (is_string($callback) && function_exists($callback)) {
            $result = call_user_func_array($callback, $params);
        } else {
            $result = $callback();
        }

        if ($result['code'] == 200 && isset($result['data'])) {
            return $result['data'];
        }
    } catch (Exception $e) {
        error_log("API call failed: " . $e->getMessage());
    }
    return $default;
}

/**
* 资源URL生成
*/
function resource_url($path) {
    global $base_url;
    $path = ltrim($path, '/');
    return $base_url . '/' . $path;
}

/**
* 广告显示函数 - 修改：不转义HTML内容
*/
function display_ad($position) {
    global $config;
    $ads = $config['ads'] ?? [];

    if (!$ads['enabled']) {
        return '';
    }

    if (isset($ads[$position]) && $ads[$position]['enabled']) {
        return $ads[$position]['content']; // 直接返回HTML内容，不转义
    }

    return '';
}

/**
* 缓存锁机制 - 防止缓存雪崩
*/
function cache_lock($key, $timeout = 10) {
    $lock_key = $key . '_lock';
    $lock_time = $GLOBALS['cache']->get($lock_key);

    if ($lock_time && (time() - $lock_time < $timeout)) {
        return false; // 已被锁定
    }

    $GLOBALS['cache']->set($lock_key, time());
    return true;
}

function cache_unlock($key) {
    $lock_key = $key . '_lock';
    $GLOBALS['cache']->delete($lock_key);
}
?>