<?php

namespace core_next;

class WordPress
{
    static function loadJS($name, $file_name, $local = true, $need = [], $footer = false)
    {
        if ($local === true) {
            $file_path = Config::$js_url . "/$file_name";
        } else {
            $file_path = $file_name;
        }
        wp_enqueue_script($name, $file_path, $need, Config::$theme_version, $footer);
    }

    static function loadCss($name, $file_name, $local = true)
    {
        if ($local === true) {
            $file_path = Config::$css_url . "/$file_name";
        } else {
            $file_path = $file_name;
        }
        wp_enqueue_style($name, $file_path, [], Config::$theme_version);
    }

    static function loadElementUI()
    {
        global $core_next_set;
        $cdn_name = $core_next_set['theme_cdn'];
        if ($cdn_name === 'bytedance') {
            $js_url = 'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-y/element-ui/2.15.7/index.min.js';
            $css_url = 'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/element-ui/2.15.7/theme-chalk/index.min.css';
        } elseif ($cdn_name === 'qiniu') {
            $js_url = 'https://cdn.staticfile.org/element-ui/2.15.12/index.min.js';
            $css_url = 'https://cdn.staticfile.org/element-ui/2.15.12/theme-chalk/index.min.css';
        } else {
            $js_url = 'https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/index.min.js';
            $css_url = 'https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/theme-chalk/index.min.css';
        }
        wp_enqueue_script('element-ui', $js_url, [], Config::$theme_version);
        wp_enqueue_style('element-ui', $css_url, [], Config::$theme_version);
    }

    static function loadHighlight($style = 'light')
    {
        wp_enqueue_script('highlight', Config::$lib_url . "/highlight/highlight.min.js", [], Config::$theme_version);
        if ($style === 'light') {

            wp_enqueue_style('highlight', Config::$lib_url . "/highlight/style/corepress.css", [], Config::$theme_version);
        } else {
            wp_enqueue_style('highlight', Config::$lib_url . "/highlight/style/corepress-dark.css", [], Config::$theme_version);
        }
    }

    static function loadStrawberryIcon()
    {
        wp_enqueue_style('strawberry', Config::$static_url . '/lib/strawberry/style.css', [], Config::$theme_version);
    }

    static function loadJQuery()
    {
        global $core_next_set;
        $cdn_name = $core_next_set['theme_cdn'];
        if ($cdn_name === 'bytedance') {
            $js_url = 'https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-y/jquery/3.6.0/jquery.min.js';

        } elseif ($cdn_name === 'qiniu') {
            $js_url = 'https://cdn.staticfile.org/jquery/3.7.0/jquery.min.js';
        } else {
            $js_url = 'https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js';
        }
        wp_enqueue_script('core-next-jquery', $js_url, [], Config::$theme_version);
    }

    static function loadVue($ver = 2)
    {
        global $core_next_set;
        $cdn_name = $core_next_set['theme_cdn'];
        if ($cdn_name === 'bytedance') {
            $js_url = 'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/vue/2.6.14/vue.min.js';

        } elseif ($cdn_name === 'qiniu') {
            $js_url = 'https://cdn.staticfile.org/vue/2.7.0/vue.min.js';

        } else {
            $js_url = 'https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.min.js';
        }
        wp_enqueue_script('vue2', $js_url, [], Config::$theme_version);
    }

    static function loadVueRouter($ver = 3)
    {
        global $core_next_set;
        $cdn_name = $core_next_set['theme_cdn'];
        if ($cdn_name === 'bytedance') {
            $js_url = 'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/vue-router/3.5.3/vue-router.min.js';

        } elseif ($cdn_name === 'qiniu') {
            $js_url = 'https://cdn.staticfile.net/vue-router/3.5.3/vue-router.min.js';

        } else {
            $js_url = 'https://cdn.bootcdn.net/ajax/libs/vue-router/3.5.3/vue-router.min.js';
        }
        wp_enqueue_script('vue-router3', $js_url, [], Config::$theme_version);
    }

    static function isAdmin()
    {
        global $current_user;
        if ($current_user->ID == 0) {
            return false;
        }

        if (current_user_can('manage_options')) {
            return true;
        }

        return false;
    }

    static function isLogin()
    {
        global $current_user;
        if ($current_user->ID == 0) {
            return false;
        }
        return true;
    }

    static function getLoopPostList()
    {
        $post_list = [];

        while (have_posts()) {
            the_post();
            $post = get_post();
            $post_list[] = self::getPostMetaData($post, false);
        }

        return self::handelPostList($post_list);
    }

    static function handelPostList($post_list)
    {

        global $core_next_set;
        foreach ($post_list as &$item) {
            if ($core_next_set['post_list_url_new_window']) {
                $item['target'] = '_blank';
            } else {
                $item['target'] = '_self';
            }

            if ($core_next_set['loading_open']) {
                if ($core_next_set['loading_img'] !== 'custom') {
                    $loading_img = 'data:image/svg+xml;base64,' . base64_encode(file_get_contents(Config::$theme_dir . "/static/img/loading/" . $core_next_set['loading_img']));
                } else {
                    $loading_img = $core_next_set['loading_img_url'];
                }
                $item['loading_img'] = $loading_img;
                $item['hide_note_loading_img'] = 'true';
            } else {
                $item['hide_loading_img'] = 'true';
            }

            if ($core_next_set['close_thumbnail']) {
                $item['hide_thumbnail'] = 'true';
            }
        }
        return $post_list;
    }

    static function getPostList($paged = 1, $cat_id = 0)
    {
        $post_list = [];
        $per_page = get_option('posts_per_page');
        $sticky = get_option('sticky_posts');
        global $core_next_set;
        if ($paged === 1 && $cat_id === 0) {
            if (count($sticky) > 0) {
                $args = [
                    'post__in' => $sticky,
                    'post_type' => 'post',
                    'post_status' => array('publish'),
                ];
                $query = new \WP_Query($args);
                self::postQueryToList($query, $post_list);
            }
        }

        $args = array(
            'posts_per_page' => $per_page,
            'cat' => $cat_id,
            'paged' => $paged,
            'post_type' => 'post',
            'post_status' => array('publish'),
            'post__not_in' => $sticky,
            'category__not_in' => $core_next_set['home_post_exclude_id']
        );
        $query = new \WP_Query($args);
        self::postQueryToList($query, $post_list);
        return self::handelPostList($post_list);
    }

    static private function postQueryToList($query, &$post_list)
    {
        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $post = get_post();
                $post_list[] = self::getPostMetaData($post);
            }
        }
        wp_reset_postdata();
    }

    static function getPostMetaData($post, $show_sticky = true, $need = 'all')
    {
        if ($need === 'all') {
            $data['title'] = $post->post_title;
            $data['post_excerpt'] = self::getPostExcerpt($post);
            $data['url'] = get_the_permalink($post);
            $data['date'] = get_the_date('Y-m-d', $post);
            date_default_timezone_set('Asia/Shanghai');
            $current_date = date('Y-m-d');
            if ($data['date'] !== $current_date) {
                $data['hide_new'] = 'true';
            }
            $data['thumbnail'] = self::getThumbnail($post);
            $category_array = get_the_category($post->ID);
            $data['cat_name'] = '';

            $stickies = get_option('sticky_posts');
            $data['sticky_html'] = '';
            $data['hide_sticky'] = 'true';
            if (is_array($stickies) && $show_sticky === true) {
                $stickies = array_map('intval', $stickies);
                $is_sticky = in_array($post->ID, $stickies, true);
                if ($is_sticky) {
                    $data['hide_sticky'] = 'false';
                }
            }

            $data['views'] = '';
            if (function_exists('the_views')) {
                $data['views'] = Tools::viewsConvert(intval(get_post_meta($post->ID, 'views', true)));
            }

            foreach ($category_array as $item) {
                $data['cat_name'] = $item->name;
                $data['cat_url'] = get_category_link($item);
                break;
            }
            $author_id = get_post_field('post_author', $post);
            $author_name = get_the_author_meta('display_name', $author_id);
            $data['author_name'] = $author_name;
            $data['comment_number'] = get_comments_number($post);
            $data['post_like'] = (int)get_post_meta($post->ID, 'cp_like', true);


        } else {
            $data['title'] = $post->post_title;
            $data['url'] = get_the_permalink($post);
            $data['date'] = get_the_date('Y-m-d', $post);
            if (in_array('post_excerpt', $need)) {
                $data['post_excerpt'] = self::getPostExcerpt($post);
            }
            if (in_array('thumbnail', $need)) {
                $data['thumbnail'] = self::getThumbnail($post);
            }
            if (in_array('views', $need)) {
                if (function_exists('the_views')) {
                    $data['views'] = Tools::viewsConvert(intval(get_post_meta($post->ID, 'views', true)));
                }
            }
        }

        return $data;
    }

    static function getWidgetPostMetaData($post)
    {
        $data['title'] = $post->post_title;
        $data['url'] = get_the_permalink($post);
        $data['thumbnail'] = self::getThumbnail($post);
        $category_array = get_the_category($post->ID);
        foreach ($category_array as $item) {
            $data['cat_name'] = $item->name;
            $data['cat_url'] = get_category_link($item);
            break;
        }
        return $data;
    }

    static function getThumbnail($post)
    {
        global $core_next_set;
        $thumbnail = $core_next_set['default_thumbnail'];
        //设置URL地址为最高优先级
        $meta_box = Options::getPostMetaBoxOptions($post->ID);
        if ($meta_box['custom_thumbnail'] !== '') {
            return Theme::handleRandomThumbnailOne($meta_box['custom_thumbnail']);
        }
        if (has_post_thumbnail($post)) {
            $set_thumbnail = get_the_post_thumbnail_url($post, 'full');
            if ($set_thumbnail !== false) {
                return Theme::handleRandomThumbnailOne($set_thumbnail);
            }
        }
        $preg = '/<img[^>]+src="([^"]+)"/i';
        preg_match($preg, $post->post_content, $imgArr);
        if (count($imgArr) != 0) {
            $thumbnail = $imgArr[1];
            return Theme::handleRandomThumbnailOne($thumbnail);
        }
        return Theme::handleRandomThumbnailOne($thumbnail);
    }

    static function getPostExcerpt($post)
    {
        global $core_next_set;
        if ($core_next_set['post_excerpt_len'] == 0) {
            return '';
        }
        $len = $core_next_set['post_excerpt_len'];
        $post_excerpt = $post->post_excerpt;
        if (strlen($post_excerpt) == 0) {
            $content = $post->post_content;
            $re_text = mb_strimwidth(strip_tags(apply_filters('the_content', $content)), 0, $len, "……");
            if (has_shortcode($content, 'pwdshow')) {
                $re_text = '内容已加密';
            }
            if (post_password_required($post)) {
                $re_text = '内容已加密，请输入密码以后查看';
            }
        } else {
            $re_text = $post_excerpt;
        }
        return $re_text;
    }

    static function handleExcerpt($post)
    {
        global $set;
        $postitem['post_meta'] = json_decode(get_post_meta($post->ID, 'corepress_post_meta', true), true);
        if ($postitem['post_meta']['closesummary'] == 1) {
            $postitem['content'] == '';
        } else {
            if (has_excerpt($post)) {
                $postitem['content'] = get_the_excerpt($post);
                if (strlen(preg_replace("/[\s]{2,}/", "", $postitem['content'])) == 0) {
                    $postitem['content'] = mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, $set['routine']['summary_lenth'], "……");
                }
            } else {
                $postitem['content'] = mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, $set['routine']['summary_lenth'], "……");
            }
        }

        if (has_shortcode($postitem['content'], 'pwdshow')) {
            $postitem['content'] = '内容已加密';
        }
        if (post_password_required()) {
            $postitem['content'] = '内容已加密，请输入密码以后查看';
        }

        return $postitem['content'];
    }


    static function getSideBarHtml($name)
    {
        ob_start(); // 开始输出缓存
        dynamic_sidebar($name); // 显示小工具
        return ob_get_clean(); // 将小工具存入变量$sidebar中
    }

    static function hasMenu($menu_name)
    {
        $locations = get_nav_menu_locations();
        if (!isset($locations[$menu_name])) {
            return false;
        }
        $menu = wp_get_nav_menu_object($locations[$menu_name]);
        return $menu !== false;
    }

    static function getMenuArray($menu_name)
    {
        $locations = get_nav_menu_locations();
        $menu = wp_get_nav_menu_object($locations[$menu_name]);
        $menu_list = wp_get_nav_menu_items($menu->term_id);
        $menu = [];
        if (!is_array($menu_list)) {
            return [];
        }
        foreach ($menu_list as $menu_item) {
            $_item['id'] = $menu_item->ID;
            $_item['title'] = $menu_item->title;
            $_item['url'] = $menu_item->url;
            $_item['parent_id'] = (int)$menu_item->menu_item_parent;
            $menu[] = $_item;
        }
        return $menu;
    }

    static function menuArrayToHtml($menu_name)
    {
        $menu_array = self::getMenuArray($menu_name);
        $html_str = '';
        foreach ($menu_array as $item) {
            if ($item['parent_id'] === 0) {
                $html_str .= '<div><a href="' . $item['url'] . '" target="_blank">' . $item['title'] . '</a></div>';
            }
        }
        return $html_str;
    }

    function getBreadcrumb()
    {
        echo '<span class="corepress-crumbs-ul">';
        if (!is_home()) {
            echo '<li><a href="';
            echo get_option('home');
            echo '">';
            echo '<i class="fas fa-home"></i> 主页';
            echo "</a></li>";
            if (is_category() || is_single()) {
                echo '<li>';
                the_category(' </li><li> ');
                if (is_single()) {
                    echo "</li>";
                }
            } elseif (is_page()) {
                echo '<li>';
                echo the_title();
                echo '</li>';
            }
        } elseif (is_tag()) {
            single_tag_title();
        } elseif (is_day()) {
            echo "<li>Archive for ";
            the_time('F jS, Y');
            echo '</li>';
        } elseif (is_month()) {
            echo "<li>Archive for ";
            the_time('F, Y');
            echo '</li>';
        } elseif (is_year()) {
            echo "<li>Archive for ";
            the_time('Y');
            echo '</li>';
        } elseif (is_author()) {
            echo "<li>Author Archive";
            echo '</li>';
        } elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {
            echo "<li>Blog Archives";
            echo '</li>';
        } elseif (is_search()) {
            echo "<li>Search Results";
            echo '</li>';
        }
        echo '</span>';
    }

    static function getCrumbsList()
    {
        $list = [];
        //home
        $item['name'] = '主页';
        $item['url'] = get_home_url();
        $list[] = $item;
        //二级
        $category_array = get_the_category();
        foreach ($category_array as $_item) {
            $item['name'] = $_item->name;
            $item['url'] = get_category_link($_item);
            break;
        }
        $list[] = $item;
        return $list;
    }

    static function getCommentsList($post_id, $page = 1, $comments_per_page = 10, $mail = '')
    {
        if (!is_numeric($post_id) || !is_numeric($page)) {
            return '参数错误';
        }
        // 设置评论参数

        // 获取所有评论
        $all_comments = get_comments(
            [
                'post_id' => $post_id,
                'status' => 'approve',
            ]
        );
        //获取顶级评论
        $top_comments = [];
        foreach ($all_comments as $comment) {
            if ($comment->comment_parent == 0) {
                $top_comments[] = $comment;
            }
        }
        //分页
        $start_number = ($page - 1) * $comments_per_page;
        $i = 0;
        $need_top_comments = [];
        foreach ($top_comments as $comment) {
            if ($i >= $start_number && $i < $start_number + $comments_per_page) {
                $need_top_comments[] = self::getCommentMeta($comment);
            }
            $i++;
        }
        foreach ($need_top_comments as &$comment) {
            $children = self::handleCommentList($all_comments, $comment['id']);
            $comment['children'] = $children;
        }


        $data['list'] = $need_top_comments;
        $data['page_count'] = ceil(count($top_comments) / $comments_per_page);


        if ($mail !== '') {
            //获取当前用户未审核评论
            $user_comments = get_comments(
                [
                    'post_id' => $post_id,
                    'status' => 'hold'
                ]
            );
            foreach ($user_comments as $_comment) {
                if ($_comment->comment_author_email == $mail) {
                    $item_comment = self::getCommentMeta($_comment);
                    $item_comment['content'] = '<b>您的评论审核中</b>(如果您是回复的评论，也展示在评论顶部。审核后会出现在正确的位置)';
                    array_unshift($data['list'], $item_comment);
                }
            }
        }
        return $data;
    }

    static private function handleCommentList($all_comment, $comment_id)
    {
        $list = [];
        foreach ($all_comment as $comment) {
            if ($comment->comment_parent == $comment_id) {
                $list[] = self::getCommentMeta($comment);
                $list = array_merge($list, self::handleCommentList($all_comment, $comment->comment_ID));
            }
        }
        return $list;
    }


    static function getCommentMeta($comment, $need_ua = true)
    {
        global $core_next_set;
        $_item['id'] = $comment->comment_ID;
        $_item['author'] = $comment->comment_author;
        $_item['content'] = apply_filters('comment_text', $comment->comment_content);
        if ($core_next_set['open_ua_parser'] && $need_ua === true) {
            $_item['content'] = '<div class="core-next-ua">' . $comment->comment_agent . '</div>' . $_item['content'];
        }
        $_item['date'] = $comment->comment_date;
        $_item['avatar'] = Theme::getUserAvatar($comment->comment_author_email);
        $_item['admin'] = 0;
        $user_id = $comment->user_id;
        $mail = $comment->comment_author_email;
        if ($user_id != 0) {
            if (user_can($user_id, 'administrator')) {
                $_item['admin'] = 1;
            }
            $_item['author_url'] = get_author_posts_url($user_id);
        } else {
            $_item['author_url'] = '';
        }
        $_item['mail'] = $mail;
        $_item['ip_data'] = [];
        if ($core_next_set['comment_location_open'] && $core_next_set['comment_location_show']) {
            $ip_info = get_comment_meta($_item['id'], 'core_ip_place', true);
            if (!empty($ip_info)) {
                if (in_array('国家', $core_next_set['comment_location_show_type'])) {
                    $_item['ip_data']['country'] = $ip_info['country'];
                }
                if (in_array('省份', $core_next_set['comment_location_show_type'])) {
                    $_item['ip_data']['province'] = $ip_info['province'];
                }
                if (in_array('城市', $core_next_set['comment_location_show_type'])) {
                    $_item['ip_data']['city'] = $ip_info['city'];
                }
                if (in_array('运营商', $core_next_set['comment_location_show_type'])) {
                    $_item['ip_data']['operator'] = $ip_info['operator'];
                }
            }
        }
        if ($core_next_set['open_user_website_url']) {
            if ($user_id != 0) {
                $_item['website_url'] = get_user_meta($user_id, 'author_url', true);
            } else {
                $_item['website_url'] = $comment->comment_author_url;
            }
        }
        return $_item;
    }

    static function getCatList()
    {
        $categories = get_categories();
        $cat_list = [];
        foreach ($categories as $category) {
            $_data['name'] = $category->name;
            $_data['id'] = $category->term_id;
            $_data['count'] = $category->count;
            $cat_list[] = $_data;
        }
        return $cat_list;
    }

    static function getCatInfoList($ids = [])
    {
        $cat_list = self::getCatList();
        $list = [];
        foreach ($ids as $item) {
            foreach ($cat_list as $cat_info_item) {
                if ($cat_info_item['id'] === $item) {
                    $cat_info_item['paged'] = 0;
                    $list[] = $cat_info_item;
                    break;
                }
            }
        }
        return $list;
    }

    static function getShortcodeCount($shortcode, $post_content)
    {
        $pattern = get_shortcode_regex(array($shortcode));
        preg_match_all('/' . $pattern . '/', $post_content, $matches);
        return count($matches[0]);
    }

    static function getShortcodeContent($name, $index, $post_content)
    {
        preg_match_all('/\[' . $name . '(.*?)\](.*?)\[\/' . $name . '\]/s', $post_content, $matches);
        // 获取第二个 my_shortcode 短代码里面包裹的内容

        return $matches[2][$index];
    }

    static function parseShortcodebak($shortcode_name, $shortcode_content)
    {
        // 定义正则表达式匹配模式
        $pattern = '/\[' . $shortcode_name . '\s+(.*?)\](.*?)\[\/' . $shortcode_name . '\]/s';

        // 匹配短代码，获取属性和内容
        preg_match($pattern, $shortcode_content, $matches);

        // 获取属性和内容
        $attrs = $matches[1];
        $content = $matches[2];

        // 解析属性，将属性和属性值存储到关联数组中
        $attr_pairs = explode(' ', $attrs);
        $attr_array = array();

        foreach ($attr_pairs as $pair) {
            $parts = explode('=', $pair);
            if (count($parts) == 2) {
                $attr_array[$parts[0]] = str_replace('"', '', $parts[1]);
            }
        }

        // 返回属性和内容
        return array(
            'attrs' => $attr_array,
            'content' => $content
        );
    }

    static function parseShortcode($shortcode_name, $content, $index)
    {
        // 定义正则表达式匹配模式
        $pattern = '/\[' . $shortcode_name . '\s+(.*?)\](.*?)\[\/' . $shortcode_name . '\]/s';

        // 匹配所有短代码，获取属性和内容
        preg_match_all($pattern, $content, $matches);

        // 获取指定序号的短代码内容
        $shortcode_content = $matches[0][$index];

        // 获取属性和内容
        preg_match($pattern, $shortcode_content, $matches);
        $attrs = $matches[1];
        $content = $matches[2];

        // 解析属性，将属性和属性值存储到关联数组中
        $attr_pairs = explode(' ', $attrs);
        $attr_array = array();

        foreach ($attr_pairs as $pair) {
            $parts = explode('=', $pair);
            if (count($parts) == 2) {
                $attr_array[$parts[0]] = str_replace('"', '', $parts[1]);
            }
        }

        // 返回属性和内容
        return array(
            'attrs' => $attr_array,
            'content' => $content
        );
    }

    static function getArchiveTitle()
    {
        $title = get_the_archive_title();
        $title = str_replace('<span class="page-title-archive">', '', $title);
        $title = str_replace('<span class="page-title-category">', '', $title);
        $title = str_replace('<span class="page-title-tag">', '', $title);
        $title = str_replace('<span>', '', $title);
        return str_replace('</span>', '', $title);
    }

    static function commentKeyWordApprove($content)
    {
        global $core_next_set;
        $word = $core_next_set['comment_approve_word'];
        if ($word == '') {
            return false;

        }
        if (strpos($word, "\n") !== false) {
            $key_arr = explode("\n", $word);
        } else {
            $key_arr[] = $word;
        }

        foreach ($key_arr as $keyword) {
            if (stripos($content, $keyword) !== false) {
                return true;
            }
        }
        return false;
    }

    static function commentKeyWordBan($content)
    {
        global $core_next_set;
        $word = $core_next_set['comment_blacklist'];
        if ($word == '') {
            return false;

        }
        if (strpos($word, "\n") !== false) {
            $key_arr = explode("\n", $word);
        } else {
            $key_arr[] = $word;
        }
        foreach ($key_arr as $keyword) {
            if (stripos($content, $keyword) !== false) {
                return true;
            }
        }
        return false;
    }

    static function getUserLatestPosts($user_id, $post_count = 5)
    {
        $args = array(
            'author' => $user_id,
            'posts_per_page' => $post_count,
            'order' => 'DESC',
            'orderby' => 'date'
        );
        return get_posts($args);
    }

    static function getCommentCount($user_id)
    {
        return get_comments(array(
            'user_id' => $user_id,
            'count' => true // 只获取评论数
        ));
    }

    static function getUserDisplayName($user_id = null)
    {
        if ($user_id === null) {
            $user_id = get_post_field('post_author', get_the_ID());
        }
        $user = get_user_by('ID', $user_id);
        return $user->display_name;
    }

    static function getUserMail($id = null)
    {
        if ($id === null) {
            $user_id = get_current_user_id();
        } else {
            $user_id = $id;
        }
        $user = get_user_by('ID', $user_id);
        return $user->user_email;
    }

    static function postCommentHaveMail($mail, $post_id)
    {
        global $wpdb;
        $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$post_id} and `comment_approved`='1' and `comment_author_email`='{$mail}' LIMIT 1";
        return $wpdb->get_results($query) !== [];
    }

    static function handleTitle($site_name, $sub_title)
    {
        global $core_next_set;
        $delimiter = $core_next_set['seo_title_delimiter'];
        $del_space = $core_next_set['seo_title_delimiter_del_space'];
        if ($del_space) {
            return "$site_name$delimiter$sub_title";
        } else {
            return "$site_name $delimiter $sub_title";
        }
    }

    static function getPostListByCatID($cat_id, $count, $need = 'all')
    {
        $args = array(
            'category' => $cat_id,
            'posts_per_page' => $count,
        );
        $posts = get_posts($args);
        $post_list = [];
        foreach ($posts as $item) {
            $post_list[] = self::getPostMetaData($item, true, $need);
        }
        $post_list = Theme::handleRandomThumbnail($post_list);
        wp_reset_postdata();
        return $post_list;
    }

    static function getUserPostMeta($post)
    {
        $data['title'] = $post->post_title;
        $data['url'] = get_the_permalink($post);
        return $data;
    }

    static function getUserCommentMeta($comment)
    {
        $data['content'] = apply_filters('comment_text', $comment->comment_content);
        $data['post_id'] = $comment->comment_post_ID;
        return $data;
    }

    static function getAuthorActivity($number, $user_id)
    {
        $need_number = ceil($number / 2);
        $comments_query = new \WP_Comment_Query;
        $latest_comments = $comments_query->query(array(
            'number' => $need_number,
            'status' => 'approve',
            'user_id' => $user_id
        ));

        $comments_data = [];
        foreach ($latest_comments as $comment) {
            $post_id = $comment->comment_post_ID;
            $comments_data[] = array(
                'type' => 'comment',
                'date' => strtotime(get_comment_date('Y-m-d H:i:s', $comment->comment_ID)),
                'content' => wp_kses_post($comment->comment_content),
                'post_title' => get_the_title($post_id),
                'post_url' => get_permalink($post_id)
            );
        }

        $latest_posts_args = array(
            'posts_per_page' => $need_number,
            'post_status' => 'publish',
            'orderby' => 'date',
            'author' => $user_id,
        );

        $latest_posts = new \WP_Query($latest_posts_args);
        $post_data = array();
        while ($latest_posts->have_posts()) : $latest_posts->the_post();
            $post_data[] = array(
                'type' => 'post',
                'date' => get_the_time('U'),
                'post_title' => get_the_title(),
                'post_url' => get_permalink(),
            );
        endwhile;
        wp_reset_postdata();
        $all_data = array_merge($comments_data, $post_data);
        usort($all_data, function ($a, $b) {
            $date1 = \DateTime::createFromFormat('U', $a['date']);
            $date2 = \DateTime::createFromFormat('U', $b['date']);
            // 比较日期时间对象并返回结果
            if ($date1 < $date2) {
                return 1;
            } elseif ($date1 > $date2) {
                return -1;
            } else {
                return 0;
            }
        });

        return $all_data;
    }
}