<?php
class luntan_post{
    public function init(){
        //个人中心接口
        add_action('wp_ajax_luntan_avatar', [$this,'luntan_avatar']);
        add_action('wp_ajax_nopriv_luntan_sendemail', [$this,'luntan_sendemail']);
        add_action('wp_ajax_luntan_sendemail', [$this,'luntan_sendemail']);
        add_action('wp_ajax_luntan_get_user', [$this,'luntan_get_user']);
        add_action('wp_ajax_nopriv_luntan_get_user', [$this,'luntan_get_user']);
        add_action('wp_ajax_luntan_get_post', [$this,'luntan_get_post']);
        add_action('wp_ajax_luntan_delete_post', [$this,'luntan_delete_post']);
        add_action('wp_ajax_luntan_add_cate', [$this,'luntan_add_cate']);
        add_action('wp_ajax_luntan_update_cate', [$this,'luntan_update_cate']);
        add_action('wp_ajax_luntan_delete_cate', [$this,'luntan_delete_cate']);
        add_action('wp_ajax_luntan_zhuanyi_cate', [$this,'luntan_zhuanyi_cate']);
        add_action('wp_ajax_luntan_get_cate', [$this,'luntan_get_cate']);
        add_action('wp_ajax_luntan_manage_post', [$this,'luntan_manage_post']);
        add_action('wp_ajax_luntan_shenhe_post', [$this,'luntan_shenhe_post']);
        add_action('wp_ajax_luntan_zhuanyi_post', [$this,'luntan_zhuanyi_post']);
        //前端接口
        add_action('wp_ajax_nopriv_luntan_cate_list', [$this,'luntan_cate_list']);
        add_action('wp_ajax_luntan_cate_list', [$this,'luntan_cate_list']);
        add_action('wp_ajax_nopriv_luntan_post_list', [$this,'luntan_post_list']);
        add_action('wp_ajax_luntan_post_list', [$this,'luntan_post_list']);
        add_action('wp_ajax_nopriv_luntan_post_detail', [$this,'luntan_post_detail']);
        add_action('wp_ajax_luntan_post_detail', [$this,'luntan_post_detail']);
        
        add_action('wp_ajax_luntan_post_img', [$this,'luntan_post_img']);
        
        add_action('wp_ajax_luntan_comment_like', [$this,'luntan_comment_like']);
         add_action('wp_ajax_nopriv_luntan_comment_like', [$this,'luntan_comment_like']);
        add_action('wp_ajax_luntan_delete_pl', [$this,'luntan_delete_pl']);
        
        add_action('wp_ajax_luntan_post_publish', [$this,'luntan_post_publish']);
        
        add_action('wp_ajax_luntan_post_pl', [$this,'luntan_post_pl']);
        
        add_action('wp_ajax_luntan_post_edit', [$this,'luntan_post_edit']);
        add_action('wp_ajax_luntan_smtp_baocun', [$this,'luntan_smtp_baocun']);
        add_action('wp_ajax_luntan_get_smtp_baocun', [$this,'luntan_get_smtp_baocun']);
        add_action('wp_ajax_luntan_smtp_baocun_cs', [$this,'luntan_smtp_baocun_cs']);
        add_action( 'phpmailer_init', [$this,'luntan_configure_smtp_mailer'] );
        add_action('wp_ajax_luntan_post_top', [$this,'luntan_post_top']);
        
        add_action('wp_ajax_luntan_get_vip', [$this,'luntan_get_vip']);
        add_action('wp_ajax_luntan_vip', [$this,'luntan_vip']);
        
        add_action('wp_ajax_luntan_xieyi', [$this,'luntan_xieyi']);
        
        add_action('wp_ajax_luntan_get_xieyi', [$this,'luntan_get_xieyi']);
        add_action('wp_ajax_nopriv_luntan_get_xieyi', [$this,'luntan_get_xieyi']);
        
        add_action('wp_ajax_luntan_url_guanli', [$this,'luntan_url_guanli']);
        
         add_action('wp_ajax_luntan_get_url_guanli', [$this,'luntan_get_url_guanli']);
        
    }
    public function luntan_get_url_guanli(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            $luntan_url_guanli = get_option('luntan_url_guanli');
            
            echo wp_json_encode(['code'=>1,'data'=>$luntan_url_guanli]);exit;
            
        }
    }
    public function luntan_url_guanli(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            $luntan_url_guanli = get_option('luntan_url_guanli');
            if($luntan_url_guanli===false){
                add_option('luntan_url_guanli',['list'=>sanitize_text_field(wp_unslash($_POST['list'])),'zhongxin'=>sanitize_text_field(wp_unslash($_POST['zhongxin']))]);
            }else{
                update_option('luntan_url_guanli',['list'=>sanitize_text_field(wp_unslash($_POST['list'])),'zhongxin'=>sanitize_text_field(wp_unslash($_POST['zhongxin']))]);
            }
            echo wp_json_encode(['code'=>1,'msg'=>'保存成功']);exit;
            
        }
    }
    public static function luntan_generate_short_code($str) {
        // 先将中文转为UTF-8编码的哈希
        $hash = md5(trim(urlencode($str)));
        $num = wp_rand(4,8);
        $short_code = substr($hash, 0, $num);
        $short_code = strtr($short_code, ['0'=>'a','1'=>'b','2'=>'c','3'=>'d','4'=>'e','5'=>'f','6'=>'g','7'=>'h','8'=>'i','9'=>'j']);
        
        return $short_code;
    }
    public function luntan_get_xieyi(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            
            $luntan_xieyi = get_option('luntan_xieyi')?get_option('luntan_xieyi'):'';
          
            echo wp_json_encode(['code'=>1,'data'=>$luntan_xieyi]);exit;
           
            
        }
        echo wp_json_encode(['code'=>0,'msg'=>'获取失败']);exit;
    }
    public function  luntan_xieyi(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            
            global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
            if (current_user_can('administrator')) {
                $luntan_xieyi = get_option('luntan_xieyi');
                if($luntan_xieyi===false){
                    if(isset($_POST['luntan_xieyi'])){
                        add_option('luntan_xieyi',wp_kses_post(wp_unslash($_POST['luntan_xieyi'])));
                    }
                }else{
                    if(isset($_POST['luntan_xieyi'])){
                    update_option('luntan_xieyi',wp_kses_post(wp_unslash($_POST['luntan_xieyi'])));
                    }
                }
                echo wp_json_encode(['code'=>1,'msg'=>'操作成功']);exit;
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
        }
        echo wp_json_encode(['code'=>0,'msg'=>'操作失败']);exit;
    }
    public function luntan_post_top(){
         if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            $avatar = get_user_meta( $user_id, 'luntan_avatar',true );
            $nickname = get_user_meta( $user_id, 'nickname',true );
            if (current_user_can('administrator')) {
                if(isset($_POST['type']) && $_POST['type']==1){
                    if(isset($_POST['id'])){
                        stick_post((int)$_POST['id']);
                    }
                }elseif(isset($_POST['type']) &&$_POST['type']==2){
                    if(isset($_POST['id'])){
                        unstick_post((int)$_POST['id']);
                    }
                    
                }elseif(isset($_POST['type']) &&$_POST['type']==3){
                    if(isset($_POST['id'])){
                        update_post_meta((int)$_POST['id'],'luntan_jing',1);
                    }
                    
                }elseif(isset($_POST['type']) &&$_POST['type']==4){
                    if(isset($_POST['id'])){
                        update_post_meta((int)$_POST['id'],'luntan_jing',0);
                    }
                   
                }
                 echo wp_json_encode(['code'=>1,'msg'=>'操作成功']);exit;
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
            
        }
        echo wp_json_encode(['code'=>0,'msg'=>'操作失败']);exit;
    }
    public function luntan_email($accept,$message){
        $config = get_option('luntan_smtp_baocun');
        $to = $accept;
        
        $subject = $config['nick'];
       
        $message = $message;
        $headers = array('Content-Type: text/html; charset=UTF-8');
        wp_mail($to, $subject, $message, $headers);
    }
    public function luntan_smtp_baocun_cs(){
        
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            $config = get_option('luntan_smtp_baocun');
            $to = $config['accept'];
            
            $subject = $config['nick'];
           
            $message = '测试发送邮件';
            $headers = array('Content-Type: text/html; charset=UTF-8');
            global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
                if(wp_mail($to, $subject, $message, $headers)){
                    echo wp_json_encode(['code'=>1,'msg'=>'发送成功']);exit;
                } else {
                    echo wp_json_encode(['code'=>0,'msg'=>'发送失败，配置不正确']);exit;
                }
           
        }
    }
    public function luntan_get_smtp_baocun(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            
            $luntan_smtp_baocun = get_option('luntan_smtp_baocun');
            if(is_array($luntan_smtp_baocun)){
                $luntan_smtp_baocun['is_register'] = get_option('users_can_register')?1:0;
            }
            echo wp_json_encode(['code'=>1,'data'=>$luntan_smtp_baocun]);exit;
        }
         echo wp_json_encode(['code'=>0,'msg'=>'获取失败']);exit;
    }
    public function  luntan_smtp_baocun(){
         if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
             global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
             $list = [
                'url'=>isset($_POST['url'])?sanitize_text_field(wp_unslash($_POST['url'])):'',    
                'email'=>isset($_POST['email'])?sanitize_email(wp_unslash($_POST['email'])):'', 
                'accept'=>isset($_POST['accept'])?sanitize_email(wp_unslash($_POST['accept'])):"", 
                'nick'=>isset($_POST['nick'])?sanitize_text_field(wp_unslash($_POST['nick'])):"", 
                'port'=>isset($_POST['port'])?(int)$_POST['port']:"", 
                'pass'=>isset($_POST['pass'])?sanitize_text_field(wp_unslash($_POST['pass'])):"", 
                'register'=>isset($_POST['register'])?(int)$_POST['register']:"", 
                'post'=>isset($_POST['post'])?(int)$_POST['post']:"", 
                'replay'=>isset($_POST['replay'])?(int)$_POST['replay']:"",
                "is_register"=>(int)$_POST['is_register'],
            ];
            $luntan_smtp_baocun = get_option('luntan_smtp_baocun');
            global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
                if($luntan_smtp_baocun===false){
                    add_option('luntan_smtp_baocun',$list);
                }else{
                    update_option('luntan_smtp_baocun',$list);
                }
                if((int)$_POST['is_register']){
                    update_option('users_can_register',1);
                }else{
                    update_option('users_can_register',0);
                }
           
            echo wp_json_encode(['code'=>1,'msg'=>'保存成功']);exit;
         }
         echo wp_json_encode(['code'=>0,'msg'=>'保存失败']);exit;
    }
    public function luntan_configure_smtp_mailer($phpmailer){
        $config = get_option('luntan_smtp_baocun');
        // 配置 SMTP 设置
        $phpmailer->isSMTP();
        $phpmailer->Host       = $config['url']; // SMTP 主机地址
        $phpmailer->SMTPAuth   = true; // 启用 SMTP 验证
        $phpmailer->Port       = $config['port']; // SMTP 端口（常见为 587 或 465）
        $phpmailer->Username   = $config['email']; // SMTP 用户名（通常是邮箱地址）
        $phpmailer->Password   = $config['pass']; // SMTP 密码
        $phpmailer->SMTPSecure = 'tls'; // 加密方式：`tls` 或 `ssl`
        // 配置发件人信息
        $phpmailer->From =$config['email'];
        $phpmailer->FromName = $config['nick'];
    }
   
    public function luntan_post_edit(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
             $updated_post = array(
                'ID' => isset($_POST['id'])?(int)$_POST['id']:'',
                'post_title' => isset($_POST['title'])?sanitize_text_field(wp_unslash($_POST['title'])):'', // 示例新标题，可根据需要修改
                'post_content' => isset($_POST['content']) ? wp_kses_post( str_replace(["\r\n", "\r", "\n"], '<br>', wp_unslash($_POST['content'])) ) : '', // 示例新内容，可根据需要修改
               
            );
            // 使用wp_update_post函数更新帖子
            $updated = wp_update_post($updated_post);
            
                $img = isset($_POST['img']) ?sanitize_text_field(wp_unslash($_POST['img'])):'';
                if($img){
                     update_post_meta((int)$_POST['id'],'luntan_img',$img);
                }
             if (isset($_POST['id']) && (int)$_POST['id'] && isset($_POST['cate_id']) && (int)$_POST['cate_id']) {
                wp_set_object_terms((int)$_POST['id'], (int)$_POST['cate_id'], 'luntan_cate');
            } 
            
            echo wp_json_encode(['code'=>1,'msg'=>'操作成功']);exit;
        }
        echo wp_json_encode(['code'=>0,'msg'=>'操作失败']);exit;
    }
    public function luntan_post_pl(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            
            $comment_data = array(
                'comment_post_ID' => isset($_POST['id']) ?(int)$_POST['id']:0,
                'comment_author' => get_userdata($user_id)->display_name,
                'comment_author_email' => get_userdata($user_id)->user_email,
                'comment_author_url' => '', // 可根据用户实际情况填写或留空
                'comment_content' =>isset($_POST['content']) ? wp_kses_post(str_replace(array("\r\n", "\r", "\n"), '<br>', wp_unslash($_POST['content']))) : "", // 替换为实际要发布的评论内容
                'comment_type' => '',
                'comment_parent' => isset($_POST['parent']) ?(int)$_POST['parent']:0,
                 // 若要回复某条评论则设置为该评论的ID，这里设为顶级评论
                'comment_approved' => 1, // 可根据需求设置是否直接批准发布
                'user_id'=>$user_id
            );
            
            // 插入评论到数据库
            $comment_id = wp_insert_comment($comment_data);
            if(isset($_POST['img']) && sanitize_url(wp_unslash($_POST['img']))){
            update_comment_meta($comment_id, 'luntan_pl_img', sanitize_url(wp_unslash($_POST['img'])));
            }
             $luntan_smtp_baocun = get_option('luntan_smtp_baocun');
             if($_POST['parent']==0 && isset($luntan_smtp_baocun['replay']) && $luntan_smtp_baocun['replay'] && isset($_POST['id']) ){
                 $this->luntan_email(get_userdata(get_post((int)$_POST['id'])->post_author)->user_email,'您的帖子有新的回复，<a href="'.get_the_permalink((int)$_POST['id']).'">查看</a>'); 
             }
            if(isset($_POST['id'])){
                update_post_meta( (int)$_POST['id'], 'luntan_replay_num', get_comments_number((int)$_POST['id']) );
            }
            echo wp_json_encode(['code'=>1,'msg'=>'操作成功','id'=>$comment_id]);exit;
        }
         echo wp_json_encode(['code'=>0,'msg'=>'操作失败']);exit;
    }
    public function luntan_post_publish(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
             if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            global $wpdb;
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            if (current_user_can('administrator')) {
                $new_post = array(
                    'post_title' =>isset($_POST['title'])?sanitize_text_field(wp_unslash($_POST['title'])):'',
                    'post_content' =>isset($_POST['content']) ? wp_kses_post( str_replace(["\r\n", "\r", "\n"], '<br>', wp_unslash($_POST['content'])) ) : '',
                    'post_type' => 'luntan',
                    'post_status' => 'publish',
                    'post_author'=>$user_id,
                    
                );
            }else{
                $new_post = array(
                    'post_title' =>isset($_POST['title'])?sanitize_text_field(wp_unslash($_POST['title'])):'',
                    'post_content' =>isset($_POST['content']) ? wp_kses_post( str_replace(["\r\n", "\r", "\n"], '<br>', wp_unslash($_POST['content'])) ) : '',
                    'post_type' => 'luntan',
                    'post_status' => 'pending',
                    'post_author'=>$user_id,
                    
                );
            }
            $post_name = $this->luntan_generate_short_code(isset($_POST['title'])?sanitize_text_field(wp_unslash($_POST['title'])):$current_user->ID.'wztkj'.wp_rand(1000,9999));
            // 插入帖子到数据库
            $post_id = wp_insert_post($new_post);
            
            $result = $wpdb->update(
                $wpdb->posts, // 表名（自动适配前缀）
                array(
                    'post_name' => $post_name // 要更新的字段和值
                ),
                array(
                    'ID' => $post_id // 条件：文章ID
                ),
            );
                                
            $img = isset($_POST['img'])?sanitize_text_field(wp_unslash($_POST['img'])):"";
            if($img && $post_id){
                update_post_meta($post_id,'luntan_img',$img);
            }
            // 添加分类到帖子
            if ($post_id && isset($_POST['cate']) &&  (int)$_POST['cate']) {
                wp_set_object_terms($post_id, (int)$_POST['cate'], 'luntan_cate');
            }
            if (current_user_can('administrator')) {
                echo wp_json_encode(['code'=>1,'msg'=>'操作成功','role'=>1]);exit;
            }else{
                echo wp_json_encode(['code'=>1,'msg'=>'操作成功','role'=>0]);exit;
            }
             
        }
        echo wp_json_encode(['code'=>0,'msg'=>'操作失败']);exit;
    }
    public function luntan_comment_like(){
          if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){

            $comment_id = isset($_POST['id'])?intval($_POST['id']):0;
            $likes_count = get_comment_meta($comment_id, 'luntan_likes_count', true);
            $cai_count = get_comment_meta($comment_id, 'luntan_cai_count', true);
            $type = isset($_POST['type'])?(int)$_POST['type']:0;
            if($type==1){
                update_comment_meta($comment_id, 'luntan_likes_count', (int)$likes_count+1);
            }elseif($type==2){
               update_comment_meta($comment_id, 'luntan_likes_count', (int)$likes_count-1);
            }elseif($type==3){
                update_comment_meta($comment_id, 'luntan_cai_count', (int)$cai_count+1);
            }else{
               update_comment_meta($comment_id, 'luntan_cai_count', (int)$cai_count-1);
            }
           echo wp_json_encode(['code'=>1,'msg'=>'操作成功']);exit;
        }
        echo wp_json_encode(['code'=>0,'msg'=>'操作失败']);exit;
    }
    public function  luntan_delete_pl(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            $comment = get_comment(isset($_POST['id'])?(int)$_POST['id']:0);
            $this->recursively_delete_comments($comment);
            //重新计算回复数量
            update_post_meta($comment->comment_post_ID,'luntan_replay_num',get_comments_number($comment->comment_post_ID));
             echo wp_json_encode(['code'=>1,'msg'=>'操作成功']);exit;
        }
        echo wp_json_encode(['code'=>0,'msg'=>'操作失败']);exit;
    }
    public function recursively_delete_comments($comment) {
        
        // 删除当前评论
        wp_delete_comment($comment->comment_ID, false);

        // 获取当前评论的子评论
        $children = get_comments(array(
            'parent' => $comment->comment_ID,
            'status' => 'all'
        ));

        // 递归删除子评论
        foreach ($children as $child) {
            $this->recursively_delete_comments($child);
        }
    }
    public function luntan_img_san($file){
        $data = [
            'tmp_name'=>isset($file['tmp_name'])?sanitize_text_field(wp_unslash($file['tmp_name'])):'',
            'name'=>isset($file['name'])?sanitize_text_field(wp_unslash($file['name'])):'',
            'size'=>isset($file['size'])?(int)$file['size']:'',
            'error'=>isset($file['error'])?(int)$file['error']:0,
        ];
        return $data;
    }
    public function luntan_post_img(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            
            // 检查是否有文件上传
            if (!isset($_FILES['file'])) {
                echo wp_json_encode(['code'=>0,'msg'=>'没有选择要上传的图片']);exit;
            }
            $file =$this->luntan_img_san($_FILES['file']);
             if (!isset( $file['tmp_name'] ) ||  ! is_uploaded_file( $file['tmp_name'] ) || !is_file( $file['tmp_name'])) {
                echo wp_json_encode(['code'=>0,'msg'=>'没有选择要上传的图片']);exit;
            }
        
            // 检查上传过程中是否有错误
            if (isset($file['error']) && (int)$file['error']!= 0) {
                echo wp_json_encode(['code'=>0,'msg'=>'图片上传失败，请稍后重试！']);exit;
            }
        
            // 获取上传文件的信息
            $file_name = $file['name'];
            $file_size = $file['size'];
            $upload_overrides = array( 'test_form' => false );
             
            $move_result = wp_handle_upload( $file, $upload_overrides );
            // 移动上传的文件到目标目录
            if ($move_result && ! isset( $move_result['error'] )) {
               $target_url = $move_result['url'];
            echo wp_json_encode(['code'=>1,'data'=>$target_url]);exit;
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'图片上传失败，请稍后重试！']);exit;
            }
            
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_post_detail(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $wpdb;
            $id = isset($_POST['id'])?(int)$_POST['id']:0;
            //浏览量加1
            $post_extend = get_post_meta( $id, 'luntan_views', true );

            update_post_meta( $id,'luntan_views',  (int)$post_extend+1 ); 
            $list['detail'] = get_post($id);
           
                $list['detail']->luntan_views =  get_post_meta($list['detail']->ID,'luntan_views',true)?get_post_meta($list['detail']->ID,'luntan_views',true):0;
                $list['detail']->nickname = get_userdata($list['detail']->post_author)->nickname?get_userdata($list['detail']->post_author)->nickname:'用户'.$list['detail']->post_author;
                
                $avatar = get_user_meta( $list['detail']->post_author, 'luntan_avatar',true );
                
                $list['detail']->avatar = $avatar;
                $list['detail']->thumb = get_post_meta($id,'luntan_img',true);
                if(is_sticky($id)){
                    $list['detail']->top = 1;
                }else{
                    $list['detail']->top = 0;
                }
                if(get_post_meta($id,'luntan_jing',true)){
                    $list['detail']->jing = 1;
                }else{
                    $list['detail']->jing = 0;
                }
                
                $list['detail']->cate=get_the_terms($id,'luntan_cate')?get_the_terms($id,'luntan_cate')[0]->term_id:0;
                
            
            if(wp_cache_get('luntan_news')===false){
                // 执行 SQL 查询
                $list['news'] = $wpdb->get_results(" 
                    SELECT p.*, MAX(c.comment_date) as latest_comment_date
                    FROM {$wpdb->posts} p
                    LEFT JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
                    WHERE p.post_type = 'luntan'
                    AND p.post_status = 'publish'
                     AND c.comment_approved = '1'
                    GROUP BY p.ID
                    ORDER BY latest_comment_date DESC
                    LIMIT 5
                ");
                wp_cache_set( 'luntan_news', $list['news'], '', 3600 );
            }else{
                $list['news'] = wp_cache_get('luntan_news');
            }
            
            foreach($list['news'] as $k=>$v){
                
                $list['news'][$k]->luntan_replay_num =  get_post_meta($v->ID,'luntan_replay_num',true)?get_post_meta($v->ID,'luntan_replay_num',true):0;
                $list['news'][$k]->luntan_views =  get_post_meta($v->ID,'luntan_views',true)?get_post_meta($v->ID,'luntan_views',true):0;
                
                $list['news'][$k]->link = get_the_permalink($v->ID);
                $latest_comment = get_comments( array(
                    'post_id' => $v->ID,
                    'number' => 1,
                    'orderby' => 'comment_date_gmt',
                    'order' => 'DESC'
                ) );
                if(!empty($latest_comment)){
                    $list['news'][$k]->comment_date = $latest_comment[0]->comment_date;
                }
                
            }
            
            $list['hot'] = get_posts(array(
                'numberposts' => 5,
                'orderby'     => 'meta_value_num',
                'order'       => 'luntan_views',
                'post_type' => 'luntan',
                'post_status'=>'publish',
            ));
             foreach($list['hot'] as $k=>$v){
                $list['hot'][$k]->luntan_replay_num =  get_post_meta($v->ID,'luntan_replay_num',true)?get_post_meta($v->ID,'luntan_replay_num',true):0;
                $list['hot'][$k]->luntan_views =  get_post_meta($v->ID,'luntan_views',true)?get_post_meta($v->ID,'luntan_views',true):0;
                $list['hot'][$k]->link = get_the_permalink($v->ID);
            }
          $args = array(
                'post_id' => $id,
                'order' => 'ASC',
                'hierarchical' => true,
                'status' => 'approve',
                'parent'=>0
            );

            // 创建评论查询对象
            $comments_query = new WP_Comment_Query;

            // 执行评论查询 
            $list['pl'] = $comments_query->query($args);
           
            if($list['pl']){
                foreach($list['pl'] as $k=>$comment){
                   $list['pl'][$k]->nickname =get_userdata($comment->user_id)->nickname?get_userdata($comment->user_id)->nickname:'用户'.$comment->user_id;
                   $list['pl'][$k]->avatar= get_user_meta( $comment->user_id, 'luntan_avatar',true );
                    $likes_count = get_comment_meta($comment->comment_ID, 'luntan_likes_count', true);
                    $cai_count = get_comment_meta($comment->comment_ID, 'luntan_cai_count', true);
                    $img = get_comment_meta($comment->comment_ID, 'luntan_pl_img', true);
                   $list['pl'][$k]->img = $img;
                   $list['pl'][$k]->likes = $likes_count;
                   $list['pl'][$k]->cai = $cai_count;
                     if ($comment->comment_parent == 0) {
                            
                             $list['pl'][$k]->child = self::luntan_get_comment_with_children($comment,$id,[]);
                           
                     }else{
                         unset($list['pl'][$k]);
                     }
                }
            }
            echo wp_json_encode(['code'=>1,'data'=>$list]);exit;
        }
        echo wp_json_encode(['code'=>0,'msg'=>'获取失败']);exit;
    }
    public static function luntan_get_comment_with_children($comment,$post_id,$arr) {
       
         $comments_query = new WP_Comment_Query;
        $children_args = array(
            'post_id' => $post_id,
            'parent' => $comment->comment_ID,
            'order' => 'ASC',
            'status' => 'approve'
        );
        $pl = $comments_query->query($children_args);
        
        if(!empty($pl)){
            foreach($pl as $k=>$v){
                
                 $pl[$k]->nickname =get_userdata($v->user_id)->nickname?get_userdata($v->user_id)->nickname:'用户'.$v->user_id;
                  $pl[$k]->avatar= get_user_meta( $v->user_id, 'luntan_avatar',true );
                   $pl[$k]->cnickname =get_userdata($comment->user_id )->nickname?get_userdata($comment->user_id)->nickname:'用户'.$comment->user_id;
                  $pl[$k]->cavatar= get_user_meta( $comment->user_id , 'luntan_avatar',true );
                  $likes_count = get_comment_meta($v->comment_ID, 'luntan_likes_count', true);
                    $cai_count = get_comment_meta($v->comment_ID, 'luntan_cai_count', true);
                    $img = get_comment_meta($v->comment_ID, 'luntan_pl_img', true);
                   $pl[$k]->img = $img;
                   $pl[$k]->likes = $likes_count;
                   $pl[$k]->cai = $cai_count;
                
            }
            $arr = array_merge($arr,$pl);
            foreach($pl as $key=>$val){
                $arr = self::luntan_get_comment_with_children($val,$post_id,$arr);
            }
        }
        return $arr;
    }
    public function luntan_post_list(){
        global $wpdb;
         if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            $page = isset($_POST['page'])?(int)$_POST['page']:1;
            $limit = isset($_POST['limit'])?(int)$_POST['limit']:10;
            $start =  ($page-1)*$limit;
            $list = [];
            $search = isset($_POST['search'])?sanitize_text_field(wp_unslash($_POST['search'])):"";
            $sticky_posts = get_option('sticky_posts');                           
            if($search){
                $placeholders = array_fill(0, count($sticky_posts), '%d');
                $sticky_params = ['%'.$search.'%'];
                $sticky_params1 = array_map('intval', $sticky_posts);
                           
                $main_params = array_merge($sticky_params,$sticky_params1, array( $start, $limit));
                
                $list['all'] = $wpdb->get_results($wpdb->prepare("SELECT p.*, MAX(c.comment_date_gmt) as latest_comment_date
                    FROM {$wpdb->posts} p
                    LEFT JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
                    WHERE p.post_status = 'publish'
                    AND p.post_type = 'luntan'
                    and post_title like %s
                    GROUP BY p.ID
                    ORDER BY 
                        CASE 
                            WHEN p.ID IN (" . implode(',', $placeholders) . ") THEN 0
                            ELSE 1
                        END ASC,
                        latest_comment_date DESC,ID desc limit %d,%d", $main_params), ARRAY_A);
                $list['count'] = $wpdb->query($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where  post_status='publish'  and post_type='luntan' and post_title like %s",'%'.$search.'%'),ARRAY_A);
            }else{
                $placeholders = array_fill(0, count($sticky_posts), '%d');
                $sticky_params1 = array_map('intval', $sticky_posts);
               
                $main_params = array_merge($sticky_params1, array( $start, $limit));
                $list['count']  = $wpdb->query("SELECT * FROM ".$wpdb->prefix ."posts  where  post_status='publish' and post_type='luntan' ",ARRAY_A);
                $list['all'] = $wpdb->get_results($wpdb->prepare("SELECT p.*, MAX(c.comment_date_gmt) as latest_comment_date
                    FROM {$wpdb->posts} p
                    LEFT JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
                    WHERE p.post_status = 'publish'
                    AND p.post_type = 'luntan'
                    GROUP BY p.ID
                    ORDER BY 
                        CASE 
                            WHEN p.ID IN (" . implode(',', $placeholders) . ") THEN 0
                            ELSE 1
                        END ASC,
                        latest_comment_date DESC,ID desc limit %d,%d", $main_params), ARRAY_A);
            }
            foreach($list['all'] as $k=>$v){
                $list['all'][$k]['luntan_replay_num'] = get_post_meta($v['ID'],'luntan_replay_num',true)?get_post_meta($v['ID'],'luntan_replay_num',true):0;
                $list['all'][$k]['luntan_views'] = get_post_meta($v['ID'],'luntan_views',true)?get_post_meta($v['ID'],'luntan_views',true):0;
                $list['all'][$k]['author_nick'] = get_userdata($v['post_author'])->nickname?get_userdata($v['post_author'])->nickname:'用户'.$v['post_author'];
                $list['all'][$k]['author_avatar'] = get_user_meta($v['post_author'],'luntan_avatar',true);
                $list['all'][$k]['link'] = get_the_permalink($v['ID']);
                if(is_sticky($v['ID'])){
                    $list['all'][$k]['top'] =1;
                }else{
                    $list['all'][$k]['top'] =0;
                }
                if(get_post_meta($v['ID'],'luntan_jing',true)){
                    $list['all'][$k]['jing'] =1;
                }else{
                    $list['all'][$k]['jing'] =0;
                }
                $list['all'][$k]['comments'] = get_comments( array(
                    'post_id' => $v['ID'],  
                    'number'  => 1,         
                    'orderby' => 'comment_date_gmt', 
                    'order'   => 'DESC',
                ) );
                foreach($list['all'][$k]['comments']  as $key=>$comment){
                   $list['all'][$k]['comments'][$key]->nickname =get_userdata($comment->user_id)->nickname?get_userdata($comment->user_id)->nickname:'用户'.$comment->user_id;
                   $list['all'][$k]['comments'][$key]->avatar = get_user_meta($comment->user_id,'luntan_avatar',true);
                }
                $list['all'][$k]['cate'] = get_the_terms($v['ID'], 'luntan_cate')?get_the_terms($v['ID'], 'luntan_cate'):[];
            }
            $categories = get_terms( array(
                'taxonomy' => 'luntan_cate',
                'hide_empty' => false,
            ) );
            $arr = [];
            foreach ($categories as $key=>$category) {
                $main_params = [$category->term_id];
                $main_params = array_merge($main_params,$sticky_params1, array( $start, $limit));
                 $arr[]=[
                    'cate'=>$category->name,
                    'id'=>$category->term_id,
                    'post'=>$wpdb->get_results($wpdb->prepare("
    SELECT p.*, MAX(c.comment_date_gmt) as latest_comment_date
    FROM {$wpdb->posts} p
    LEFT JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
    JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
    JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
    WHERE p.post_status = 'publish'
    AND p.post_type = 'luntan'
    AND tt.taxonomy = 'luntan_cate'
    AND tt.term_id = %d
    GROUP BY p.ID
    ORDER BY 
        CASE 
            WHEN p.ID IN (" . implode(',', $placeholders) . ") THEN 0
            ELSE 1
        END ASC,
        latest_comment_date DESC,ID desc limit %d,%d
",$main_params),ARRAY_A),
                    'count'=>count(get_posts(array(
                        'tax_query' => array(
                                array(
                                    'taxonomy' => 'luntan_cate', // 自定义分类法名称
                                    'field'    => 'term_id', // 可以是 term_id、slug 等
                                    'terms'    => array( $category->term_id) // 要查询的分类 ID 数组
                                )
                            ),
                        'post_type' => 'luntan',
                        'numberposts' => -1,
                         'post_status'=>'publish',
                    )))
                ];
            }
            foreach($arr as $key=>$val){
                foreach($val['post'] as $k=>$v){
                    
                    $arr[$key]['post'][$k]['luntan_replay_num'] = get_post_meta($v['ID'],'luntan_replay_num',true)?get_post_meta($v['ID'],'luntan_replay_num',true):0;
                   
                    $arr[$key]['post'][$k]['luntan_views'] = get_post_meta($v['ID'],'luntan_views',true)?get_post_meta($v['ID'],'luntan_views',true):0;
                    $arr[$key]['post'][$k]['author_nick'] = get_userdata($v['post_author'])->nickname?get_userdata($v['post_author'])->nickname:'用户'.$v['post_author'];
                    $arr[$key]['post'][$k]['author_avatar'] = get_user_meta($v['post_author'],'luntan_avatar',true);
                    $arr[$key]['post'][$k]['link'] = get_the_permalink($v['ID']);
                    if(is_sticky($v['ID'])){
                       $arr[$key]['post'][$k]['top'] =1;
                    }else{
                        $arr[$key]['post'][$k]['top'] =0;
                    }
                    if(get_post_meta($v['ID'],'luntan_jing',true)){
                        $arr[$key]['post'][$k]['jing'] =1;
                    }else{
                        $arr[$key]['post'][$k]['jing'] =0;
                    }
                    $arr[$key]['post'][$k]['comments'] = get_comments( array(
                        'post_id' => $v['ID'],  
                        'number'  => 1,         
                        'orderby' => 'comment_date_gmt', 
                        'order'   => 'DESC',
                    ) );
                    foreach($arr[$key]['post'][$k]['comments']  as $keys=>$comment){
                      $arr[$key]['post'][$k]['comments'][$keys]->nickname =get_userdata($comment->user_id)->nickname?get_userdata($comment->user_id)->nickname:'用户'.$comment->user_id;
                      $arr[$key]['post'][$k]['comments'][$keys]->avatar = get_user_meta($comment->user_id,'luntan_avatar',true);
                    }
                }
            }
            $list['cate'] = $arr;
            
            
            if(wp_cache_get('luntan_news')===false){
                // 执行 SQL 查询
                $list['news'] = $wpdb->get_results(" 
                    SELECT p.*, MAX(c.comment_date) as latest_comment_date
                    FROM {$wpdb->posts} p
                    LEFT JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
                    WHERE p.post_type = 'luntan'
                    AND p.post_status = 'publish'
                     AND c.comment_approved = '1'
                    GROUP BY p.ID
                    ORDER BY latest_comment_date DESC
                    LIMIT 5
                ");
                wp_cache_set( 'luntan_news', $list['news'], '', 3600 );
            }else{
                $list['news'] = wp_cache_get('luntan_news');
            }
            
            foreach($list['news'] as $k=>$v){
                
                $list['news'][$k]->luntan_replay_num =  get_post_meta($v->ID,'luntan_replay_num',true)?get_post_meta($v->ID,'luntan_replay_num',true):0;
                $list['news'][$k]->luntan_views =  get_post_meta($v->ID,'luntan_views',true)?get_post_meta($v->ID,'luntan_views',true):0;
                
                $list['news'][$k]->link = get_the_permalink($v->ID);
                $latest_comment = get_comments( array(
                    'post_id' => $v->ID,
                    'number' => 1,
                    'orderby' => 'comment_date_gmt',
                    'order' => 'DESC'
                ) );
                if($latest_comment){
                    $list['news'][$k]->comment_date = $latest_comment->comment_date;
                }
                
            }
            $list['hot'] = get_posts(array(
                'numberposts' => 5,
                'orderby'     => 'meta_value_num',
                'order'       => 'luntan_views',
                'post_type' => 'luntan',
                'post_status'=>'publish',
            ));
             foreach($list['hot'] as $k=>$v){
                $list['hot'][$k]->luntan_replay_num =  get_post_meta($v->ID,'luntan_replay_num',true)?get_post_meta($v->ID,'luntan_replay_num',true):0;
                $list['hot'][$k]->luntan_views =  get_post_meta($v->ID,'luntan_views',true)?get_post_meta($v->ID,'luntan_views',true):0;
                $list['hot'][$k]->link = get_the_permalink($v->ID);
            }
            echo wp_json_encode(['code'=>1,'data'=>$list]);exit;
            
        }
        echo wp_json_encode(['code'=>0,'msg'=>'获取失败']);exit;
    }
    public function luntan_cate_list(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            $categories = get_terms( array(
                'taxonomy'   => 'luntan_cate', // 自定义分类法的名称
                'hide_empty' => false,         // 是否隐藏没有关联文章的分类项
            ) );
            $arr = [];
            foreach ($categories as $category) {
                $arr[]=[
                    'cate'=>$category->name,
                    'id'=>$category->term_id,
                    
                ];
    
            }
            echo wp_json_encode(['code'=>1,'data'=>$arr]);exit;
        }
        echo wp_json_encode(['code'=>0,'msg'=>'获取失败']);exit;
    }
    public function luntan_avatar(){
        
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            if(!isset($_FILES['file'])){
                echo wp_json_encode(['code'=>0,'msg'=>'没有选择要上传的图片']);exit;
            }
            // 检查是否有文件上传
             $file =$this->luntan_img_san($_FILES['file']);
             if (!isset( $file['tmp_name'] ) ||  ! is_uploaded_file( $file['tmp_name'] ) || !is_file( $file['tmp_name'])) {
                echo wp_json_encode(['code'=>0,'msg'=>'没有选择要上传的图片']);exit;
            }
           
            // 检查上传过程中是否有错误
            if ($file['error']!= 0) {
                echo wp_json_encode(['code'=>0,'msg'=>'图片上传失败，请稍后重试！']);exit;
            }
             $upload_overrides = array( 'test_form' => false );
            $move_result = wp_handle_upload( $file, $upload_overrides );
            // 移动上传的文件到目标目录
            if ($move_result && !isset( $move_result['error'] )) {
                $target_url = $move_result['url'];
                update_user_meta( $user_id, 'luntan_avatar',$target_url );
                echo wp_json_encode(['code'=>1,'data'=>$target_url]);exit;
               
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'图片上传失败，请稍后重试！']);exit;
            }
            
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_sendemail(){
        
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
             $config = get_option('luntan_smtp_baocun');
            
            
            $subject = $config['nick'];
            $to = isset($_POST['email'])?sanitize_email(wp_unslash($_POST['email'])):'';
           
            $code = wp_rand(100000,999999);
            setcookie('luntan_code',$code,current_time('timestamp')+300);
            $message = '您的验证码是：'.$code;
            $headers = array('Content-Type: text/html; charset=UTF-8');
            if(wp_mail($to, $subject, $message, $headers)){
                echo wp_json_encode(['code'=>1,'msg'=>'发送成功']);exit;
            } else {
                echo wp_json_encode(['code'=>0,'msg'=>'发送失败']);exit;
            }
        }
    }
    public function luntan_get_user(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            $avatar = get_user_meta( $user_id, 'luntan_avatar',true );
            $nickname = get_user_meta( $user_id, 'nickname',true );
            if (current_user_can('administrator')) {
                $level =1;
            }else{
                $level = 0;
            }
            $pub_num = count(get_posts(array(
                    'author'=>$user_id,
                    'numberposts' => -1, // 获取所有符合条件的文章，-1表示无限制数量
                    'post_type' => 'luntan',
            )));
            echo wp_json_encode(['code'=>1,'user'=>$current_user,'avatar'=>$avatar,'nickname'=>$nickname,'level'=>$level,'pub_num'=>$pub_num]);exit;
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_get_post(){
        
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $wpdb;
            if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            $search = isset($_POST['search'])?sanitize_text_field(wp_unslash($_POST['search'])):'';
            
            $page = isset($_POST['page'])?(int)$_POST['page']:"";
            $limit = isset($_POST['limit'])?(int)$_POST['limit']:'';
            $start =  ($page-1)*$limit;
            if($search){
                $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where post_author=%d and post_status=%s  and post_type='luntan' and post_title like %s  order by ID desc limit %d,%d ",$user_id,isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):"",'%'.$search.'%',$start,$limit),ARRAY_A);
                $count = $wpdb->query($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where post_author=%d and post_status=%s and post_type='luntan' and post_title like %s ",$user_id,isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):"",'%'.$search.'%'),ARRAY_A);
            }else{
                $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where post_author=%d and post_status=%s  and post_type='luntan'  order by ID desc limit %d,%d ",$user_id,isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):"",$start,$limit),ARRAY_A);
                $count = $wpdb->query($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where post_author=%d and post_status=%s and post_type='luntan' ",$user_id,isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):""),ARRAY_A);
            }
            foreach($data as $k=>$v){
                $data[$k]['luntan_replay_num'] = get_post_meta($v['ID'],'luntan_replay_num',true)?get_post_meta($v['ID'],'luntan_replay_num',true):0;
            }
            echo wp_json_encode(['code'=>1,'data'=>$data,'count'=>$count,'pagesize'=>ceil($count/$limit)]);exit;
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_manage_post(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $wpdb;
            if ( !is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $keywords = sanitize_text_field(wp_unslash($_POST['keywords']));
            if($keywords){
                $count = $wpdb->query($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where post_status=%s and post_type='luntan' and post_title like %s ",isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):"",'%'.$keywords.'%'),ARRAY_A);
                $page = isset($_POST['page'])?(int)$_POST['page']:"";
                $limit = isset($_POST['limit'])?(int)$_POST['limit']:'';
                $start =  ($page-1)*$limit;
                $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where  post_status=%s  and post_type='luntan'   and post_title like %s  order by ID desc limit %d,%d ",isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):'','%'.$keywords.'%',$start,$limit),ARRAY_A);
                foreach($data as $k=>$v){
                    $data[$k]['luntan_replay_num'] = get_post_meta($v['ID'],'luntan_replay_num',true)?get_post_meta($v['ID'],'luntan_replay_num',true):0;
                    $luntan_img = get_post_meta($v['ID'],'luntan_img',true);
                    $data[$k]['img'] = explode(',',$luntan_img);
                    $data[$k]['cate'] = get_the_terms($v['ID'],'luntan_cate');
                    $avatar = get_user_meta( $v['post_author'], 'luntan_avatar',true );
                    $data[$k]['avatar'] = $avatar;
                    $user = get_userdata( $v['post_author'] );
                    $data[$k]['email'] = $user->user_email;
                    
                }
            }else{
                $count = $wpdb->query($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where post_status=%s and post_type='luntan' ",isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):""),ARRAY_A);
                $page = isset($_POST['page'])?(int)$_POST['page']:"";
                $limit = isset($_POST['limit'])?(int)$_POST['limit']:'';
                $start =  ($page-1)*$limit;
                $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".$wpdb->prefix ."posts  where  post_status=%s  and post_type='luntan'     order by ID desc limit %d,%d ",isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):'',$start,$limit),ARRAY_A);
                foreach($data as $k=>$v){
                    $data[$k]['luntan_replay_num'] = get_post_meta($v['ID'],'luntan_replay_num',true)?get_post_meta($v['ID'],'luntan_replay_num',true):0;
                    $luntan_img = get_post_meta($v['ID'],'luntan_img',true);
                    $data[$k]['img'] = explode(',',$luntan_img);
                    $data[$k]['cate'] = get_the_terms($v['ID'],'luntan_cate');
                    $avatar = get_user_meta( $v['post_author'], 'luntan_avatar',true );
                    $data[$k]['avatar'] = $avatar;
                    $user = get_userdata( $v['post_author'] );
                    $data[$k]['email'] = $user->user_email;
                    
                }
            }
            echo wp_json_encode(['code'=>1,'data'=>$data,'count'=>$count,'pagesize'=>ceil($count/$limit)]);exit;
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_delete_post(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $wpdb;
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            $id = explode(',',isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):'');
            $id = array_unique(array_map('absint', $id));
            if (current_user_can('administrator')) {
                global $luntan_wzt_log;
                if(!$luntan_wzt_log){
                    echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
                global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
                foreach($id as $k=>$v){
                    $res = $wpdb->query($wpdb->prepare("DELETE FROM " . $wpdb->prefix . "posts where ID=%d",$v));
                    if($res){
                        $res = $wpdb->query($wpdb->prepare("DELETE FROM " . $wpdb->prefix . "comments where comment_post_ID =%d",$v));
                        $luntan_img = get_post_meta($v,'luntan_img',true);
                        $luntan_img = explode(',',$luntan_img);
                        if(!empty($luntan_img)){
                            foreach($luntan_img as $key=>$val){
                                $site_root = isset($_SERVER['DOCUMENT_ROOT'])?sanitize_text_field(wp_unslash($_SERVER['DOCUMENT_ROOT'])):"";
                                    // 解析图片 URL 以获取相对路径
                                    $parsed_url = wp_parse_url($val);
                                    $path = $parsed_url['path'];
                                    $local_path = $site_root . $path;
                                
                                    // 检查文件是否存在
                                    if (file_exists($local_path)) {
                                        // 删除文件
                                        wp_delete_file($local_path);
                                    }
                            }
                        }
                        
                    }else{
                        echo wp_json_encode(['code'=>0,'msg'=>'删除失败，没有权限']);exit;
                    }
                }
                
            }else{
                foreach($id as $k=>$v){
                    $res = $wpdb->query($wpdb->prepare("DELETE FROM " . $wpdb->prefix . "posts where ID=%d and post_author=%d",$v,$user_id));
                    if($res){
                        $res = $wpdb->query($wpdb->prepare("DELETE FROM " . $wpdb->prefix . "comments where comment_post_ID =%d",$v));
                        $luntan_img = get_post_meta($v,'luntan_img',true);
                        $luntan_img = explode(',',$luntan_img);
                        if(!empty($luntan_img)){
                            foreach($luntan_img as $key=>$val){
                                $site_root = isset($_SERVER['DOCUMENT_ROOT'])?sanitize_text_field(wp_unslash($_SERVER['DOCUMENT_ROOT'])):"";
                                    // 解析图片 URL 以获取相对路径
                                    $parsed_url = wp_parse_url($val);
                                    $path = $parsed_url['path'];
                                    $local_path = $site_root . $path;
                                
                                    // 检查文件是否存在
                                    if (file_exists($local_path)) {
                                        // 删除文件
                                        wp_delete_file($local_path);
                                        
                                    }
                            }
                        }
                        
                    }else{
                        echo wp_json_encode(['code'=>0,'msg'=>'删除失败，没有权限']);exit;
                    }
                }
               
            }
            echo wp_json_encode(['code'=>1,'msg'=>'删除成功']);exit;
            
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_guolv_arr($arr){
        $data = [];
        foreach($arr as $k=>$v){
            $data[$k] =sanitize_text_field( wp_unslash($v['cate']));
        }
        return $data;
    }
    public function luntan_add_cate(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            
            if (current_user_can('administrator')) {
                //过滤数组
                $cate = $this->luntan_guolv_arr($_POST['cate']);
                
               
                global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
                foreach($cate as $k=>$v){
                    $name = $v;
                    $result = wp_insert_term(
                        $name,
                        'luntan_cate'
                    );
                }
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
            
            echo wp_json_encode(['code'=>1,'msg'=>'新增成功']);exit;
            
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_update_cate(){
        
         if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
             global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            
            if (current_user_can('administrator')) {
                $id = isset($_POST['id'])?(int)$_POST['id']:0;
                
                
                $cate = isset($_POST['cate'])?sanitize_text_field(wp_unslash($_POST['cate'])):"";
                $slug = isset($_POST['slug'])?sanitize_text_field(wp_unslash($_POST['slug'])):"";
                if(!$slug){
                     echo wp_json_encode(['code'=>0,'msg'=>'分类地址不能为空']);exit;
                }
              global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
                $result = wp_update_term(
                    $id,
                    'luntan_cate',
                    array(
                        'name' => $cate,
                        'slug'=>$slug
                       
                    )
                );
                
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
            
            echo wp_json_encode(['code'=>1,'msg'=>'编辑成功']);exit;
            
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_delete_cate(){
         if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
             global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            
            if (current_user_can('administrator')) {
                 $id = isset($_POST['id'])?(int)$_POST['id']:0;
                global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
               $result = wp_delete_term($id, 'luntan_cate');
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
            
            echo wp_json_encode(['code'=>1,'msg'=>'删除成功']);exit;
            
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_zhuanyi_post(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            
            if (current_user_can('administrator')) {
                $id = isset($_POST['cate1'])?(int)$_POST['cate1']:0;
                $ids = explode(',',isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):"");
               global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
                foreach($ids as $k=>$v){
                    $v =(int)$v;
                   
                    $res = wp_set_object_terms($v, $id,'luntan_cate');
                   
                    
                   
                }
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
            echo wp_json_encode(['code'=>1,'msg'=>'转移成功']);exit;
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_zhuanyi_cate(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            
            if (current_user_can('administrator')) {
                global $luntan_key;
             if(!$luntan_key){
                $pay = luntan_index::pay_money();
                if(!$pay){
                     echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                }
            }
                $id = isset($_POST['cate1'])?(int)$_POST['cate1']:0;
                $target_category_id = isset($_POST['cate2'])?(int)$_POST['cate2']:'';
                $posts_in_source_category = get_posts(array(
                    'tax_query' => array(
                                array(
                                    'taxonomy' => 'luntan_cate', // 自定义分类法名称
                                    'field'    => 'term_id', // 可以是 term_id、slug 等
                                    'terms'    => array( $id) // 要查询的分类 ID 数组
                                )
                            ),
                    'numberposts' => -1, // 获取所有符合条件的文章，-1表示无限制数量
                    'post_type' => 'luntan', // 根据实际情况，这里可调整为其他文章类型，如自定义文章类型等
                ));
                foreach ($posts_in_source_category as $post) {
                   
                    wp_set_object_terms($post->ID, $target_category_id,'luntan_cate');
                }
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
            
            echo wp_json_encode(['code'=>1,'msg'=>'转移成功']);exit;
            
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_get_cate(){
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $luntan_wzt_log;
            
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            
            if (current_user_can('administrator')) {
               $categories = get_terms( array(
                    'taxonomy'   => 'luntan_cate', // 自定义分类法的名称
                    'hide_empty' => false,         // 是否隐藏没有关联文章的分类项
                    'orderby'    => 'term_id',  // 按创建时间排序
                    'order'      => 'desc'          // 升序排列（从旧到新），DESC为降序（从新到旧）
                ));
                               
                $arr = [];
                foreach ($categories as $category) {
                 
                    
                    $arr[]=[
                        'cate'=>$category->name,
                        'id'=>$category->term_id,
                    // 获取每个分类下的文章数量
                     'num'=> count(get_posts(array(
                        'post_type' => 'luntan',
                        'numberposts' => -1,
                         'tax_query' => array(
                                array(
                                    'taxonomy' => 'luntan_cate', // 自定义分类法名称
                                    'field'    => 'term_id', // 可以是 term_id、slug 等
                                    'terms'    => array( $category->term_id ) // 要查询的分类 ID 数组
                                )
                            )
                    ))),
                    'slug'=>$category->slug
                    
                    ];
        
                }
                echo wp_json_encode(['code'=>1,'data'=>$arr]);exit;
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
        }
        echo wp_json_encode(['code'=>0]);exit;
         
    }
    public  function luntan_shenhe_post(){
         if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
             global $luntan_wzt_log;
            if(!$luntan_wzt_log){
                echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
            }
            global $wpdb;
            if (!is_user_logged_in() ) {
                echo wp_json_encode(['code'=>0,'msg'=>'请先登录']);exit;
            }
            $ids = explode(',',isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):"");
            $ids = array_unique(array_map('absint', $ids));
            if (current_user_can('administrator')) {
                global $luntan_key;
                 if(!$luntan_key){
                    $pay = luntan_index::pay_money();
                    if(!$pay){
                         echo wp_json_encode(['code'=>0,'msg'=>'请先授权']);exit;
                    }
                }
                //发送邮件提醒
                $luntan_smtp_baocun = get_option('luntan_smtp_baocun');
                foreach($ids as $k=>$v){
                    $res = $wpdb->update($wpdb->prefix . 'posts',['post_status'=>isset($_POST['post_status'])?sanitize_text_field(wp_unslash($_POST['post_status'])):''],['ID'=>(int)$v]);
                    if(isset($_POST['post_status']) && $_POST['post_status']=='publish' && isset($luntan_smtp_baocun['post']) && $luntan_smtp_baocun['post']){
                        $this->luntan_email(get_userdata(get_post((int)$v)->post_author)->user_email,'您的帖子"'.get_post((int)$v)->post_title.'"已审核通过');
                    }
                }
                echo wp_json_encode(['code'=>1,'msg'=>'操作成功']);exit;
            }else{
                echo wp_json_encode(['code'=>0,'msg'=>'没有权限']);exit;
            }
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    //去除字符串的反斜杠
    public function delete_fanxiegang($str){
        $str = stripslashes($str);
        $str = str_replace("\\",'',$str);
        return $str;
    }
    public function set_local_image_as_featured( $post_id, $image_url ) {
       
    
        // 转换图片 URL 为文件路径
        $upload_dir = wp_upload_dir(); // 获取上传目录
        $base_url   = $upload_dir['baseurl']; // 上传目录的 URL
        $base_path  = $upload_dir['basedir']; // 上传目录的物理路径
    
 
    
        // 获取图片的绝对路径
        $relative_path = str_replace( $base_url, '', $image_url );
        $file_path     = $base_path . $relative_path;
    
 
    
        // 插入附件到数据库
        $filetype = wp_check_filetype( basename( $file_path ), null );
        $attachment = array(
            'guid'           => $image_url, // 图片的完整 URL
            'post_mime_type' => $filetype['type'],
            'post_title'     => sanitize_file_name( wp_unslash(basename( $file_path )) ),
            'post_content'   => '',
            'post_status'    => 'inherit',
        );
    
        // 创建附件
        $attachment_id = wp_insert_attachment( $attachment, $file_path, $post_id );
    
        // 生成并保存元数据
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        $attach_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
        wp_update_attachment_metadata( $attachment_id, $attach_data );
    
        // 设置为特色图片
        set_post_thumbnail( $post_id, $attachment_id );
    }
     public function luntan_get_vip(){
        
        if(isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            global $luntan_wzt_log;
             $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,
            );
            $luntan_level = get_option('luntan_level');
            
            
            if(!isset($luntan_level[5]) || $luntan_level[5]<time()-24*3600 || !isset($luntan_level[2]) || (int)str_replace('.','',LUNTAN_VERSION)!=(int)str_replace('.','',$luntan_level[3])){
                $url = 'https://art.seohnzz.com/api/money/level9?url='. luntan_index::luntan_url(0);
                $result = wp_remote_get($url,$defaults);
                if(!is_wp_error($result)){
                    $level = wp_remote_retrieve_body($result);
                    
                    $level = json_decode($level,true);
                    
                    $level1 = explode(',',$level['level']);
                    $level1[2] = LUNTAN_VERSION;
                    $level1[3] = $level['version'];
                    $level1[4] = $luntan_wzt_log;
                    $level2 = $level1;
                    if(isset($level1[0]) && ($level1[0]==1 || $level1[0]==2)){
                        $level2[5] = time();
                        
                        update_option('luntan_level',$level2);
                        
                    }
                }
            }else{
                
                $level1 = $luntan_level;
                $level1[2] = LUNTAN_VERSION;
                $level1[4] = $luntan_wzt_log;
               
            }
            $data['level'] = $level1;                                   
            
            echo wp_json_encode(['code'=>1,'data'=>$data]);exit;
        }
        echo wp_json_encode(['code'=>0]);exit;
    }
    public function luntan_vip(){
        if(isset($_POST['nonce'])  && wp_verify_nonce(sanitize_text_field( wp_unslash($_POST['nonce'])),'luntan')){
            $key = isset($_POST['key'])?sanitize_text_field(wp_unslash($_POST['key'])):"";
            $data = luntan_index::luntan_url(0);
            $url1 = isset($_SERVER['SERVER_NAME'])?sanitize_text_field(wp_unslash($_SERVER['SERVER_NAME'])):"";
            $url = 'https://art.seohnzz.com/api/money/log2?url='.$data.'&url1='.$url1.'&key='.$key.'&type=9';
            $defaults = array(
                'timeout' => 120,
                'connecttimeout'=>120,
                '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)){
                $content = wp_remote_retrieve_body($result);
                if($content){
                    $luntan_wzt_log = get_option('luntan_wzt_log');
                    if($luntan_wzt_log!==false){
            	        update_option('luntan_wzt_log',$key);
            	    }else{
            	        add_option('luntan_wzt_log',$key);
            	    }
                    echo wp_json_encode(['code'=>1]);exit;
                }
        	}
        	echo wp_json_encode(['code'=>0]);exit;
        	
        
        }
    }
    
   

}