<?php
if(!defined('ABSPATH'))exit;
class baiduseo_common
{
    public function init()
    {
        add_action('wp', [$this, 'baiduseo_init_session']);
        $baiduseo_zz = get_option('baiduseo_zz');
        // //兼容所有文章类型的推送,推送全部计划任务
        if (isset($baiduseo_zz['status']) && is_string($baiduseo_zz['status']) && strpos($baiduseo_zz['status'], '1') !== false) {
            $tuisong = explode(',', $baiduseo_zz['post_type']);

            if (is_array($tuisong) && !empty($tuisong)) {
                foreach ($tuisong as $k => $v) {
                    add_action('save_post_' . $v, [$this, 'baiduseo_articlepublish_ts'], 10, 3);
                }
            }
        }
        add_action('init', [$this, 'baiduseo_register_publish_hooks'], 20);


        if (is_admin()) {
            add_action('admin_enqueue_scripts', [$this, 'baiduseo_enqueue']);
            add_filter('plugin_action_links_' . BAIDUSEO_NAME, [$this, 'baiduseo_plugin_action_links']);
            add_action('admin_menu', [$this, 'baiduseo_addpages']);
        } else {
            add_action('wp_head', [$this, 'baiduseo_mainpage'], 1);
        }
        add_action('wp_footer', [$this, 'baiduseo_wztkjseo']);
        add_shortcode('baiduseofriends', [$this, 'baiduseo_get_shortcode']);
        add_action('manage_posts_custom_column', [$this, 'baiduseo_yuanchuang_column_content'], 10, 2);
        add_filter('manage_posts_columns', [$this, 'baiduseo_yuanchuang_column']);
        add_action('wp_ajax_baiduseo_liuliang_log', [$this, 'baiduseo_liuliang_log']);
        add_action('wp_ajax_nopriv_baiduseo_liuliang_log', [$this, 'baiduseo_liuliang_log']);
        add_filter('cron_schedules', [$this,'baiduseo_cron_ts_verey']);
       
    }
    public function baiduseo_cron_ts_verey($schedules){
         // 添加每分钟执行的间隔
        if (!isset($schedules['baiduseo_every_minute'])) {
            $schedules['baiduseo_every_minute'] = array(
                'interval' => 60, // 间隔时间（秒）
                'display'  => __('Every Minute', 'baiduseo')
            );
        }
        if (!isset($schedules['baiduseo_every_five_minute'])) {
            $schedules['baiduseo_every_five_minute'] = array(
                'interval' => 300,
                'display'  => __('Every five Minute', 'baiduseo')
            );
        }
        return $schedules;
    }
    public function baiduseo_register_publish_hooks()
    {
        $seo_init = get_option('baiduseo_tag');
        if (isset($seo_init['name'])) {
            $post_types = explode(',', $seo_init['name']);
            if (!empty($post_types)) {
                foreach ($post_types as $k => $v) {

                    add_action('publish_' . $v, [$this, 'baiduseo_articlepublish']);
                    add_action('publish_future_' . $v, [$this, 'baiduseo_articlepublish']);
                }
            }
        }
    }
    public function baiduseo_init_session()
    {
        if (!session_id()) {
            ob_start();
            session_start();
            ob_end_flush();
        }
    }
    public function baiduseo_liuliang_log()
    {
        if (isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'baiduseo_front')) {
            
            $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(strtolower(wp_unslash($_SERVER['HTTP_USER_AGENT']))) : '';
            
            if (empty($userAgent)) {
                return;
            }

            $botKeywords = [
                'bot',
                'crawl',
                'spider',
                'slurp',
                'search',
                'fetch',
                'index',
                'googlebot',
                'bingbot',
                'yandexbot',
                'baiduspider',
                'sogou',
                'exabot',
                'msnbot',
                'mj12bot',
                'ahrefs',
                'semrush',
                'duckduckbot',
                'facebot',
                'ia_archiver',
                'python-requests',
                'curl',
                'wget',
                'postmanruntime',
                'httpclient'
            ];
            $isBot = false;
            foreach ($botKeywords as $keyword) {
                if (strpos($userAgent, $keyword) !== false) {
                    $isBot = true;
                    break;
                }
            }
           
            if ($isBot) {
                return;
            }
            global $wpdb;
            $currnetTime = current_time('Y-m-d H:i:s');
            $today = current_time('Y-m-d');
            
            $params = [
                'userAgent' => isset($_POST['userAgent']) ? sanitize_text_field(wp_unslash($_POST['userAgent'])) : '',
                
                'ip' => isset($_POST['ip']) ? sanitize_text_field(wp_unslash($_POST['ip'])) : '',
                'currentUrl' => isset($_POST['currentUrl']) ? sanitize_url(wp_unslash($_POST['currentUrl'])) : '',
                'referrer' => isset($_POST['referrer']) ? sanitize_url(wp_unslash($_POST['referrer'])) : '',
                'baiduseo_time' => isset($_POST['baiduseo_time']) ? sanitize_text_field(wp_unslash($_POST['baiduseo_time'])) : '',

                'baiduseo_language' => isset($_POST['baiduseo_language']) ? sanitize_text_field(wp_unslash($_POST['baiduseo_language'])) : '',
                'baiduseo_pla' => isset($_POST['baiduseo_pla']) ? sanitize_text_field(wp_unslash($_POST['baiduseo_pla'])) : '',
                'baiduseo_liulanqi' => isset($_POST['baiduseo_liulanqi']) ? sanitize_text_field(wp_unslash($_POST['baiduseo_liulanqi'])) : '',
                'baiduseo_type' => isset($_POST['baiduseo_type']) ? (int)$_POST['baiduseo_type'] : 0,
                'baiduseo_detail' => isset($_POST['baiduseo_detail']) ? sanitize_text_field(wp_unslash($_POST['baiduseo_detail'])) : '',
                'session'=>isset($_POST['baiduseo_liulan']) ? sanitize_text_field(wp_unslash($_POST['baiduseo_liulan'])) : '',
            ];
            
            $params['session'] = md5(
                $params['userAgent'] .
                    $params['ip'] .
                    $params['session'].
                    $params['currentUrl'] .
                    $params['referrer'] .
                    $params['baiduseo_time']
            );
            
           
            $shibie = md5($params['userAgent'] . $params['baiduseo_pla'] . $params['ip']);
            
            $existing_record = $wpdb->get_row($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}baiduseo_liuliang 
                 WHERE session = %s",
                $params['session']
            ), ARRAY_A);
           
            if ($existing_record) {
                $wpdb->update(
                    $wpdb->prefix . 'baiduseo_liuliang',
                    ['updatetime' => $currnetTime],
                    ['id' => $existing_record['id']]
                );
                return;
            }
            
            $has_today_record = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}baiduseo_liuliang 
                 WHERE shibie = %s AND DATE(time) = %s",
                $shibie,
                $today
            ));
            $status = empty($has_today_record) ? 1 : 0;
            $today_start = current_time('Y-m-d') . ' 00:00:00';
            $ip_exists = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}baiduseo_liuliang 
                 WHERE ip = %s
                 AND time < %s",
                $params['ip'],
                $today_start
            ));
            $is_new = $ip_exists > 0 ? 1 : 0;
            
            $today_pinci = (int)$wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}baiduseo_liuliang 
                 WHERE shibie = %s AND DATE(time) = %s",
                $shibie,
                $today
            ));
            $pinci = $today_pinci + 1;

            $first_record = $wpdb->get_row($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}baiduseo_liuliang 
                 WHERE shibie = %s AND DATE(time) = %s AND status = 1 
                 ORDER BY id ASC LIMIT 1",
                $shibie,
                $today
            ), ARRAY_A);
           

            $insert_data = [
                'source' => $params['referrer'] ? $params['referrer'] : '隐匿来源',
                'url' => $params['currentUrl'],
                'time' => $currnetTime,
                'ip' => $params['ip'] === 'unknown' ? '' : $params['ip'],
                'shibie' => $shibie,
                'session' => $params['session'],
                'type' => $params['baiduseo_type'],
                'status' => $status,
                'lan' => $params['baiduseo_language'],
                'pla' => $params['baiduseo_pla'],
                'liulanqi' => $params['baiduseo_liulanqi'],
                'is_new' => $is_new,
                'pinci' => $pinci,
                'pid' => $first_record ? $first_record['id'] : 0,
                'baiduseo_detail' => $params['baiduseo_detail']
            ];
            $res = $wpdb->insert($wpdb->prefix . 'baiduseo_liuliang', $insert_data);
            
            if ($first_record) {
                $wpdb->update(
                    $wpdb->prefix . 'baiduseo_liuliang',
                    ['shendu' => $pinci], // 总条数 = 当前pinci（已+1）
                    ['id' => $first_record['id']]
                );
            }
        }
    }
    public function baiduseo_wztkjseo()
    {

        
        $baiduseo_liuliang = get_option('baiduseo_liuliang');

        if (isset($baiduseo_liuliang['open']) && $baiduseo_liuliang['open']) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $baiduseo_ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $baiduseo_ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
            } else {
                $baiduseo_ip = '';
            }
            $baiduseo_time = time();
            if (!isset($_SESSION['baiduseo_liulan'])) {
                $_SESSION['baiduseo_liulan'] = md5($baiduseo_ip . wp_rand(1000000, 999999));
            }

?>
            <script>
                function baiduseo_getBrowserType() {
                    const ua = (navigator.userAgent || "").toLowerCase();


                    // 一、爬虫检测


                    const botKeywords = [
                        'bot', 'crawl', 'spider', 'slurp', 'search', 'fetch', 'index',
                        'googlebot', 'bingbot', 'yandexbot', 'baiduspider', 'sogou', 'exabot',
                        'duckduckbot', 'facebot', 'ia_archiver', 'semrush', 'ahrefsbot',
                        'python-requests', 'curl', 'wget', 'postmanruntime', 'httpclient'
                    ];

                    let isBot = false;
                    if (!ua || ua.trim() === "") {
                        isBot = true; // UA为空
                    } else {
                        isBot = botKeywords.some(keyword => ua.includes(keyword));
                    }

                    // 如果是爬虫访问，直接返回结果
                    if (isBot) {
                        return
                    }

                    // 二、浏览器识别逻辑
                    let browser = 'Other';
                    let version = '';

                    // Opera
                    if (ua.includes('opera') || ua.includes('opr/')) {
                        browser = 'Opera';
                    }
                    // IE系列
                    else if (ua.includes('trident') && ua.includes('rv:11.0')) {
                        browser = 'IE11';
                    } else if (ua.includes('compatible') && ua.includes('msie') && !ua.includes('opera')) {
                        const match = ua.match(/msie (\d+\.\d+)/);
                        if (match) {
                            const ver = parseFloat(match[1]);
                            if (ver === 7) browser = 'IE7';
                            else if (ver === 8) browser = 'IE8';
                            else if (ver === 9) browser = 'IE9';
                            else if (ver === 10) browser = 'IE10';
                            else browser = 'IE';
                            version = ver;
                        }
                    }
                    // Edge（新版/旧版）
                    else if (ua.includes('edg/') || ua.includes('edge/')) {
                        browser = 'Edge';
                    }
                    // Firefox
                    else if (ua.includes('firefox')) {
                        browser = 'Firefox';
                    }
                    // UC 浏览器
                    else if (ua.includes('ubrowser')) {
                        browser = 'UC';
                    }
                    // QQ 浏览器
                    else if (ua.includes('qqbrowser')) {
                        browser = 'QQ';
                    }
                    // Safari（排除 Chrome/Edge/Opera）
                    else if (ua.includes('safari') && !ua.includes('chrome') && !ua.includes('edg') && !ua.includes('opr')) {
                        browser = 'Safari';
                    }
                    // Chrome（排除 Edge/Opera/UC）
                    else if (ua.includes('chrome') && !ua.includes('edg') && !ua.includes('opr') && !ua.includes('ubrowser')) {
                        browser = 'Chrome';
                    }

                    // -------------------------
                    // 三、返回结果
                    // -------------------------
                    return {
                        browser,
                        version,
                        isBot: false
                    };
                }

window.BaiduSeo = window.BaiduSeo || {};

(function(ns) {
    /* 配置常量 */
    var STORAGE_KEY = 'baiduseo_traffic_source';
    var EXPIRY_DAYS = 30;

    /* 核心逻辑 */
    ns.detectTrafficSource = function() {
        var siteDomain = window.location.hostname;
        var ref = document.referrer || '';
        var params = new URLSearchParams(window.location.search);
        var now = Date.now();

        var saved = localStorage.getItem(STORAGE_KEY);
        if (saved) {
            try {
                var parsed = JSON.parse(saved);
                if (parsed && parsed.type && parsed.timestamp) {
                    var ageDays = (now - parsed.timestamp) / (86400000);
                    if (ageDays < EXPIRY_DAYS) {
                        return parsed;
                    } else {
                        localStorage.removeItem(STORAGE_KEY);
                    }
                }
            } catch (e) {
                localStorage.removeItem(STORAGE_KEY);
            }
        }

        var adParams = ['utm_medium', 'utm_source', 'utm_campaign', 'gclid', 'fbclid', 'ttclid', 'msclkid'];
        var searchEngines = ['google.', 'bing.', 'yahoo.', 'baidu.', 'sogou.', 'so.com', 'duckduckgo.', 'yandex.', 'sm.cn', 'ecosia.'];
        var traffic = { type: 'direct', referrer: null, detail: '直接访问', timestamp: now };

        /* 检测广告 */
        for (var i = 0; i < adParams.length; i++) {
            if (params.has(adParams[i])) {
                traffic = { type: 'paid', referrer: ref || null, detail: '付费访问', timestamp: now };
                break;
            }
        }

        /* 检测搜索 */
        if (traffic.type === 'direct' && ref) {
            var refLower = ref.toLowerCase();
            for (var j = 0; j < searchEngines.length; j++) {
                if (refLower.indexOf(searchEngines[j]) !== -1 || refLower.indexOf('/search?') !== -1) {
                    traffic = { type: 'organic', referrer: ref, detail: '自然流量', timestamp: now };
                    break;
                }
            }
        }

        /* 检测外链 */
        if (traffic.type === 'direct' && ref && ref.indexOf(siteDomain) === -1) {
            traffic = { type: 'referral', referrer: ref, detail: '外部链接', timestamp: now };
        }

        try { localStorage.setItem(STORAGE_KEY, JSON.stringify(traffic)); } catch (e) {}
        return traffic;
    };

    ns.baiduseo_sendRequest = function() {
        /* 安全地获取 PHP 变量，如果变量不存在则返回空字符串 */
        var baiduseo_ip = <?php echo json_encode(isset($baiduseo_ip) ? $baiduseo_ip : ''); ?>;
        var baiduseo_nonce = <?php echo json_encode(function_exists('wp_create_nonce') ? wp_create_nonce('baiduseo_front') : ''); ?>;
        var baiduseo_time = <?php echo json_encode(isset($baiduseo_time) ? $baiduseo_time : ''); ?>;
        
        /* 复杂的 Session 获取逻辑，增加防御 */
        var baiduseo_session = <?php 
            $safe_session = '';
            if (isset($_SESSION['baiduseo_liulan'])) {
                $safe_session = $_SESSION['baiduseo_liulan'];
            }
            echo json_encode($safe_session); 
        ?>;

        var baiduseo_action = 'baiduseo_liuliang_log';
        var baiduseo_userAgent = navigator.userAgent;
        var baiduseo_language = navigator.language || navigator.userLanguage || '';
        var trafficData = ns.detectTrafficSource();
        var browserInfo = baiduseo_getBrowserType();
        var baiduseo_liulanqi = (browserInfo && browserInfo.browser) ? browserInfo.browser : '';
        var baiduseo_type = /mobile/i.test(baiduseo_userAgent) ? 2 : 1;
        var baiduseo_pla = (function() {
            var userAgent = navigator.userAgent;
            if (userAgent.indexOf("Windows NT 10.0") !== -1) return "Windows 10";
            if (userAgent.indexOf("Windows NT 6.2") !== -1) return "Windows 8";
            if (userAgent.indexOf("Windows NT 6.1") !== -1) return "Windows 7";
            if (userAgent.indexOf("Windows NT 6.0") !== -1) return "Windows Vista";
            if (userAgent.indexOf("Windows NT 5.1") !== -1) return "Windows XP";
            if (userAgent.indexOf("Windows NT 5.0") !== -1) return "Windows 2000";
            if (userAgent.indexOf("Mac") !== -1) return "Mac/iOS";
            if (userAgent.indexOf("X11") !== -1) return "UNIX";
            if (userAgent.indexOf("Linux") !== -1) return "Linux";
            return "Other";
        })();
        
        var requestData = [
            'ip=' + encodeURIComponent(baiduseo_ip),
            'userAgent=' + encodeURIComponent(baiduseo_userAgent),
            'referrer=' + encodeURIComponent(trafficData.referrer || ""),
            'currentUrl=' + encodeURIComponent(window.location.href),
            'nonce=' + encodeURIComponent(baiduseo_nonce),
            'action=' + encodeURIComponent(baiduseo_action),
            'baiduseo_time=' + encodeURIComponent(baiduseo_time),
            'session=' + encodeURIComponent(baiduseo_session),
            'baiduseo_liulan=' + encodeURIComponent(baiduseo_session),
            'baiduseo_language=' + encodeURIComponent(baiduseo_language),
            'baiduseo_pla=' + encodeURIComponent(baiduseo_pla),
            'baiduseo_liulanqi=' + encodeURIComponent(baiduseo_liulanqi),
            'baiduseo_type=' + encodeURIComponent(baiduseo_type),
            'baiduseo_detail=' + encodeURIComponent(trafficData.detail)
        ].join('&');

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '<?php echo esc_url(admin_url("admin-ajax.php")); ?>', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(requestData);
    };

    /* 获取定时时间，默认为 6000 毫秒 */
    var requestInterval = <?php 
        $interval = 6000;
        if (isset($baiduseo_liuliang) && is_array($baiduseo_liuliang) && isset($baiduseo_liuliang['pinci'])) {
            $val = intval($baiduseo_liuliang['pinci']);
            if ($val > 0) $interval = $val * 1000;
        }
        echo json_encode($interval); 
    ?>;

    /* 执行发送 */
    ns.baiduseo_sendRequest();
    if (requestInterval > 0) {
        ns.requestTimer = setInterval(ns.baiduseo_sendRequest, requestInterval);
        window.addEventListener('beforeunload', function() {
            clearInterval(ns.requestTimer);
        });
    }

})(window.BaiduSeo);
            </script>
<?php
        }
    }
    public function baiduseo_yuanchuang_column($columns)
    {
        $baiduseo_youhua = get_option('baiduseo_youhua');
        if (!isset($baiduseo_youhua['listbtn']) || !$baiduseo_youhua['listbtn']) {
            // if(1){
            $columns['yuanchuang'] = 'seo合集';
            // $columns['gaixie'] = '智能改写';
            // $columns['kuaisu'] = '快速推送';
            echo "
            <style>
                .wzt_mask {
                    position: fixed;
                    width: 100%;
                    height: 100%;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    overflow: hidden;
                    background-color: rgba(0, 0, 0, 0.8);
                    z-index: 9999;
                    opacity: 0.7;
                }
                .wzt_loading{
                    width: 80px;
                    height: 40px;
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
                .wzt_loading span{
                    display: inline-block;
                    width: 8px;
                    height: 100%;
                    border-radius: 4px;
                    background: #99CCFF;
                    -webkit-animation: load 1s ease infinite;
                    animation: load 1s ease infinite;
                }
                @-webkit-keyframes load{
                    0%,100%{
                        height: 40px;
                        background: #99CCFF;
                    }
                    50%{
                        height: 70px;
                        margin: -15px 0;
                        background: #0099FF;
                    }
                }
                .wzt_loading span:nth-child(2){
                    -webkit-animation-delay:0.2s;
                    animation-delay:0.2s;
                }
                .wzt_loading span:nth-child(3){
                    -webkit-animation-delay:0.4s;
                    animation-delay:0.4s;
                }
                .wzt_loading span:nth-child(4){
                    -webkit-animation-delay:0.6s;
                    animation-delay:0.6s;
                }
                .wzt_loading span:nth-child(5){
                    -webkit-animation-delay:0.8s;
                    animation-delay:0.8s;
                }
            </style>
            
            
            <script>
                jQuery(document).ready(function($){
                    function popupInformation(msg) {
                        $('body').append(`<div class='wzt_popupInfo' 
                            style='position: fixed;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%);
                            padding: 10px 20px;
                            color: #FFF;
                            background-color: rgba(0, 0, 0, .4);
                            border-radius: 5px;
                            z-index: 10000;'><span>`+ msg +`</span></div>`
                        );
                            
                        setTimeout(() => {
                            $('.wzt_popupInfo').remove();
                        }, 3000);
                    }
                
                    $('.baiduseo_yuanchuangwzt').click(function() {
                        $('body').append(`
                        <!-- 加载遮罩层 -->
                        <div class='wzt_mask'>
                            <div class='wzt_loading'>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                        </div>
                        `)
                        var id = $(this).attr('data-id');
                        $.ajax({
                            url: '" . esc_url(admin_url('admin-ajax.php')) . "',
                            data: {
                                \"id\": id ,\"nonce\":\"" . esc_attr(wp_create_nonce('baiduseo')) . "\",\"action\":\"baiduseo_yuanchuang\"
                            },
                            type: 'post',
                            dataType: 'json',
                            success: function(res) {
                                if(res.msg!='0'){
                                    popupInformation('提交成功，请等待处理');
                                    location.reload();
                                }else{
                                    if(res.data){
                                        popupInformation(res.data);
                                        $('.wzt_mask').remove()
                                    }else{
                                        popupInformation('提交失败,失败的原因可能为：1.网络波动，请刷新后重试。2.远端服务器压力过大，请稍后重试。'); 
                                        $('.wzt_mask').remove()
                                    }
                                }
                            }
                        })
                        return false;
                    })
                    $('.kuaisuwzt').click(function() {
                        $('body').append(`
                        <!-- 加载遮罩层 -->
                        <div class='wzt_mask'>
                            <div class='wzt_loading'>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                        </div>
                        
                        `)
                        var id = $(this).attr('data-id');
                        $.ajax({
                            url: '" . esc_url(admin_url('admin-ajax.php')) . "',
                            data: {
                                \"id\": id ,\"nonce\":\"" . esc_attr(wp_create_nonce('baiduseo_kuaisu')) . "\",\"action\":\"baiduseo_kuaisu\"
                            },
                            type: 'post',
                            dataType: 'json',
                            success: function(res) {
                                if(res.msg!='0'){
                                    $('.wzt_mask').remove()
                                    popupInformation('提交成功');
                                    location.reload();
                                }else{
                                    popupInformation('提交失败,失败原因可能为：1.可能你的网站没有快速推送的权限。2.你的快速推送配额不足。3.站长信息填写的api链接不正确。');
                                    $('.wzt_mask').remove()
                                }
                            }
                        })
                        return false;
                    });
                    
                    $('.baiduseo_gaixiewzt').click(function() {
                        $('body').append(`
                        <!-- 加载遮罩层 -->
                        <div class='wzt_mask'>
                            <div class='wzt_loading'>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                        </div>
                        
                        `)
                        var id = $(this).attr('data-id');
                        $.ajax({
                            url: '" . esc_url(admin_url('admin-ajax.php')) . "',
                            data: {
                                \"id\": id ,\"nonce\":\"" . esc_attr(wp_create_nonce('baiduseo')) . "\",\"action\":\"baiduseo_gaixie\"
                            },
                            type: 'post',
                            dataType: 'json',
                            success: function(res) {
                               
                                if(res.msg=='1'){
                                    $('.wzt_mask').remove()
                                    popupInformation('提交成功');
                                    location.reload();
                                }else if(res.msg=='2'){
                                     $('.wzt_mask').remove();
                                    popupInformation('通道维护中，请等待更新');
                                }else{
                                    $('.wzt_mask').remove()
                                    popupInformation('提交失败,积分不足');
                                }
                            }
                        })
                        return false;
                    });
                    $('.putongwzt').click(function(){
                        $('body').append(`
                        <!-- 加载遮罩层 -->
                        <div class='wzt_mask'>
                            <div class='wzt_loading'>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                        </div>`)
                         var id = $(this).attr('data-id');
                        $.ajax({
                            url: '" . esc_url(admin_url('admin-ajax.php')) . "',
                            data: {
                                \"id\": id ,\"nonce\":\"" . esc_attr(wp_create_nonce('baiduseo')) . "\",\"action\":\"baiduseo_ptts\"
                            },
                            type: 'post',
                            dataType: 'json',
                            success: function(res) {
                                if(res.msg!='0'){
                                    $('.wzt_mask').remove()
                                    let remind = '提交成功';
                                    popupInformation(remind);
                                    location.reload();
                                }else{
                                    $('.wzt_mask').remove()
                                    popupInformation(res.data);
                                }
                            }
                        })
                        return false;
                    })
                })
            </script>";
        }
        return $columns;
    }
    public static function baiduseo_dssdd($value)
    {
       
        $url = baiduseo_common::baiduseo_url(0);
        $log = baiduseo_kp::baiduseo_wzt_log();
        if($log){
            $type = 1;
            $arr = [
                md5($url),
                md5($log),
                md5($type),
                md5($url . $log),
                md5($url . $type),
                md5($log . $url),
                md5($log . $type),
                md5($type . $url),
                md5($type . $log),
                md5($url . $log . $type),
                md5($url . $type . $log),
                md5($log . $url . $type),
                md5($log . $type . $url),
                md5($type . $url . $log),
                md5($type . $log . $url),
            ];
            return $arr;
        }else{
            return 0;
        }
    }
    public function baiduseo_yuanchuang_column_content($column_name, $post_id)
    {
        if (current_user_can('manage_options')) {
            $post_extend = get_post_meta($post_id, 'baiduseo', true);
            if ($column_name == 'yuanchuang') {
                if (isset($post_extend['status']) && $post_extend['status'] == 2) {
                    echo '检测中...<br />';
                } elseif (isset($post_extend['status']) && $post_extend['status'] == 1) {
                    if (isset($post_extend['hyc']) && $post_extend['hyc']) {
                        if ($post_extend['hyc'] == '102') {
                            echo '无效内容';
                        } elseif ($post_extend['hyc'] == '101') {
                            echo '无效内容';
                        } else {
                            echo '原创率：' . esc_attr($post_extend['hyc']) . '% <br/>';
                        }
                    } else {
                        if ($post_extend['yc'] == '102') {
                            echo '无效内容';
                        } elseif ($post_extend['yc'] == '101') {
                            echo '无效内容';
                        } else {
                            echo '原创率：' . esc_attr($post_extend['yc']) . '% <br />';
                        }
                    }
                } elseif (isset($post_extend['status']) && $post_extend['status'] == 3) {
                    if (isset($post_extend['yc'])) {
                        if ($post_extend['yc'] == '102') {
                            echo '无效内容';
                        } elseif ($post_extend['yc'] == '101') {
                            echo '无效内容';
                        } else {
                            echo '原创率：' . esc_attr($post_extend['yc']) . '% <br />';
                        }
                    } else {
                        echo '检测中...<br />';
                    }
                } else {
                    echo "
                    <style>
                        .baiduseo_yuanchuangwzt {
                            padding:0px 8px;
                            display: block;
                            margin: 5px 0;
                        }
                    </style>
                    <button class='baiduseo_yuanchuangwzt' data-id=" . (int)$post_id . " type='button'>原创检测</button>
                    ";
                }

                if (isset($post_extend['status']) && $post_extend['status'] == 3) {
                    echo '智能改写中...<br />';
                } elseif (isset($post_extend['yc']) && $post_extend['yc'] && (!isset($post_extend['hyc']) || !$post_extend['hyc'])) {
                    echo "<style>
                        .baiduseo_gaixiewzt {
                            padding:0px 8px;
                            display: block;
                            margin: 5px 0;
                        }
                    </style>
                    <button class='baiduseo_gaixiewzt' data-id=" . esc_attr($post_id) . " type='button'>智能改写</button>
                    ";
                } else {

                    if (isset($post_extend['hyc']) && $post_extend['hyc']) {
                        echo '改写后：' . esc_attr($post_extend['yc']) . '%';
                    } else {
                        echo "<style>
                        .baiduseo_gaixiewzt {
                            padding:0px 8px;
                            display: block;
                        }
                        </style>
                        <button class='baiduseo_gaixiewzt' data-id=" . (int)$post_id . " type='button'>智能改写</button>
                    ";
                    }
                }
                $link = get_permalink($post_id);
                global $wpdb;
                // $post1 = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."baiduseo_zz  where type=2 and link=%s order by id desc ",$link),ARRAY_A);
                // if(!empty($post1)){
                //     echo '已推送';
                // }else{
                //     echo "<style>
                //     .kuaisuwzt,
                //     .putongwzt {
                //         display: block;
                //         padding:0px 8px;
                //         margin: 5px 0;
                //     }
                // </style><button class='kuaisuwzt' data-id=".(int)$post_id." type='button'>快速推送</button>";
                // }
                echo '<button class="putongwzt" data-id="' . (int)$post_id . '" type="button">一键推送</button>';
            }
        }
    }
    public function baiduseo_get_shortcode($atts, $content = null)
    {

        return  baiduseo_seo::baiduseo_friends_hh(md5(baiduseo_common::baiduseo_url(0)));
    }
    public function baiduseo_mainpage()
    {

        $baiduseo_zz = get_option('baiduseo_zz');
        if (isset($baiduseo_zz['toutiao_key']) && $baiduseo_zz['toutiao_key'] &&  isset($baiduseo_zz['pingtai']) && is_string($baiduseo_zz['pingtai'])  && strpos($baiduseo_zz['pingtai'], '3') !== false) {
            echo '<script>
                  /*seo合集头条推送*/
                (function(){
                var el = document.createElement("script");
                el.src = "https://sf1-scmcdn-tos.pstatp.com/goofy/ttzz/push.js?' . esc_attr($baiduseo_zz['toutiao_key']) . '";
                el.id = "ttzz";
                var s = document.getElementsByTagName("script")[0];
                s.parentNode.insertBefore(el, s);
                })(window)
                </script>';
        }
        if (!isset($_SERVER['REQUEST_URI'])) {
            $_SERVER['REQUEST_URI'] = '';
        }
        $shouye = sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']));
        if ($shouye == '/' || $shouye == '') {

            if (is_front_page() && is_home()) {
                $seo = get_option('seo_init');
                if ($seo) {
                    if (isset($seo['keywords']) && $seo['keywords']) {
                        echo '<meta name="keywords" content="' . esc_attr($seo['keywords']) . '">' . "\n\r";
                    }
                    if (isset($seo['description']) && $seo['description']) {
                        echo '<meta name="description" content="' . esc_attr($seo['description']) . '">' . "\n\r";
                    }
                }
            } elseif (is_front_page()) {
                $seo = get_option('seo_init');
                if ($seo) {
                    if (isset($seo['keywords']) && $seo['keywords']) {
                        echo '<meta name="keywords" content="' . esc_attr($seo['keywords']) . '">' . "\n\r";
                    }
                    if (isset($seo['description']) && $seo['description']) {
                        echo '<meta name="description" content="' . esc_attr($seo['description']) . '">' . "\n\r";
                    }
                }
            } elseif (is_home()) {
                $seo = get_option('seo_init');
                if ($seo) {
                    if (isset($seo['keywords']) && $seo['keywords']) {
                        echo '<meta name="keywords" content="' . esc_attr($seo['keywords']) . '">' . "\n\r";
                    }
                    if (isset($seo['description']) && $seo['description']) {
                        echo '<meta name="description" content="' . esc_attr($seo['description']) . '">' . "\n\r";
                    }
                }
            }
        }
        if (is_category()) {
            $cate = get_the_category();

            if (isset($cate[0]->cat_ID)) {
                $seo = get_option('baiduseo_cate_' . $cate[0]->cat_ID);

                if (!empty($seo)) {
                    if (isset($seo['keywords']) && $seo['keywords']) {

                        echo sprintf('<meta name="keywords" content="%s" />' . "\n", esc_attr($seo['keywords']));
                    }
                    if (isset($seo['description']) && $seo['description']) {
                        echo sprintf('<meta name="description" content="%s" />' . "\n", esc_attr($seo['description']));
                    }
                }
            }
        } elseif (is_single()) {
            add_action('the_content', [$this, 'BaiduSEO_addlink']);
        } elseif (is_page()) {


            global $post;

            $baiduseo_page = get_post_meta($post->ID, 'baiduseo_page', true);
            if (isset($baiduseo_page['keywords']) && $baiduseo_page['keywords']) {

                echo sprintf('<meta name="keywords" content="%s" />' . "\n", esc_attr($baiduseo_page['keywords']));
            }
            if (isset($baiduseo_page['description']) && $baiduseo_page['description']) {
                echo sprintf('<meta name="description" content="%s" />' . "\n", esc_attr($baiduseo_page['description']));
            }
        }
    }
    public function BaiduSEO_addlink($content)
    {

        global $wpdb;
        $baiduseo_wzt_log = baiduseo_kp::baiduseo_wzt_log();
        $alt = get_option('seo_alt_auto');

        $post_title = get_the_title();
        if ((isset($alt['alt']) && $alt['alt']) || (isset($alt['title']) && $alt['title'])) {
            if (preg_match_all('#<img([^>]+)>#is', $content, $match)) {
                $img_seo = array();
                $img_idx = -1;
                foreach ($match[0] as $k => $img) {
                    if (!preg_match('#src=.+#', $img)) {
                        continue;
                    }
                    $src_img = $img;

                    $img = str_replace(array('alt=""', "alt=''", 'title=""', "title=''"), '', $img);

                    $img_key = md5($img);
                    if (!isset($img_seo[$img_key])) {
                        $img_idx++;
                        $img_seo[$img_key] = $img_idx;
                    }
                    $img_k = $img_seo[$img_key];
                    $add_html = '';

                    if (isset($alt['title']) && $alt['title']) {

                        if ($alt['title'] == '2') {
                            if (preg_match('#/.+?\.(jpg|jpeg|gif|webp|png|bmp)#is', $img, $name_match)) {
                                $add_html .= ' title="' . esc_attr(basename($name_match[0])) . '"';
                            }
                        } else if ($post_title) {

                            $add_html .= ' title="' . esc_attr($post_title) . '"';
                        }
                    }

                    if (isset($alt['alt']) && $alt['alt']) {

                        if ($alt['alt'] == '2') {
                            if (preg_match('#/.+?\.(jpg|jpeg|gif|webp|png|bmp)#is', $img, $name_match)) {
                                $add_html .= ' alt="' . esc_attr(basename($name_match[0])) . '"';
                            }
                        } else if ($post_title) {
                            $add_html .= ' alt="' . esc_attr($post_title) . '"';
                        }
                    }
                    if (!$add_html) {
                        continue;
                    }
                    $original = str_replace(array('alt=""', "alt=''", 'title=""', "title=''"), '', $match[1][$k]);

                    $new_img = '<img' . $add_html . ' ' . $original . '>';
                    $content = str_replace($src_img, $new_img, $content);
                }
            }
        }
        $seo_init = get_option('baiduseo_tag');
        $post_types = [];
        if (isset($seo_init['name'])) {
            $post_types = explode(',', $seo_init['name']);
        }

        $id = get_the_ID();
        if ($baiduseo_wzt_log) {
            $log = 1; // 原代码中支付逻辑注释，暂保留1
            if ($log) {
                $Tag_manage = get_option('baiduseo_tag');
                if (!empty($Tag_manage)) {
                    $current_post_type = get_post_type($id);
                    if (empty($post_types) || !in_array($current_post_type, $post_types)) {
                        return $content;
                    }
                    $current_tag_taxonomy = '';


                    $supported_taxonomies = get_object_taxonomies($current_post_type, 'objects');

                    foreach ($supported_taxonomies as $tax) {
                        if (!$tax->hierarchical) {
                            $current_tag_taxonomy = $tax->name;
                            break;
                        }
                    }



                    if (empty($current_tag_taxonomy)) {
                        return $content;
                    }


                    if ((isset($Tag_manage['bqgl']) && is_string($Tag_manage['bqgl']) && strpos($Tag_manage['bqgl'], '2') !== false)) {

                        if (isset($Tag_manage['link']) && ($Tag_manage['link'] == 1)) {

                            $tags = $wpdb->get_results(
                                $wpdb->prepare(
                                    'select a.* from (
                                    ' . $wpdb->prefix . 'terms as a 
                                    left join ' . $wpdb->prefix . 'term_taxonomy as b on a.term_id=b.term_id
                                ) left join ' . $wpdb->prefix . 'term_relationships as c on b.term_taxonomy_id =c.term_taxonomy_id  
                                where b.taxonomy=%s and c.object_id=%d group by a.name',
                                    $current_tag_taxonomy, // 动态标签分类法
                                    $id
                                ),
                                ARRAY_A
                            );

                            if (!empty($tags)) {
                                foreach ($tags as $val) {


                                    $term = get_term($val['term_id'], $current_tag_taxonomy); // 先获取术语对象

                                    // 修改2：获取标签链接时指定分类法，适配自定义标签
                                    $val['url'] = get_term_link($term);

                                    if (is_wp_error($val['url'])) {
                                        $val['url'] = '';
                                    }
                                    // 以下为原逻辑（标签匹配、加粗、变色），保持不变
                                    if (isset($Tag_manage['hremove']) && $Tag_manage['hremove'] == 1) {

                                        if (preg_match('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', $content, $matches)) {

                                            if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                if ($Tag_manage['bold'] == 1) {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['url'] . '"><b style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</b></a>', $content, 1);
                                                } else {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['url'] . '" style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                                }
                                            } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || (!$Tag_manage['color']))) {
                                                if ($Tag_manage['bold'] == 1) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['url'] . '"><b>' . $val['name'] . '</b></a>', $content, 1);
                                                } else {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['url'] . '">' . $val['name'] . '</a>', $content, 1);
                                                }
                                            } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['url'] . '" style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                            } else {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['url'] . '">' . $val['name'] . '</a>', $content, 1);
                                            }
                                        }
                                    } else {

                                        if (preg_match('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', $content, $matches)) {
                                            if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {

                                                if ($Tag_manage['bold'] == 1) {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['url'] . '"><b style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</b></a>', $content, 1);
                                                } else {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['url'] . '" style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                                }
                                            } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || (!$Tag_manage['color']))) {
                                                if ($Tag_manage['bold'] == 1) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['url'] . '"><b>' . $val['name'] . '</b></a>', $content, 1);
                                                } else {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['url'] . '">' . $val['name'] . '</a>', $content, 1);
                                                }
                                            } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['url'] . '" style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                            } else {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['url'] . '">' . $val['name'] . '</a>', $content, 1);
                                            }
                                        }
                                    }
                                }
                            }
                        } else {

                            // 子场景：标签不加链接（仅加粗/变色）
                            // 修改3：同样替换为动态标签分类法
                            $tags = $wpdb->get_results(
                                $wpdb->prepare(
                                    'select a.* from (
                                    ' . $wpdb->prefix . 'terms as a 
                                    left join ' . $wpdb->prefix . 'term_taxonomy as b on a.term_id=b.term_id
                                ) left join ' . $wpdb->prefix . 'term_relationships as c on b.term_taxonomy_id =c.term_taxonomy_id  
                                where b.taxonomy=%s and c.object_id=%d group by a.name',
                                    $current_tag_taxonomy, // 动态标签分类法
                                    $id
                                ),
                                ARRAY_A
                            );

                            if (!empty($tags)) {
                                foreach ($tags as $val) {
                                    // 以下为原逻辑（标签匹配、加粗、变色），保持不变
                                    if (isset($Tag_manage['hremove']) && $Tag_manage['hremove'] == 1) {
                                        if (preg_match('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', $content, $matches)) {
                                            if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                if ($Tag_manage['bold'] == 1) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<b style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</b>', $content, 1);
                                                } else {
                                                    if ($val['tag_target'] && $val['tag_nofollow']) {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank" rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                    } elseif ($val['tag_target'] && !$val['tag_nofollow']) {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank">' . $val['name'] . '</a>', $content, 1);
                                                    } elseif (!$val['tag_target'] && $val['tag_nofollow']) {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '"  rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                    } else {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                                    }
                                                }
                                            } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || !$Tag_manage['color'])) {
                                                if ($Tag_manage['bold'] == 1) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<b>' . $val['name'] . '</b>', $content, 1);
                                                }
                                            } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                if ($val['tag_target'] && $val['tag_nofollow']) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank" rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                } elseif ($val['tag_target'] && !$val['tag_nofollow']) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank" >' . $val['name'] . '</a>', $content, 1);
                                                } elseif (!$val['tag_target'] && $val['tag_nofollow']) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '" rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                } else {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a  style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                                }
                                            }
                                        }
                                    } else {
                                        if (preg_match('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', $content, $matches)) {
                                            if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                if ($Tag_manage['bold'] == 1) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<b style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</b>', $content, 1);
                                                } else {
                                                    if ($val['tag_target'] && $val['tag_nofollow']) {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank" rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                    } elseif ($val['tag_target'] && !$val['tag_nofollow']) {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank">' . $val['name'] . '</a>', $content, 1);
                                                    } elseif (!$val['tag_target'] && $val['tag_nofollow']) {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '"  rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                    } else {
                                                        $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                                    }
                                                }
                                            } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || !$Tag_manage['color'])) {
                                                if ($Tag_manage['bold'] == 1) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<b>' . $val['name'] . '</b>', $content, 1);
                                                }
                                            } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                if ($val['tag_target'] && $val['tag_nofollow']) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank" rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                } elseif ($val['tag_target'] && !$val['tag_nofollow']) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '" target="_blank" >' . $val['name'] . '</a>', $content, 1);
                                                } elseif (!$val['tag_target'] && $val['tag_nofollow']) {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '" rel="nofollow">' . $val['name'] . '</a>', $content, 1);
                                                } else {
                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['name']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a  style="color:' . $Tag_manage['color'] . '">' . $val['name'] . '</a>', $content, 1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //内链
                    if ((isset($Tag_manage['bqgl']) && is_string($Tag_manage['bqgl']) && strpos($Tag_manage['bqgl'], '1') !== false) || !isset($Tag_manage['bqgl'])) {

                        //定义自增数量
                        $nladdnum = 0;
                        //处理优先级
                        if (isset($Tag_manage['bqgl']) && is_string($Tag_manage['bqgl']) && strpos($Tag_manage['bqgl'], '2') !== false) {
                            if (!empty($tags)) {
                                $placeholders = array_fill(0, count($tags), '%s');
                                $placeholder_string = implode(',', $placeholders);
                                $tag_names = wp_list_pluck($tags, 'name');

                                $post1 = $wpdb->get_results(
                                    $wpdb->prepare("SELECT * FROM {$wpdb->prefix}baiduseo_neilian WHERE keywords NOT IN({$placeholder_string}) AND sort > 0 ORDER BY sort DESC", $tag_names),
                                    ARRAY_A
                                );
                            } else {
                                $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort>0   order by sort desc ", ARRAY_A);
                            }
                        } else {
                            $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort>0 order by sort desc ", ARRAY_A);
                        }

                        if (!empty($post1)) {
                            foreach ($post1 as $key => $val) {

                                if ($val['target'] == 1) {
                                    $target = 'target=_blank';
                                } else {
                                    $target = '';
                                }
                                if ($val['nofollow'] == 1) {
                                    $nofollow = 'rel="nofollow"';
                                } else {
                                    $nofollow = '';
                                }
                                if (isset($Tag_manage['hremove']) && $Tag_manage['hremove'] == 1) {
                                    if (preg_match('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', $content, $matches)) {
                                        $nladdnum++;
                                        if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {

                                            if ($Tag_manage['bold'] == 1) {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b style="color:' . $Tag_manage['color'] . '">' . $val['keywords'] . '</b></a>', $content, 1);
                                            } else {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            }
                                        } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || (!$Tag_manage['color']))) {
                                            if ($Tag_manage['bold'] == 1) {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b>' . $val['keywords'] . '</b></a>', $content, 1);
                                            } else {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            }
                                        } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                            $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                        } else {
                                            $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                        }
                                        if (isset($Tag_manage['nlnum']) && $Tag_manage['nlnum'] != 11 && $nladdnum >= $Tag_manage['nlnum']) {
                                            break;
                                        }
                                    }
                                } else {
                                    if (preg_match('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', $content, $matches)) {
                                        $nladdnum++;
                                        if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {

                                            if ($Tag_manage['bold'] == 1) {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b style="color:' . $Tag_manage['color'] . '">' . $val['keywords'] . '</b></a>', $content, 1);
                                            } else {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            }
                                        } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || (!$Tag_manage['color']))) {
                                            if ($Tag_manage['bold'] == 1) {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b>' . $val['keywords'] . '</b></a>', $content, 1);
                                            } else {

                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            }
                                        } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                            $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                        } else {
                                            $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                        }
                                        if (isset($Tag_manage['nlnum']) && $Tag_manage['nlnum'] != 11 && $nladdnum >= $Tag_manage['nlnum']) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (isset($Tag_manage['nlnum']) && ($nladdnum < $Tag_manage['nlnum'] || $Tag_manage['nlnum'] == 11)) {
                            if (isset($Tag_manage['pp']) && $Tag_manage['pp'] == 1) {
                                if (isset($Tag_manage['bqgl']) && is_string($Tag_manage['bqgl']) && strpos($Tag_manage['bqgl'], '2') !== false) {
                                    if (!empty($tags)) {
                                        $placeholders = array_fill(0, count($tags), '%s');
                                        $placeholder_string = implode(',', $placeholders);
                                        $tag_names = wp_list_pluck($tags, 'name');

                                        $post1 = $wpdb->get_results(
                                            $wpdb->prepare("SELECT * FROM {$wpdb->prefix}baiduseo_neilian 
                                                    WHERE keywords NOT IN({$placeholder_string}) 
                                                    AND sort = 0 
                                                    ORDER BY LENGTH(keywords) DESC", $tag_names),
                                            ARRAY_A
                                        );
                                    } else {
                                        $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort=0    order by LENGTH(keywords) desc", ARRAY_A);
                                    }
                                } else {
                                    $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort=0    order by LENGTH(keywords) desc", ARRAY_A);
                                }
                            } elseif (isset($Tag_manage['pp']) && $Tag_manage['pp'] == 2) {
                                if (isset($Tag_manage['bqgl']) && is_string($Tag_manage['bqgl']) && strpos($Tag_manage['bqgl'], '2') !== false) {
                                    if (!empty($tags)) {
                                        $placeholders = array_fill(0, count($tags), '%s');
                                        $placeholder_string = implode(',', $placeholders);
                                        $tag_names = wp_list_pluck($tags, 'name');

                                       

                                        $post1 = $wpdb->get_results(
                                            $wpdb->prepare("SELECT * FROM {$wpdb->prefix}baiduseo_neilian 
                                                    WHERE keywords NOT IN({$placeholder_string}) 
                                                    AND sort = 0 
                                                    ORDER BY LENGTH(keywords) ASC", $tag_names),
                                            ARRAY_A
                                        );
                                    } else {
                                        $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort=0   order by LENGTH(keywords) asc", ARRAY_A);
                                    }
                                } else {
                                    $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort=0   order by LENGTH(keywords) asc", ARRAY_A);
                                }
                            } else {
                                if (isset($Tag_manage['bqgl']) && is_string($Tag_manage['bqgl']) && strpos($Tag_manage['bqgl'], '2') !== false) {
                                    if (!empty($tags)) {
                                        $placeholders = array_fill(0, count($tags), '%s');
                                        $placeholder_string = implode(',', $placeholders);
                                        $tag_names = wp_list_pluck($tags, 'name');

                                        $post1 = $wpdb->get_results(
                                            $wpdb->prepare("SELECT * FROM {$wpdb->prefix}baiduseo_neilian 
                                                    WHERE keywords NOT IN({$placeholder_string}) 
                                                    AND sort = 0 
                                                    ORDER BY id DESC", $tag_names),
                                            ARRAY_A
                                        );
                                    } else {
                                        $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort=0  order by id desc", ARRAY_A);
                                    }
                                } else {
                                    $post1 = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "baiduseo_neilian where sort=0  order by id desc", ARRAY_A);
                                }
                            }

                            if (!empty($post1)) {
                                foreach ($post1 as $key => $val) {
                                    if ($val['target'] == 1) {
                                        $target = 'target=_blank';
                                    } else {
                                        $target = '';
                                    }
                                    if ($val['nofollow'] == 1) {
                                        $nofollow = 'rel="nofollow"';
                                    } else {
                                        $nofollow = '';
                                    }
                                    if (isset($Tag_manage['hremove']) && $Tag_manage['hremove'] == 1) {
                                        if (preg_match('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', $content, $matches)) {
                                            $nladdnum++;
                                            if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {

                                                if ($Tag_manage['bold'] == 1) {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b style="color:' . $Tag_manage['color'] . '">' . $val['keywords'] . '</b></a>', $content, 1);
                                                } else {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                                }
                                            } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || (!$Tag_manage['color']))) {
                                                if ($Tag_manage['bold'] == 1) {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b>' . $val['keywords'] . '</b></a>', $content, 1);
                                                } else {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                                }
                                            } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            } else {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            }
                                        }
                                    } else {
                                        if (preg_match('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', $content, $matches)) {
                                            $nladdnum++;
                                            if (isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {

                                                if ($Tag_manage['bold'] == 1) {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b style="color:' . $Tag_manage['color'] . '">' . $val['keywords'] . '</b></a>', $content, 1);
                                                } else {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                                }
                                            } elseif (isset($Tag_manage['bold']) && (!isset($Tag_manage['color']) || (!$Tag_manage['color']))) {
                                                if ($Tag_manage['bold'] == 1) {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '><b>' . $val['keywords'] . '</b></a>', $content, 1);
                                                } else {

                                                    $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                                }
                                            } elseif (!isset($Tag_manage['bold']) && isset($Tag_manage['color']) && $Tag_manage['color']) {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" style="color:' . $Tag_manage['color'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            } else {
                                                $content = preg_replace('{(?!((<.*?)|(<a.*?)))(' . baiduseo_tag::BaiduSEO_preg($val['keywords']) . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i', '<a href="' . $val['link'] . '" ' . $target . ' ' . $nofollow . '>' . $val['keywords'] . '</a>', $content, 1);
                                            }
                                        }
                                    }
                                    if (isset($Tag_manage['nlnum']) && $Tag_manage['nlnum'] != 11 && $nladdnum >= $Tag_manage['nlnum']) {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $content;
    }
    public  function baiduseo_addpages()
    {
        add_menu_page(__('SEO合集', 'baiduseo'), __('SEO合集', 'baiduseo'), 'manage_options', 'baiduseo', [$this, 'baiduseo_toplevelpage']);
    }
    public function baiduseo_toplevelpage()
    {
        echo "<div id='baiduseo_wztkj-app'></div>";
    }
    public  function baiduseo_enqueue($hook)
    {
        if ('toplevel_page_baiduseo' != $hook) return;
        require plugin_dir_path(BAIDUSEO_FILE) . 'inc/admin/assets.php';
        foreach ($baiduseo_assets as $key => $val) {
            if ($val['type'] == 'css') {
                wp_enqueue_style($val['name'],  plugin_dir_url(BAIDUSEO_FILE) . 'inc/admin/' . $val['url'], array(), BAIDUSEO_VERSION, 'all');
            } elseif ($val['type'] == 'js') {
                wp_enqueue_script($val['name'], plugin_dir_url(BAIDUSEO_FILE) . 'inc/admin/' . $val['url'], array(), BAIDUSEO_VERSION, true);
            }
        }
        wp_register_script('baiduseo.js', false, array(), BAIDUSEO_VERSION, false);
        wp_enqueue_script('baiduseo.js');
        $url1 = baiduseo_common::baiduseo_url(0);
        $baiduseo_yindao = get_option('baiduseo_yindao');
        $baiduseo_yindao = $baiduseo_yindao ? $baiduseo_yindao : 0;
        $baiduseo_version  = esc_url_raw(admin_url('plugin-install.php?tab=plugin-information&plugin=baiduseo'));
        $baiduseo_indexnow = md5(esc_url(baiduseo_common::baiduseo_url(1)));
        $baiduseo_aiarticle =  esc_url_raw(admin_url('plugin-install.php?tab=plugin-information&plugin=aiarticle'));
        $baiduseo_google = baiduseo_common::baiduseo_url(1) . '/wp-sitemap.xml';
        wp_add_inline_script('baiduseo.js', 'var baiduseo_wztkj_url="' . esc_js(plugins_url('', BAIDUSEO_FILE)) . '/inc/admin",baiduseo_nonce="' . esc_attr(wp_create_nonce('baiduseo')) . '",baiduseo_ajax="' . esc_url(admin_url('admin-ajax.php')) . '",baiduseo_tag ="' . esc_url(admin_url('edit-tags.php?taxonomy=post_tag')) . '",baiduseo_url="' . esc_url($url1) . '",baiduseo_yindao=' . (int)$baiduseo_yindao . ',baiduseo_v="' . esc_url($baiduseo_version) . '",baiduseo_indexnow="' . esc_attr($baiduseo_indexnow) . '",baiduseo_google="' . esc_url($baiduseo_google) . '",baiduseo_aiarticle="'.esc_url($baiduseo_aiarticle).'";', 'before');
    }
    public  function baiduseo_plugin_action_links($links)
    {
        $links[] = '<a href="' . admin_url('admin.php?page=baiduseo&nonce=' . esc_attr(wp_create_nonce('baiduseo'))) . '">设置</a>';
        return $links;
    }
    public function baiduseo_articlepublish_ts($post_ID, $post, $update)
    {
        $baiduseo_wzt_log = baiduseo_kp::baiduseo_wzt_log();
        if (!$baiduseo_wzt_log) {
            return;
        }
        if (wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
            return;
        }

        if ($post->post_status !== 'publish') {
            return;
        }

        global $wpdb;

        // 直接使用WPDB查询和更新
        $option_name = 'baiduseo_my_minute_task';

        // 查询现有数据
        $result = $wpdb->get_var($wpdb->prepare(
            "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s",
            $option_name
        ));

        $current_tasks = [];

        if ($result) {
            // 反序列化数据
            $unserialized = unserialize($result);
            if ($unserialized !== false && is_array($unserialized)) {
                $current_tasks = $unserialized;
            } else {
                // 尝试JSON解码
                $decoded = json_decode($result, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    $current_tasks = $decoded;
                }
            }
        }

        // 确保是数组
        if (!is_array($current_tasks)) {
            $current_tasks = [];
        }

        // 检查是否已经存在
        if (!in_array($post_ID, $current_tasks)) {
            $current_tasks[] = $post_ID;

            // 直接插入或更新数据库
            if ($result) {
                // 更新现有记录
                $wpdb->update(
                    $wpdb->options,
                    [
                        'option_value' => serialize($current_tasks),
                        'autoload' => 'no'
                    ],
                    ['option_name' => $option_name],
                    ['%s', '%s'],
                    ['%s']
                );
            } else {
                // 插入新记录
                $wpdb->insert(
                    $wpdb->options,
                    [
                        'option_name' => $option_name,
                        'option_value' => serialize($current_tasks),
                        'autoload' => 'no'
                    ],
                    ['%s', '%s', '%s']
                );
            }
        }
    }
    public function baiduseo_articlepublish($post_ID)
    {
        global $wpdb;
        $baiduseo_wzt_log = baiduseo_kp::baiduseo_wzt_log();
        // 1. 基础检查
        if (!$baiduseo_wzt_log) {
            return;
        }

        // 2. 获取文章对象和类型，为动态处理做准备
        $post = get_post($post_ID);
        if (!$post) {
            return; // 如果文章不存在，则退出
        }
        $post_type = $post->post_type;
        $post_content = $post->post_content;

        // 3. 动态获取当前文章类型支持的“标签”分类法 (非层级分类法)
        $taxonomies = get_object_taxonomies($post_type, 'names');
        $tag_taxonomies = '';
        foreach ($taxonomies as $tax) {
            if (!is_taxonomy_hierarchical($tax)) {
                $tag_taxonomies = $tax;
                break;
            }
        }

        // 如果该文章类型没有任何标签分类法，则无需继续执行
        if (!$tag_taxonomies) {
            return;
        }
        $current_taxonomy = $tag_taxonomies;

        // 4. 读取插件设置
        $baiduseo_tag = get_option('baiduseo_tag');

        // 准备标签列表（根据设置排序）
        if (isset($baiduseo_tag['pp']) && $baiduseo_tag['pp'] == 1) {
            $tags = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'terms ORDER BY LENGTH(name) DESC', ARRAY_A);
        } elseif (isset($baiduseo_tag['pp']) && $baiduseo_tag['pp'] == 2) {
            $tags = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'terms ORDER BY LENGTH(name) ASC', ARRAY_A);
        } else {
            $tags = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'terms', ARRAY_A);
        }

        // 性能优化：提前准备好正则表达式的模式
        $hremove_regex = isset($baiduseo_tag['hremove']) && $baiduseo_tag['hremove'] == 1;

        // 5. 执行标签添加逻辑
        // 情况A：不限制标签数量，或数量设置为11
        if (!isset($baiduseo_tag['num']) || !$baiduseo_tag['num'] || $baiduseo_tag['num'] == 11) {
            foreach ($tags as $v) {
                // 检查该术语是否属于当前文章类型的标签分类法
                $term_in_tax = $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}term_taxonomy WHERE taxonomy = %s AND term_id = %d",
                    $current_taxonomy,
                    $v['term_id']
                ));
                if (!$term_in_tax) {
                    continue;
                }

                // 构建正则表达式
                $term_regex = baiduseo_tag::BaiduSEO_preg($v['name']);
                if ($hremove_regex) {
                    $pattern = '{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . $term_regex . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i';
                } else {
                    $pattern = '{(?!((<.*?)|(<a.*?)))(' . $term_regex . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i';
                }

                if (preg_match($pattern, $post_content, $matches)) {
                    // 获取 term_taxonomy_id
                    $tt_id = $wpdb->get_var($wpdb->prepare(
                        "SELECT term_taxonomy_id FROM {$wpdb->prefix}term_taxonomy WHERE taxonomy = %s AND term_id = %d",
                        $current_taxonomy,
                        $v['term_id']
                    ));

                    if ($tt_id) {
                        // 检查该标签是否已与文章关联
                        $is_attached = $wpdb->get_var($wpdb->prepare(
                            "SELECT COUNT(*) FROM {$wpdb->prefix}term_relationships WHERE object_id = %d AND term_taxonomy_id = %d",
                            $post_ID,
                            $tt_id
                        ));
                        if (!$is_attached) {
                            // 添加关联
                            $wpdb->insert($wpdb->prefix . "term_relationships", [
                                'object_id' => $post_ID,
                                'term_taxonomy_id' => $tt_id
                            ]);
                            // 更新计数
                            $wpdb->query($wpdb->prepare(
                                "UPDATE {$wpdb->prefix}term_taxonomy SET count = count + 1 WHERE term_taxonomy_id = %d",
                                $tt_id
                            ));
                        }
                    }
                }
            }
        }
        // 情况B：限制标签数量
        else {
            $max_tags = (int)$baiduseo_tag['num'];
            // 获取当前文章已有的标签数量
            $existing_terms_count = wp_get_object_terms($post_ID, $current_taxonomy, array('fields' => 'ids'));
            $existing_terms_count = is_array($existing_terms_count) ? count($existing_terms_count) : 0;

            if ($existing_terms_count < $max_tags) {
                foreach ($tags as $v) {
                    // 如果已达到标签数量上限，则停止循环
                    if ($existing_terms_count >= $max_tags) {
                        break;
                    }

                    // 检查该术语是否属于当前文章类型的标签分类法
                    $term_in_tax = $wpdb->get_var($wpdb->prepare(
                        "SELECT COUNT(*) FROM {$wpdb->prefix}term_taxonomy WHERE taxonomy = %s AND term_id = %d",
                        $current_taxonomy,
                        $v['term_id']
                    ));
                    if (!$term_in_tax) {
                        continue;
                    }

                    // 构建正则表达式
                    $term_regex = baiduseo_tag::BaiduSEO_preg($v['name']);
                    if ($hremove_regex) {
                        $pattern = '{(?!((<.*?)|(<a.*?)|(<h[1-6].*?>)))(' . $term_regex . ')(?!(([^<>]*?)>)|([^>]*?<\/a>)|([^>]*?<\/h[1-6]>))}i';
                    } else {
                        $pattern = '{(?!((<.*?)|(<a.*?)))(' . $term_regex . ')(?!(([^<>]*?)>)|([^>]*?<\/a>))}i';
                    }

                    if (preg_match($pattern, $post_content, $matches)) {
                        // 获取 term_taxonomy_id
                        $tt_id = $wpdb->get_var($wpdb->prepare(
                            "SELECT term_taxonomy_id FROM {$wpdb->prefix}term_taxonomy WHERE taxonomy = %s AND term_id = %d",
                            $current_taxonomy,
                            $v['term_id']
                        ));

                        if ($tt_id) {
                            // 检查该标签是否已与文章关联
                            $is_attached = $wpdb->get_var($wpdb->prepare(
                                "SELECT COUNT(*) FROM {$wpdb->prefix}term_relationships WHERE object_id = %d AND term_taxonomy_id = %d",
                                $post_ID,
                                $tt_id
                            ));
                            if (!$is_attached) {
                                // 添加关联
                                $wpdb->insert($wpdb->prefix . "term_relationships", [
                                    'object_id' => $post_ID,
                                    'term_taxonomy_id' => $tt_id
                                ]);
                                // 更新计数
                                $wpdb->query($wpdb->prepare(
                                    "UPDATE {$wpdb->prefix}term_taxonomy SET count = count + 1 WHERE term_taxonomy_id = %d",
                                    $tt_id
                                ));
                                // 更新已添加标签计数
                                $existing_terms_count++;
                            }
                        }
                    }
                }
            }
        }
    }
    public static function baiduseo_url($type = 0)
    {
        if ($type == 1) {
            $url1 = get_option('siteurl');
            $url1 = wp_parse_url($url1);
            $url1 = $url1['scheme'] . '://' . $url1['host'];
            return $url1;
        } else {
            $url1 = get_option('siteurl');
            $url1 = str_replace('https://', '', $url1);
            $url1 = str_replace('http://', '', $url1);
            $url1 = trim($url1, '/');
            $url1 = explode('/', $url1);
            return $url1[0];
        }
    }
    public static function baiduseo_get_token()
    {
        $baiduseo_wzt_token1 = get_option('baiduseo_wzt_token1');
        $baiduseo_wzt_token2 = get_option('baiduseo_wzt_token2');
        $baiduseo_wzt_token3 = get_option('baiduseo_wzt_token3');
        return [$baiduseo_wzt_token1, $baiduseo_wzt_token2, $baiduseo_wzt_token3];
    }
    public static function baiduseo_tongxun()
    {
        $baiduseo_tongxun = get_option('baiduseo_tongxun');
        if ($baiduseo_tongxun !== false) {
            return $baiduseo_tongxun;
        } else {
            $siteurl = get_option('siteurl');
            $code = time() . wp_rand(1, 999999) . $siteurl;
            $code = md5($code);
            add_option('baiduseo_tongxun', $code);
            return $code;
        }
    }
}
