<?php
if(!defined('ABSPATH'))exit;
class baiduseo_seo{
    public function init(){
         if(is_admin()){
            global $wpdb;
            $charset_collate = '';
            if (!empty($wpdb->charset)) {
              $charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}";
            }
            if (!empty( $wpdb->collate)) {
              $charset_collate .= " COLLATE {$wpdb->collate}";
            }
            if ( ! function_exists( 'dbDelta' ) ) {
                require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
            }
            if($wpdb->get_var("show tables like '{$wpdb->prefix}baiduseo_ai_lishi'") !=  $wpdb->prefix."baiduseo_ai_lishi"){
                $sql15 = "CREATE TABLE " . $wpdb->prefix . "baiduseo_ai_lishi   (
                    id bigint NOT NULL AUTO_INCREMENT,
                    hexin varchar(255) NOT NULL ,
                    guangjianci varchar(255) NOT NULL,
                    riqi timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    neirong text,
                    jifen varchar(255) DEFAULT -0.35,
                    UNIQUE KEY id (id)
                ) $charset_collate;";
                dbDelta($sql15);
            }
            $res = $wpdb->query('Describe '.$wpdb->prefix.'baiduseo_ai_lishi jifen');
            
            if($res){
                 
            }else{
               $wpdb->query(' ALTER TABLE '.$wpdb->prefix.'baiduseo_ai_lishi ADD COLUMN `jifen` varchar(255) DEFAULT "-0.35"');
            }
             if($wpdb->get_var("show tables like '{$wpdb->prefix}baiduseo_wzjc'") !=  $wpdb->prefix."baiduseo_wzjc"){
                $sql15 = "CREATE TABLE " . $wpdb->prefix . "baiduseo_wzjc   (
                    id bigint NOT NULL AUTO_INCREMENT,
                    url varchar(255) NOT NULL ,
                    url1 varchar(255) NOT NULL ,
                    content varchar(255) NOT NULL,
                    level tinyint default 1,
                    txt text,
                    UNIQUE KEY id (id)
                ) $charset_collate;";
                dbDelta($sql15);
            }
        }
        $this->baiduseo_clear();
        
    }
    public function baiduseo_clear(){
        $baiduseo_clear = get_option('baiduseo_clear');
        if(!$baiduseo_clear || (isset($baiduseo_clear['time']) && $baiduseo_clear['time']<time()) ){
            
            $data =  baiduseo_common::baiduseo_url(0);
            
            
        	$url = "https://api.seoceo.cn/api/baiduseo/index1?url={$data}&type=1";
            
        	$defaults = array(
                'timeout' => 4000,
                'connecttimeout'=>4000,
                'redirection' => 3,
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
                'sslverify' => FALSE,
            );
            $result = wp_remote_get($url,$defaults);
            if(!is_wp_error($result)){
                $result = wp_remote_retrieve_body($result);
                 $baiduseo_wzt_log = get_option('baiduseo_wzt_log');
                if($baiduseo_wzt_log!=$result){
                    delete_option('baiduseo_wzt_token3');
                    delete_option('baiduseo_wzt_token2');
                    delete_option('baiduseo_wzt_token1');
                }
            }
            if($baiduseo_clear!==false){
                update_option('baiduseo_clear',['time'=>time()+3*3600*24]);
            }else{
                add_option('baiduseo_clear',['time'=>time()+3*3600*24]);
            }
        }
    }
    public static function seo_index($key,$des){
        $seo_init = get_option('seo_init');
        if($seo_init!==false){
            update_option('seo_init',['keywords'=>$key,'description'=>$des]);
        }else{
            add_option('seo_init',['keywords'=>$key,'description'=>$des]);
        }  
    }
    public static function baiduseo_sanitizing_key($key,$arr){
        foreach ($arr as $item) {
            if (is_string($key) && strpos($key, $item) !== false) {
                return $key;
            }
        }
        return 0;
    }
    public static function baiduseo_sanitizing_date($key){
        if (strlen($key) !== 104) {
            return false;
        }
    
        // 提取各部分
        $a = substr($key, 32, 2);
        $b = substr($key, 66, 2);
        $c = substr($key, 100, 4);
        $today = date_i18n('Ymd', current_time('timestamp'));
        $num = $c.$b.$a;
        if((int)$num>(int)$today){
            return $key;
        }
        return 0;
    }
    public static function sanitizing_json($data){
        $arr = [];
        $data = json_decode($data,true);
       
        if(is_array($data)){
            $BaiduSEO = isset($data['BaiduSEO'])?(int)$data['BaiduSEO']:0;
           
            switch ($BaiduSEO) {
               
                case 37:
                    $arr['BaiduSEO'] = 37;
                   
                    $arr['wyc'] = [
                        'wp_id'=>(int)$data['wyc']['wp_id'],
                        'content_edit'=>wp_kses_post($data['wyc']['content_edit']),
                        'yc'=>(int)$data['wyc']['yc'],
                        'num'=>(int)$data['wyc']['num'],
                        'endtime'=>sanitize_text_field($data['wyc']['endtime']),
                        'hyc'=>(int)$data['wyc']['hyc'],
                        'gx_status'=>(int)$data['wyc']['gx_status'],
                        'kouchu'=>sanitize_text_field($data['wyc']['kouchu']),
                    ];
                    break;
                case 41:
                    $arr['BaiduSEO'] = 41;
                    $arr['wp_id'] = $data['wp_id'];
                    $arr['content'] = wp_kses_post($data['content']);
                    $arr['key'] =  sanitize_text_field($data['key']);
                    break;
                case 46:
                    $arr['BaiduSEO'] = 46;
                    $arr['daochu'] = [
                        'link'=>sanitize_url($data['daochu']['link']),
                        'guo'=>sanitize_text_field($data['daochu']['guo']),
                        'keywords'=>sanitize_text_field($data['daochu']['keywords']),
                        'size'=>sanitize_text_field($data['daochu']['size']),
                    ];
                    break;
                case 47:
                    $arr['BaiduSEO'] = 47;
                    $arr['key'] = sanitize_text_field($data['key']);
                    break;
                case 48:
                    $arr['BaiduSEO'] = 48;
                    break;
                case 49:
                    $arr['BaiduSEO'] = 49;
                    $arr['title'] = sanitize_text_field($data['title']);
                    $arr['con'] = sanitize_textarea_field($data['content']);
                    $arr['cate'] = (int)$data['cate'];
                    $arr['is_chachong'] =(int)$data['is_chachong'];
                    $arr['is_tese'] =isset($data['is_tese'])?(int)$data['is_tese']:0;
                    $arr['is_tuku_header'] =isset($data['is_tuku_header'])?(int)$data['is_tuku_header']:0;
                    $arr['is_tuku_footer'] =isset($data['is_tuku_footer'])?(int)$data['is_tuku_footer']:0;
                    $arr['img'] = isset($data['img'])?sanitize_url($data['img']):'';
                    $arr['img1'] = isset($data['img1'])?sanitize_url($data['img1']):'';
                    $arr['author'] =  (int)$data['author'];
                    $arr['key'] =  sanitize_text_field($data['key']);
                    break;
                case 50:
                    $arr['BaiduSEO'] = 50;
                    break;
                default:
                    return 0;
                    break;
            }
            
            return $arr;
        }else{
            return 0;
        }
    }
    public static function cate_seo($key,$des,$cate){
        $seo_init = get_option('baiduseo_cate_'.$cate);
        $seo = ['keywords'=>$key,'description'=>$des];   
        if($seo_init!==false){
            update_option('baiduseo_cate_'.$cate,$seo);
        }else{
            add_option('baiduseo_cate_'.$cate,$seo);
        } 
    }
    public static function page_seo($key,$des,$page){
        $baiduseo_page = get_post_meta( $page, 'baiduseo_page', true );
        $seo = ['keywords'=>$key,'description'=>$des]; 
        update_post_meta($page,'baiduseo_page',$seo);
        
    }
    public static function page_404(){
        WP_Filesystem();
        global $wp_filesystem;
       
        $wp_filesystem->put_contents( ABSPATH .'/404.html','<!DOCTYPE html>
            <html>
            <head>
            <meta charset="UTF-8">
            <title>System Error404</title>
            <meta name="robots" content="noindex,nofollow" />
            <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
            <style>
                    /* Base */
                    body {
                        color: #333;
                        font: 14px Verdana, "Helvetica Neue", helvetica, Arial, "Microsoft YaHei", sans-serif;
                        margin: 0;
                        padding: 0 20px 20px;
                        word-break: break-word;
                    }
                    h1{
                        margin: 10px 0 0;
                        font-size: 28px;
                        font-weight: 500;
                        line-height: 32px;
                    }
                    h2{
                        color: #4288ce;
                        font-weight: 400;
                        padding: 6px 0;
                        margin: 6px 0 0;
                        font-size: 18px;
                        border-bottom: 1px solid #eee;
                    }
                    h3.subheading {
                        color: #4288ce;
                        margin: 6px 0 0;
                        font-weight: 400;
                    }
                    h3{
                        margin: 12px;
                        font-size: 16px;
                        font-weight: bold;
                    }
                    abbr{
                        cursor: help;
                        text-decoration: underline;
                        text-decoration-style: dotted;
                    }
                    a{
                        color: #868686;
                        cursor: pointer;
                    }
                    a:hover{
                        text-decoration: underline;
                    }
                    .line-error{
                        background: #f8cbcb;
                    }
            
                    .echo table {
                        width: 100%;
                    }
            
                    .echo pre {
                        padding: 16px;
                        overflow: auto;
                        font-size: 85%;
                        line-height: 1.45;
                        background-color: #f7f7f7;
                        border: 0;
                        border-radius: 3px;
                        font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
                    }
            
                    .echo pre > pre {
                        padding: 0;
                        margin: 0;
                    }
                    /* Layout */
                    .col-md-3 {
                        width: 25%;
                    }
                    .col-md-9 {
                        width: 75%;
                    }
                    [class^="col-md-"] {
                        float: left;
                    }
                    .clearfix {
                        clear:both;
                    }
                    @media only screen 
                    and (min-device-width : 375px) 
                    and (max-device-width : 667px) { 
                        .col-md-3,
                        .col-md-9 {
                            width: 100%;
                        }
                    }
                    /* Exception Info */
                    .exception {
                        margin-top: 20px;
                    }
                    .exception .message{
                        padding: 12px;
                        border: 1px solid #ddd;
                        border-bottom: 0 none;
                        line-height: 18px;
                        font-size:16px;
                        border-top-left-radius: 4px;
                        border-top-right-radius: 4px;
                        font-family: Consolas,"Liberation Mono",Courier,Verdana,"微软雅黑";
                    }
            
                    .exception .code{
                        float: left;
                        text-align: center;
                        color: #fff;
                        margin-right: 12px;
                        padding: 16px;
                        border-radius: 4px;
                        background: #999;
                    }
                    .exception .source-code{
                        padding: 6px;
                        border: 1px solid #ddd;
            
                        background: #f9f9f9;
                        overflow-x: auto;
            
                    }
                    .exception .source-code pre{
                        margin: 0;
                    }
                    .exception .source-code pre ol{
                        margin: 0;
                        color: #4288ce;
                        display: inline-block;
                        min-width: 100%;
                        box-sizing: border-box;
                    font-size:14px;
                        font-family: "Century Gothic",Consolas,"Liberation Mono",Courier,Verdana;
                        padding-left: 40px;
                    }
                    .exception .source-code pre li{
                        border-left: 1px solid #ddd;
                        height: 18px;
                        line-height: 18px;
                    }
                    .exception .source-code pre code{
                        color: #333;
                        height: 100%;
                        display: inline-block;
                        border-left: 1px solid #fff;
                    font-size:14px;
                        font-family: Consolas,"Liberation Mono",Courier,Verdana,"微软雅黑";
                    }
                    .exception .trace{
                        padding: 6px;
                        border: 1px solid #ddd;
                        border-top: 0 none;
                        line-height: 16px;
                    font-size:14px;
                        font-family: Consolas,"Liberation Mono",Courier,Verdana,"微软雅黑";
                    }
                    .exception .trace ol{
                        margin: 12px;
                    }
                    .exception .trace ol li{
                        padding: 2px 4px;
                    }
                    .exception div:last-child{
                        border-bottom-left-radius: 4px;
                        border-bottom-right-radius: 4px;
                    }
            
                    /* Exception Variables */
                    .exception-var table{
                        width: 100%;
                        margin: 12px 0;
                        box-sizing: border-box;
                        table-layout:fixed;
                        word-wrap:break-word;            
                    }
                    .exception-var table caption{
                        text-align: left;
                        font-size: 16px;
                        font-weight: bold;
                        padding: 6px 0;
                    }
                    .exception-var table caption small{
                        font-weight: 300;
                        display: inline-block;
                        margin-left: 10px;
                        color: #ccc;
                    }
                    .exception-var table tbody{
                        font-size: 13px;
                        font-family: Consolas,"Liberation Mono",Courier,"微软雅黑";
                    }
                    .exception-var table td{
                        padding: 0 6px;
                        vertical-align: top;
                        word-break: break-all;
                    }
                    .exception-var table td:first-child{
                        width: 28%;
                        font-weight: bold;
                        white-space: nowrap;
                    }
                    .exception-var table td pre{
                        margin: 0;
                    }
            
                    /* Copyright Info */
                    .copyright{
                        margin-top: 24px;
                        padding: 12px 0;
                        border-top: 1px solid #eee;
                    }
            
                    /* SPAN elements with the classes below are added by prettyprint. */
                    pre.prettyprint .pln { color: #000 }  /* plain text */
                    pre.prettyprint .str { color: #080 }  /* string content */
                    pre.prettyprint .kwd { color: #008 }  /* a keyword */
                    pre.prettyprint .com { color: #800 }  /* a comment */
                    pre.prettyprint .typ { color: #606 }  /* a type name */
                    pre.prettyprint .lit { color: #066 }  /* a literal value */
                    /* punctuation, lisp open bracket, lisp close bracket */
                    pre.prettyprint .pun, pre.prettyprint .opn, pre.prettyprint .clo { color: #660 }
                    pre.prettyprint .tag { color: #008 }  /* a markup tag name */
                    pre.prettyprint .atn { color: #606 }  /* a markup attribute name */
                    pre.prettyprint .atv { color: #080 }  /* a markup attribute value */
                    pre.prettyprint .dec, pre.prettyprint .var { color: #606 }  /* a declaration; a variable name */
                    pre.prettyprint .fun { color: red }  /* a function name */
                </style>
            </head>
            <body>
            <div class="echo">
            <script>setTimeout(function (){location.href="/";},2000);</script> </div>
            <div class="exception">
            <div class="info"><h1>404页面提醒您，该页面不存在！</h1></div>
            </div>
            <div class="copyright">
            </div>
            </body>
            </html>' );
        
        $seo_301_404_url = get_option('seo_301_404_url');
        if($seo_301_404_url!=false){
            update_option('seo_301_404_url',['404_url'=>1]);
        }else{
            add_option('seo_301_404_url',['404_url'=>1]);
        }
    }
    public static function robots($roobots){
        $url =trim(get_option('home'),'/').'/robots.txt';   
        $currnetTime= current_time( 'Y/m/d H:i:s');
        $robot = [                                          
            'robot'=>$roobots,                                                
            'time'=>$currnetTime,                                     
            'url'=>$url,                                        
        ];    
         WP_Filesystem();
        global $wp_filesystem;
       
        $wp_filesystem->put_contents( ABSPATH .'/robots.txt',$roobots);
        $rootbot = get_option('seo_robots_sc');
        if($rootbot){
           update_option('seo_robots_sc',$robot); 
        }else{
            add_option('seo_robots_sc',$robot);
        }
    }
    
public static function sitemap($page, $two, $tag_sl = 0)
{
    global $wpdb;

    $LIMIT = 9995;
    $home  = trim(home_url('/'),'/');

    $currnetTime  = current_time('Y/m/d H:i:s');
    $currnetTime1 = current_time('Y-m-d H:i:s');

    $sitemap = get_option('seo_baidu_sitemap');
    if (!is_array($sitemap)) {
        $sitemap = [];
    }

    // 默认值，避免未定义 key 触发 Notice，同时保证频率/优先级有兜底
    $defaults = [
        'type1' => 0, 'type2' => 0, 'type3' => 0, 'type4' => 0, 'type5' => 0,
        'level1' => 8, 'level2' => 8, 'level3' => 6, 'level4' => 8, 'level5' => 6,
        'post_time' => 'daily', 'page_time' => 'daily', 'tag_time' => 'weekly', 'other_time' => 'daily', 'cate_time' => 'weekly',
        'tag_open' => 0,
    ];
    $sitemap = array_merge($defaults, $sitemap);

    // 触发分页阈值（沿用你的原意：用 post 的发布数判断）
    $art_num = 0;
    $count_obj = wp_count_posts();
    if (is_object($count_obj) && isset($count_obj->publish)) {
        $art_num = (int) $count_obj->publish;
    }

    if ($art_num > 10000) {
        if (!isset($sitemap['sitemap_htmlurl']) || !is_array($sitemap['sitemap_htmlurl'])) {
            $sitemap['sitemap_htmlurl'] = [];
        }
        $baiduseo_sitemap_num = get_option('baiduseo_sitemap_num');
        if ($baiduseo_sitemap_num !== false) {
            $baiduseo_sitemap_num = (int) $baiduseo_sitemap_num + 1;
            update_option('baiduseo_sitemap_num', $baiduseo_sitemap_num,false);
        } else {
            $baiduseo_sitemap_num = 1;
            update_option('baiduseo_sitemap_num', 1);
        }
    } else {
        $sitemap['sitemap_url'] = [];
        $sitemap['sitemap_htmlurl'] = [];
        $baiduseo_sitemap_num = 1;
        update_option('baiduseo_sitemap_num', 1);
    }

    $data = $sitemap;
    $data['time'] = $currnetTime;

    // 工具函数：priority
    $priority_of = static function ($levelInt) {
        $p = ((float) $levelInt) / 10.0;
        if (abs($p - 1.0) < 0.00001) {
            return '1.0';
        }
        return number_format($p, 1, '.', '');
    };

    // 第1页生成 tag.html（沿用你的逻辑）
    $html_tag = '';
    if ($baiduseo_sitemap_num === 1 && (int) $sitemap['tag_open'] === 1) {
        $data['sitemap_tag'] = $home . '/tag.html';

        $tag_limit = $tag_sl ? 500 : $LIMIT;

        $tags_for_html = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT t.term_id, t.name
                 FROM {$wpdb->terms} t
                 INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                 WHERE tt.taxonomy = %s
                 ORDER BY t.term_id ASC
                 LIMIT %d",
                'post_tag',
                (int) $tag_limit
            ),
            ARRAY_A
        );

        $html_tag = "<!DOCTYPE html>\n<html>\n<head>\n<meta charset='UTF-8'>\n<meta name='viewport' content='width=device-width, initial-scale=1.0'>\n<style>\nbody {\nbackground-color: #f3f3f3;\n}\nul li {\ndisplay: inline-block;\npadding: 5px 10px;\nmargin: 5px 0px;\nbackground-color: #fff;\nborder-radius: 25px;\n}\n* {\nmargin: 0;\npadding: 0;\n}\na {\ntext-decoration: none;\ncolor: #111;\nfont-weight: 300;\n}\na:hover{\ncolor: skyblue;\n}\n</style>\n</head>\n<body>\n<ul>";
        foreach ($tags_for_html as $val) {
            $term_id = isset($val['term_id']) ? (int) $val['term_id'] : 0;
            $name    = isset($val['name']) ? (string) $val['name'] : '';
            $html_tag .= "<li><a href='" . esc_url(get_tag_link($term_id)) . "' title='" . esc_attr($name) . "'>" . esc_html($name) . "</a></li>\n";
        }
        $html_tag .= "</ul>\n</body>\n</html>";
    }

    // sitemap_url / sitemap_htmlurl（给前端展示）
    $data['sitemap_url']     = isset($data['sitemap_url']) && is_array($data['sitemap_url']) ? $data['sitemap_url'] : [];
    $data['sitemap_htmlurl'] = isset($data['sitemap_htmlurl']) && is_array($data['sitemap_htmlurl']) ? $data['sitemap_htmlurl'] : [];

    if ($baiduseo_sitemap_num > 1) {
        $page1 = $baiduseo_sitemap_num - 1;
        $xml_url = $home . '/sitemap' . $page1 . '.xml';
        if (!in_array($xml_url, $data['sitemap_url'], true)) {
            $data['sitemap_url'][] = $xml_url;
        }
    } else {
        $xml_url = $home . '/sitemap.xml';
        if (!in_array($xml_url, $data['sitemap_url'], true)) {
            $data['sitemap_url'][] = $xml_url;
        }
    }

    $html_url = $home . '/sitemap.html';
    if (!in_array($html_url, $data['sitemap_htmlurl'], true)) {
        $data['sitemap_htmlurl'][] = $html_url;
    }

    $data['sitemap_url']     = array_values(array_unique($data['sitemap_url']));
    $data['sitemap_htmlurl'] = array_values(array_unique($data['sitemap_htmlurl']));

    // === 用户选择开关 ===
    $enable_post  = ((int) $sitemap['type1'] === 1);
    $enable_page  = ((int) $sitemap['type2'] === 1);
    $enable_tag   = ((int) $sitemap['type3'] === 1);
    $enable_other = ((int) $sitemap['type4'] === 1);
    $enable_cate  = ((int) $sitemap['type5'] === 1);

    if (!$enable_post && !$enable_page && !$enable_tag && !$enable_other && !$enable_cate) {
        update_option('seo_baidu_sitemap', $data);
        update_option('baiduseo_sitemap_num', 0);
        return;
    }

    // ====== 构建资源池（安全审查：全部 prepare 字面量 SQL，不使用 $sql 变量传递）======
    $pools = [];

    // POSTS 池：用白名单分支构造 SQL（避免动态 where 字符串被判 NotPrepared）
    $post_mode = 'none';
    if ($enable_other && !$enable_post && !$enable_page) {
        $post_mode = 'only_other';
    } elseif (!$enable_other && ($enable_post || $enable_page)) {
        $post_mode = 'only_post_page';
    } elseif ($enable_other && ($enable_post || $enable_page)) {
        $post_mode = 'mixed';
    }

    if ($post_mode !== 'none') {
        // 统计 total
        if ($post_mode === 'only_other') {
            $post_total = (int) $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(1)
                     FROM {$wpdb->posts}
                     WHERE post_status = %s
                       AND post_type NOT IN ('nav_menu_item','attachment','post','page')",
                    'publish'
                )
            );

            $pools[] = [
                'key' => 'posts',
                'total' => $post_total,
                'fetch' => static function ($offset, $limit) use ($wpdb) {
                    return $wpdb->get_results(
                        $wpdb->prepare(
                            "SELECT ID, post_type, post_date
                             FROM {$wpdb->posts}
                             WHERE post_status = %s
                               AND post_type NOT IN ('nav_menu_item','attachment','post','page')
                             ORDER BY post_date DESC, ID DESC
                             LIMIT %d, %d",
                            'publish',
                            (int) $offset,
                            (int) $limit
                        ),
                        ARRAY_A
                    );
                },
            ];
        }

        if ($post_mode === 'only_post_page') {
            // 只允许 post/page 组合（白名单）
            if ($enable_post && $enable_page) {
                $post_total = (int) $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(1)
                         FROM {$wpdb->posts}
                         WHERE post_status = %s
                           AND post_type IN (%s, %s)",
                        'publish',
                        'post',
                        'page'
                    )
                );

                $pools[] = [
                    'key' => 'posts',
                    'total' => $post_total,
                    'fetch' => static function ($offset, $limit) use ($wpdb) {
                        return $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT ID, post_type, post_date
                                 FROM {$wpdb->posts}
                                 WHERE post_status = %s
                                   AND post_type IN (%s, %s)
                                 ORDER BY post_date DESC, ID DESC
                                 LIMIT %d, %d",
                                'publish',
                                'post',
                                'page',
                                (int) $offset,
                                (int) $limit
                            ),
                            ARRAY_A
                        );
                    },
                ];
            } elseif ($enable_post) {
                $post_total = (int) $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(1)
                         FROM {$wpdb->posts}
                         WHERE post_status = %s
                           AND post_type = %s",
                        'publish',
                        'post'
                    )
                );

                $pools[] = [
                    'key' => 'posts',
                    'total' => $post_total,
                    'fetch' => static function ($offset, $limit) use ($wpdb) {
                        return $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT ID, post_type, post_date
                                 FROM {$wpdb->posts}
                                 WHERE post_status = %s
                                   AND post_type = %s
                                 ORDER BY post_date DESC, ID DESC
                                 LIMIT %d, %d",
                                'publish',
                                'post',
                                (int) $offset,
                                (int) $limit
                            ),
                            ARRAY_A
                        );
                    },
                ];
            } elseif ($enable_page) {
                $post_total = (int) $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(1)
                         FROM {$wpdb->posts}
                         WHERE post_status = %s
                           AND post_type = %s",
                        'publish',
                        'page'
                    )
                );

                $pools[] = [
                    'key' => 'posts',
                    'total' => $post_total,
                    'fetch' => static function ($offset, $limit) use ($wpdb) {
                        return $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT ID, post_type, post_date
                                 FROM {$wpdb->posts}
                                 WHERE post_status = %s
                                   AND post_type = %s
                                 ORDER BY post_date DESC, ID DESC
                                 LIMIT %d, %d",
                                'publish',
                                'page',
                                (int) $offset,
                                (int) $limit
                            ),
                            ARRAY_A
                        );
                    },
                ];
            }
        }

        if ($post_mode === 'mixed') {
            // post/page + other：允许 post/page，且允许除 post/page/nav/attachment 外的其它类型
            // 白名单写死结构，避免动态 where
            if ($enable_post && $enable_page) {
                $post_total = (int) $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(1)
                         FROM {$wpdb->posts}
                         WHERE post_status = %s
                           AND post_type NOT IN ('nav_menu_item','attachment')
                           AND (
                                 post_type IN (%s, %s)
                                 OR post_type NOT IN ('nav_menu_item','attachment','post','page')
                               )",
                        'publish',
                        'post',
                        'page'
                    )
                );

                $pools[] = [
                    'key' => 'posts',
                    'total' => $post_total,
                    'fetch' => static function ($offset, $limit) use ($wpdb) {
                        return $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT ID, post_type, post_date
                                 FROM {$wpdb->posts}
                                 WHERE post_status = %s
                                   AND post_type NOT IN ('nav_menu_item','attachment')
                                   AND (
                                         post_type IN (%s, %s)
                                         OR post_type NOT IN ('nav_menu_item','attachment','post','page')
                                       )
                                 ORDER BY post_date DESC, ID DESC
                                 LIMIT %d, %d",
                                'publish',
                                'post',
                                'page',
                                (int) $offset,
                                (int) $limit
                            ),
                            ARRAY_A
                        );
                    },
                ];
            } elseif ($enable_post) {
                $post_total = (int) $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(1)
                         FROM {$wpdb->posts}
                         WHERE post_status = %s
                           AND post_type NOT IN ('nav_menu_item','attachment')
                           AND (
                                 post_type = %s
                                 OR post_type NOT IN ('nav_menu_item','attachment','post','page')
                               )",
                        'publish',
                        'post'
                    )
                );

                $pools[] = [
                    'key' => 'posts',
                    'total' => $post_total,
                    'fetch' => static function ($offset, $limit) use ($wpdb) {
                        return $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT ID, post_type, post_date
                                 FROM {$wpdb->posts}
                                 WHERE post_status = %s
                                   AND post_type NOT IN ('nav_menu_item','attachment')
                                   AND (
                                         post_type = %s
                                         OR post_type NOT IN ('nav_menu_item','attachment','post','page')
                                       )
                                 ORDER BY post_date DESC, ID DESC
                                 LIMIT %d, %d",
                                'publish',
                                'post',
                                (int) $offset,
                                (int) $limit
                            ),
                            ARRAY_A
                        );
                    },
                ];
            } elseif ($enable_page) {
                $post_total = (int) $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(1)
                         FROM {$wpdb->posts}
                         WHERE post_status = %s
                           AND post_type NOT IN ('nav_menu_item','attachment')
                           AND (
                                 post_type = %s
                                 OR post_type NOT IN ('nav_menu_item','attachment','post','page')
                               )",
                        'publish',
                        'page'
                    )
                );

                $pools[] = [
                    'key' => 'posts',
                    'total' => $post_total,
                    'fetch' => static function ($offset, $limit) use ($wpdb) {
                        return $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT ID, post_type, post_date
                                 FROM {$wpdb->posts}
                                 WHERE post_status = %s
                                   AND post_type NOT IN ('nav_menu_item','attachment')
                                   AND (
                                         post_type = %s
                                         OR post_type NOT IN ('nav_menu_item','attachment','post','page')
                                       )
                                 ORDER BY post_date DESC, ID DESC
                                 LIMIT %d, %d",
                                'publish',
                                'page',
                                (int) $offset,
                                (int) $limit
                            ),
                            ARRAY_A
                        );
                    },
                ];
            }
        }
    }

    // TAG 池
    if ($enable_tag) {
        $tag_total = (int) $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(1)
                 FROM {$wpdb->terms} t
                 INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                 WHERE tt.taxonomy = %s",
                'post_tag'
            )
        );

        $pools[] = [
            'key' => 'tag',
            'total' => $tag_total,
            'fetch' => static function ($offset, $limit) use ($wpdb) {
                return $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT t.term_id
                         FROM {$wpdb->terms} t
                         INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                         WHERE tt.taxonomy = %s
                         ORDER BY t.term_id ASC
                         LIMIT %d, %d",
                        'post_tag',
                        (int) $offset,
                        (int) $limit
                    ),
                    ARRAY_A
                );
            },
        ];
    }

    // CATEGORY 池
    if ($enable_cate) {
        $cate_total = (int) $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(1)
                 FROM {$wpdb->terms} t
                 INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                 WHERE tt.taxonomy = %s",
                'category'
            )
        );

        $pools[] = [
            'key' => 'cate',
            'total' => $cate_total,
            'fetch' => static function ($offset, $limit) use ($wpdb) {
                return $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT t.term_id
                         FROM {$wpdb->terms} t
                         INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                         WHERE tt.taxonomy = %s
                         ORDER BY t.term_id ASC
                         LIMIT %d, %d",
                        'category',
                        (int) $offset,
                        (int) $limit
                    ),
                    ARRAY_A
                );
            },
        ];
    }

    // ====== 全局线性分页（安全优先：逻辑简单，避免 start1/start2 拼公式）======
    $global_start = ($baiduseo_sitemap_num - 1) * $LIMIT;
    $remain       = $LIMIT;

    $article = [];
    $tag     = [];
    $cate    = [];

    foreach ($pools as $pool) {
        $total = (int) $pool['total'];
        if ($total <= 0) {
            continue;
        }

        if ($global_start >= $total) {
            $global_start -= $total;
            continue;
        }

        $take = min($remain, $total - $global_start);
        if ($take > 0) {
            $rows = call_user_func($pool['fetch'], $global_start, $take);

            if ($pool['key'] === 'posts') {
                $article = array_merge($article, $rows);
            } elseif ($pool['key'] === 'tag') {
                $tag = array_merge($tag, $rows);
            } elseif ($pool['key'] === 'cate') {
                $cate = array_merge($cate, $rows);
            }

            $remain -= $take;
            $global_start = 0;

            if ($remain <= 0) {
                break;
            }
        }
    }

    // 无数据：回收并归零（保留你的“前端展示”思路）
    if (!$article && !$tag && !$cate) {
        $page1 = $baiduseo_sitemap_num - 1;

        foreach ($data['sitemap_url'] as $key => $val) {
            if (strpos($val, $home . '/sitemap') === 0 && substr($val, -4) === '.xml') {
                $n = str_replace([$home . '/sitemap', '.xml'], ['', ''], $val);
                if ($n !== '' && ctype_digit((string)$n)) {
                    $num = (int) $n;
                    if ($num >= $page1 && $page1 > 0) {
                        unset($data['sitemap_url'][$key]);
                    }
                }
            }
        }

        $data['sitemap_url'] = array_values(array_unique($data['sitemap_url']));
        $data['sitemap_htmlurl'] = array_values(array_unique($data['sitemap_htmlurl']));

        update_option('seo_baidu_sitemap', $data);
        update_option('baiduseo_sitemap_num', 0);
        return;
    }

    // ====== 生成 XML（严格使用你的优先级/频率配置）======
    $xml  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    $xml .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

    if ($baiduseo_sitemap_num === 1) {
        $xml .= "<url>\n";
        $xml .= "<loc>" . htmlspecialchars(esc_url_raw($home), ENT_QUOTES) . "</loc>\n";
        $xml .= "<lastmod>{$currnetTime1}</lastmod>\n";
        $xml .= "<changefreq>daily</changefreq>\n";
        $xml .= "<priority>1.0</priority>\n";
        $xml .= "</url>\n";
    }

    if ($article) {
        foreach ($article as $val) {
            $post_type = isset($val['post_type']) ? (string) $val['post_type'] : '';

            if ($post_type === 'post') {
                $priority = $priority_of($sitemap['level1']);
                $freq     = (string) $sitemap['post_time'];
            } elseif ($post_type === 'page') {
                $priority = $priority_of($sitemap['level2']);
                $freq     = (string) $sitemap['page_time'];
            } else {
                $priority = $priority_of($sitemap['level4']);
                $freq     = (string) $sitemap['other_time'];
            }

            $loc = esc_url_raw(get_permalink((int) $val['ID']));
            $lastmod = isset($val['post_date']) ? (string) $val['post_date'] : $currnetTime1;

            $xml .= "<url>\n";
            $xml .= "<loc>" . htmlspecialchars($loc, ENT_QUOTES) . "</loc>\n";
            $xml .= "<lastmod>{$lastmod}</lastmod>\n";
            $xml .= "<changefreq>{$freq}</changefreq>\n";
            $xml .= "<priority>{$priority}</priority>\n";
            $xml .= "</url>\n";
        }
    }

    if ($tag) {
        $priority = $priority_of($sitemap['level3']);
        $freq     = (string) $sitemap['tag_time'];

        foreach ($tag as $val) {
            $loc = get_term_link((int) $val['term_id']);
            if (is_wp_error($loc)) {
                continue;
            }
            $xml .= "<url>\n";
            $xml .= "<loc>" . htmlspecialchars($loc, ENT_QUOTES) . "</loc>\n";
            $xml .= "<changefreq>{$freq}</changefreq>\n";
            $xml .= "<priority>{$priority}</priority>\n";
            $xml .= "</url>\n";
        }
    }

    if ($cate) {
        $priority = $priority_of($sitemap['level5']);
        $freq     = (string) $sitemap['cate_time'];

        foreach ($cate as $val) {
            $loc = get_term_link((int) $val['term_id']);
            if (is_wp_error($loc)) {
                continue;
            }
            $xml .= "<url>\n";
            $xml .= "<loc>" . htmlspecialchars($loc, ENT_QUOTES) . "</loc>\n";
            $xml .= "<changefreq>{$freq}</changefreq>\n";
            $xml .= "<priority>{$priority}</priority>\n";
            $xml .= "</url>\n";
        }
    }

    $xml .= "</urlset>";

    // ====== 写文件 ======
    if (!function_exists('WP_Filesystem')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    WP_Filesystem();
    global $wp_filesystem;

    // sitemap.html（保留原分类树，补上 prepare 与必要转义）
    $html = "<!DOCTYPE html>\n<html>\n<head>\n<meta charset='UTF-8'>\n<meta name='viewport' content='width=device-width, initial-scale=1.0'><style>\nbody {\nbackground-color: #f3f3f3;\n}\nul {\nbackground-color: #fff;\nmax-width: 1200px;\nmargin: 0 auto;\nbox-sizing: border-box;\npadding: 15px 125px;\n}\nul li {\npadding: 15px 0;\n}\nul li a {\ncolor: #333;\npadding-left: 25px;\ntext-decoration: none;\n}\nbody>ul>li>a{\nfont-weight:bold\n}\n</style>\n</head>\n<body>\n<ul >";

    $category0 = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT t.term_id, t.name, tt.parent
             FROM {$wpdb->terms} t
             INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
             WHERE tt.taxonomy = %s AND tt.parent = %d
             ORDER BY t.term_id DESC
             LIMIT %d",
            'category',
            0,
            1000
        ),
        ARRAY_A
    );

    $html .= "<li><a href='/' target='_blank'>首 页</a></li>\n";

    foreach ($category0 as $val) {
        $term0 = (int) $val['term_id'];
        $name0 = isset($val['name']) ? (string) $val['name'] : '';

        $children1 = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT t.term_id, t.name, tt.parent
                 FROM {$wpdb->terms} t
                 INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                 WHERE tt.taxonomy = %s AND tt.parent = %d
                 ORDER BY t.term_id DESC
                 LIMIT %d",
                'category',
                $term0,
                1000
            ),
            ARRAY_A
        );

        if (!empty($children1)) {
            $html .= "<li><a href='" . esc_url(get_category_link($term0)) . "' target='_blank'>" . esc_html($name0) . "</a>\n<ul>";
            foreach ($children1 as $c1) {
                $term1 = (int) $c1['term_id'];
                $name1 = isset($c1['name']) ? (string) $c1['name'] : '';

                $children2 = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT t.term_id, t.name, tt.parent
                         FROM {$wpdb->terms} t
                         INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                         WHERE tt.taxonomy = %s AND tt.parent = %d
                         ORDER BY t.term_id DESC
                         LIMIT %d",
                        'category',
                        $term1,
                        1000
                    ),
                    ARRAY_A
                );

                if (!empty($children2)) {
                    $html .= "<li><a href='" . esc_url(get_category_link($term1)) . "' target='_blank'>" . esc_html($name1) . "</a>\n<ul>";
                    foreach ($children2 as $c2) {
                        $term2 = (int) $c2['term_id'];
                        $name2 = isset($c2['name']) ? (string) $c2['name'] : '';
                        $html .= "<li><a href='" . esc_url(get_category_link($term2)) . "' target='_blank'>" . esc_html($name2) . "</a></li>\n";
                    }
                    $html .= "</ul>\n</li>";
                } else {
                    $html .= "<li><a href='" . esc_url(get_category_link($term1)) . "' target='_blank'>" . esc_html($name1) . "</a></li>\n";
                }
            }
            $html .= "</ul>\n</li>\n";
        } else {
            $html .= "<li><a href='" . esc_url(get_category_link($term0)) . "' target='_blank'>" . esc_html($name0) . "</a></li>\n";
        }
    }

    $html .= "</ul>\n</body>\n</html>";

    if ($baiduseo_sitemap_num > 1) {
        $page1 = $baiduseo_sitemap_num - 1;
        $result = $wp_filesystem->put_contents(ABSPATH . "/sitemap{$page1}.xml", $xml);
        if($result=== false){
            return;
        }
    } else {
        if ((int) $sitemap['tag_open'] === 1 && $html_tag !== '') {
            $wp_filesystem->put_contents(ABSPATH . "/tag.html", $html_tag);
        }
        $result = $wp_filesystem->put_contents(ABSPATH . "/sitemap.xml", $xml);
        if($result=== false){
            return;
        }
    }

    $result = $wp_filesystem->put_contents(ABSPATH . "/sitemap.html", $html);
    if($result=== false){
        return;
    }

    // 写回 option（前端展示需要）
    update_option('seo_baidu_sitemap', $data,false);
}
    public static function silian($two,$sl=0){
         global $wpdb;
        //$two==2后端$two==1前端 
        $silian = get_option('seo_baidu_silian');
        $currnetTime= current_time( 'Y/m/d H:i:s');
            
            $data = [                                               
                'silian_url'=>[],                                                
                'silian_htmlurl'=>[],                                          
                'time'=>$currnetTime                                     
            ];
            if($sl){
                $count = $wpdb->query('select * from '.$wpdb->prefix . 'baiduseo_zhizhu where  type="404" group by address limit 500',ARRAY_A);
            }else{
                $count = $wpdb->query('select * from '.$wpdb->prefix . 'baiduseo_zhizhu where  type="404" group by address',ARRAY_A);
            }
            
            for($i=0;$i<ceil($count/50000);$i++){
                $start = $i*50000;
                if($sl){
                    $zhizhu = $wpdb->get_results($wpdb->prepare('select * from '.$wpdb->prefix . 'baiduseo_zhizhu where  type="404"  group by address limit %d , 500',$start),ARRAY_A);
                }else{
                    $zhizhu = $wpdb->get_results($wpdb->prepare('select * from '.$wpdb->prefix . 'baiduseo_zhizhu where  type="404"  group by address limit %d , 50000',$start),ARRAY_A);
                }
                
                $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
                $xml .= "<urlset>\n";
                $txt = '';
                foreach($zhizhu as $key=>$val){
                    $url = get_option('home');
                    $url1 = trim($url,'/');
                    if(is_string($val['address']) && strpos($val['address'], $url1) !== false) {
                        $xml .= "<url>\n";
                        $xml .= "<loc>".htmlspecialchars($val['address'])."</loc>\n";
                        $xml .= "</url>\n";
                        $txt .=$val['address']."\n";
                  
                    }
                    
                }
                 WP_Filesystem();
                global $wp_filesystem;
                $xml .= "</urlset>\n";
                if($two==2){
                    if($i==0){
                        $data['silian_url'][] = get_option('home'). '/silian.xml';
                        $data['silian_htmlurl'][] = get_option('home'). '/silian.txt';
                        $wp_filesystem->put_contents ('../silian.xml',$xml);
                        $wp_filesystem->put_contents ('../silian.txt',$txt);
                    }else{
                        $data['silian_url'][] = get_option('home'). '/silian'.$i.'.xml';
                        $data['silian_htmlurl'][] = get_option('home'). '/silian'.$i.'.txt';
                        $wp_filesystem->put_contents ('../silian'.$i.'.xml',$xml);
                        $wp_filesystem->put_contents ('../silian'.$i.'.txt',$txt);
                    }
                }elseif($two==1){
                    if($i==0){
                        $data['silian_url'][] = get_option('home'). '/silian.xml';
                         $data['silian_htmlurl'][] = get_option('home'). '/silian.txt';
                        $wp_filesystem->put_contents (ABSPATH.'/silian.xml',$xml);
                        $wp_filesystem->put_contents (ABSPATH.'/silian.txt',$txt);
                    }else{
                        $data['silian_url'][] = get_option('home'). '/silian'.$i.'.xml';
                        $data['silian_htmlurl'][] = get_option('home'). '/silian'.$i.'.txt';
                        $wp_filesystem->put_contents (ABSPATH.'/silian'.$i.'.xml',$xml);
                        $wp_filesystem->put_contents (ABSPATH.'/silian'.$i.'.txt',$txt);
                    }
                }
            }
            if($silian!==false){
                update_option('seo_baidu_silian',$data);
            }else{
                add_option('seo_baidu_silian',$data);
            }
    }
    public static function alt($alt,$title){
        $seo_alt_auto = get_option('seo_alt_auto');
        $alt_seo = ['alt'=>$alt,'title'=>$title];
        if($seo_alt_auto!==false){
            update_option('seo_alt_auto',$alt_seo);
        }else{
            add_option('seo_alt_auto',$alt_seo);
        }
    }
    public static function pay_money(){
    $baiduseo_wzt_log = baiduseo_kp::baiduseo_wzt_log();
    if(!$baiduseo_wzt_log){
        return 0;
    }

    $data = baiduseo_common::baiduseo_url(0);
    $defaults = array(
        'timeout' => 4000,
        'connecttimeout' => 4000,
        'redirection' => 3,
        'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
        'sslverify' => FALSE,
    );

    // 1. 定义服务器地址（移除失败次数相关逻辑）
    $primary_server_url = "https://api.seoceo.cn/api/index/pay_money?url={$data}&type=1&log={$baiduseo_wzt_log}";
    $backup_server_url = "https://www.seoceo.cn/api/money/pay_money?url={$data}&type=1&log={$baiduseo_wzt_log}";

    // 2. 先请求主服务器
    $result = wp_remote_get($primary_server_url, $defaults);
    $is_backup_used = false;

    // 3. 主服务器请求失败（网络/502等错误），立即切换到备用服务器重试
    if (is_wp_error($result)) {
        $result = wp_remote_get($backup_server_url, $defaults);
        $is_backup_used = true;
        // 备用服务器也失败，直接返回0
        if (is_wp_error($result)) {
            return 0;
        }
    }

    // 4. 处理服务器返回的内容
    $content = wp_remote_retrieve_body($result);
    $content = json_decode($content, true);

    // 检查返回数据格式是否有效
    if (!isset($content['status'])) {
        // 主服务器返回格式错误，立即重试备用服务器
        if (!$is_backup_used) {
            $result = wp_remote_get($backup_server_url, $defaults);
            $is_backup_used = true;
            // 备用服务器也失败/格式错误
            if (is_wp_error($result)) {
                return 0;
            }
            $content = wp_remote_retrieve_body($result);
            $content = json_decode($content, true);
            // 备用服务器返回格式仍错误，返回0
            if (!isset($content['status'])) {
                return 0;
            }
        } else {
            // 已经是备用服务器，格式错误直接返回0
            return 0;
        }
    }

    // 5. 业务逻辑成功 (status = 1)
    if ($content['status'] == 1) {
        // 只有主服务器返回成功时才保存Token
        if (!$is_backup_used) {
            if (isset($content['token1']) && $content['token1']) {
                update_option('baiduseo_wzt_token1', $content['token1'], false);
            }
            if (isset($content['token2']) && $content['token2']) {
                update_option('baiduseo_wzt_token2', $content['token2'], false);
            }
            if (isset($content['token3']) && $content['token3']) {
                update_option('baiduseo_wzt_token3', $content['token3'], false);
            }
        }
        return 1;
    }
    // 6. 业务逻辑失败 (status = 0)
    elseif ($content['status'] == 0) {
        return 0; 
    }

    // 所有其他未预料到的情况
    return 0;
}
    public static function baiduseo_friends_hh($key){
        if(md5(baiduseo_common::baiduseo_url(0))==$key){
            global $wpdb;
            $wztkj_linkhh = get_option('baiduseo_linkhh');
            if(isset($wztkj_linkhh['kqtype']) && $wztkj_linkhh['kqtype']==2){
                $friends = $wpdb->get_results('select * from '.$wpdb->prefix . 'wztkj_friends where (status1=0 and status2=0 and status3=2) or status1=5',ARRAY_A);
            }else{
                $friends = $wpdb->get_results('select * from '.$wpdb->prefix . 'wztkj_friends where (status1=0 and status2=0) or status1=5',ARRAY_A);
            }
            echo '<span style="display:none">'.esc_attr(md5(baiduseo_common::baiduseo_url(0))).'</span>';
            
            if (isset($wztkj_linkhh['ystype']) && $wztkj_linkhh['ystype'] == 1) {
                if(isset($wztkj_linkhh['link']) && $wztkj_linkhh['link']){
                    echo '
                        <style>
                            .baiduseo_linkhh_box {
                                width: var(--container-width, 100%);
                                margin: 0 auto;
                                display: flex;
                                align-items: center;
                                flex-wrap: wrap;
                                list-style: none;
                            }
                            .baiduseo_linkhh_box li {
                                list-style: none;
                                width: 14.2857%;
                                padding: 2px;
                                margin-bottom: 5px;
                                box-sizing: border-box;
                            }
                            .baiduseo_linkhh_box a {
                                width: 100%;
                                border: 1px solid #eee;
                                white-space: nowrap;
                                text-overflow: ellipsis;
                                overflow: hidden;
                                color: #062743;
                                font-size: 14px;
                                display: block;
                                box-sizing: border-box;
                                text-align: center;
                                line-height: 38px;
                                background-color: #fff;
                                border-radius: 3px;
                                transition: .5s;
                                position: relative;
                            }
                            .baiduseo_linkhh_box a:hover {
                                text-decoration: underline;
                            }
                            .baiduseo_linkhh_box span {
                                position: absolute;
                                z-index: 10;
                                background: linear-gradient(90deg, #0162c8, #55e7fc);
                                transform: translate(-50%, -50%);
                                pointer-events: none;
                                border-radius: 50%;
                                animation: scaleAnimate 1s linear infinite;
                            }
                            @keyframes scaleAnimate {
                                from {
                                    width: 0px;
                                    height: 0px;
                                    opacity: .5;
                                }
                                to {
                                    width: 500px;
                                    height: 500px;
                                    opacity: 0;
                                }
                            }
                        </style>
                        <ul class="baiduseo_linkhh_box" style="--container-width: '.esc_attr($wztkj_linkhh['yswidth']).'">
                    ';
                    if(!empty($friends)){
                        foreach($friends as $key=>$val){
                            echo '<li><a href="'.esc_url($val['link']).'" target="_blank">'.esc_attr($val['keywords']).'</a></li>';
                        }
                    }else{
                        $keywords = explode(',',$wztkj_linkhh['keywords']);
                        echo '<li><a href="/" target="_blank">'.esc_attr($keywords[0]).'</a></li>';
                    }
                    echo '
                        </ul>
                        <script>
                            function isMobile(){
                                return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
                            }
                            if (isMobile()) {
                                document.querySelector(".baiduseo_linkhh_box").style = "width:'.esc_attr($wztkj_linkhh['mobilewidth']).'";
                                document.querySelectorAll(".baiduseo_linkhh_box li").forEach(li => {
                                    li.style.width = "50%";
                                });
                            }
    
                            const links = document.querySelectorAll(".baiduseo_linkhh_box li a");
                            links.forEach(link => {
                                link.addEventListener("mouseenter", function(e) {
                                    let x = e.offsetX;
                                    let y = e.offsetY;
                    
                                    let ripples = document.createElement("span");
                                    ripples.style.left = x + "px";
                                    ripples.style.top = y + "px";
                                    this.appendChild(ripples);
                    
                                    setTimeout(() => {
                                        ripples.remove();
                                    }, 1000);
                                });
                            });
                        </script>
                    ';
                }else{
                    
                }
            } else if (isset($wztkj_linkhh['ystype']) && $wztkj_linkhh['ystype'] == 2) {
                if(isset($wztkj_linkhh['link']) && $wztkj_linkhh['link']){
                    echo '
                        <style>
                            .baiduseo_linkhh_box_container {
                                background-color: #fff;
                            }
                            .baiduseo_linkhh_box {
                                width: var(--container-width, 100%);
                                margin: 0 auto;
                                font-size: 14px;
                                padding: 15px 0;
                                box-sizing: border-box;
                            }
                            .baiduseo_linkhh_box a {
                                font-size: 14px;
                                margin-right: 10px;
                            }
                            .baiduseo_linkhh_box a:hover {
                                text-decoration: underline;
                            }
                        </style>
                        <div class="baiduseo_linkhh_box_container">
                            <div class="baiduseo_linkhh_box" style="--container-width: '.esc_attr($wztkj_linkhh['yswidth']).'">
                                <span>友情链接：</span>
                    ';
                   
                    if(!empty($friends)){
                        foreach($friends as $key=>$val){
                            echo '<a href="'.esc_url($val['link']).'" target="_blank">'.esc_attr($val['keywords']).'</a>';
                        }
                    }else{
                        $keywords = explode(',',$wztkj_linkhh['keywords']);
                        echo '<a href="/" target="_blank">'.esc_attr($keywords[0]).'</a>';
                    }
                    echo '
                            </div>
                        </div>
                        <script>
                            function isMobile(){
                                return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
                            }
                            if (isMobile()) {
                                document.querySelector(".baiduseo_linkhh_box").style = "width:'.esc_attr($wztkj_linkhh['mobilewidth']).'";
                            }
                        </script>    
                    ';
                }else{
                    
                }
            }
        }
    }
}
