<?php
if(!defined('ABSPATH'))exit;
class baiduseo_youhua{
    public function init(){
        $baiduseo_youhua = get_option('baiduseo_youhua', []);
        if (empty($baiduseo_youhua)) return;
        $function_map = [
            'thumb'      => 'baiduseo_thumb',
            'head_dy'    => 'baiduseo_head_dy',
            'xml_rpc'    => 'baiduseo_xml_rpc',
            'feed'       => 'baiduseo_feed',
            'post_thumb' => 'baiduseo_post_thumb',
            'gravatar'   => 'baiduseo_gravatar',
            'lan'        => 'baiduseo_lan',
            'category'   => 'baiduseo_category',
            'wp_json'    => 'baiduseo_wp_json',
            'art_cron'   => 'baiduseo_art_cron', 
        ];
    
       
        foreach ($function_map as $option_key => $method_name) {
            if (isset($baiduseo_youhua[$option_key]) && $baiduseo_youhua[$option_key]) {
                $this->$method_name(); 
            }
        }
    }
    public function baiduseo_bootstrap() {
            
    	if(!wp_next_scheduled( 'baiduseo_art_cron' )){
            wp_schedule_event( time(), 'baiduseo_every_five_minute', 'baiduseo_art_cron' );
        }
        
    }
    public function baiduseo_cronexec() {
    	global $wpdb;
    	$scheduled_ids = $wpdb->get_col(
    		$wpdb->prepare(
    			"SELECT ID FROM {$wpdb->posts} WHERE post_date <= %s AND post_status = 'future' LIMIT %d",
    			current_time( 'mysql', 0 ),
    			20
    		)
    	);
    	
    	if ( ! count( $scheduled_ids ) ) {
    		return;
    	}
    
    	array_map( 'wp_publish_post', $scheduled_ids );
    }
    public function baiduseo_art_cron(){
        add_action( 'plugins_loaded', [$this,'baiduseo_bootstrap'] );
        add_action( 'baiduseo_art_cron',[$this,'baiduseo_cronexec'] );
        
        
        
    }
    public function  baiduseo_wp_json(){
        add_filter('rest_pre_dispatch', [$this,'baiduseo_restrict_rest_api_to_same_origin'], 10, 3);
        if(isset($_SERVER['REQUEST_URI']) && is_string($_SERVER['REQUEST_URI']) &&  strpos(sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), 'wp-sitemap-users') !== false){
                status_header(404);
            header('Content-Type: application/xml; charset=' . esc_attr(get_bloginfo('charset')));
            echo '<?xml version="1.0" encoding="' . esc_attr(get_bloginfo('charset')) . '"?>';
            echo '<error><message>Not Found</message></error>';
            exit;
        }
        add_filter('wp_sitemaps_add_provider', function ($provider, $name) {
            if ($name === 'users') {
                return false;
            }
            return $provider;
        }, 10, 2);

    }
    function baiduseo_remove_user_sitemap_from_index($entry, $provider) {
        // 检查当前条目是否为用户站点地图（匹配 "wp-sitemap-users-" 开头的URL）
        if ($provider === 'user' || $provider === 'users') {
            // 返回null表示从列表中移除该条目
            return false;
        }
        return $entry;
    }
    public function baiduseo_restrict_rest_api_to_same_origin($result, $wp_rest_server, $request ){
          // Check if it's a request to access users endpoint
        if (is_string($request->get_route()) &&  strpos( $request->get_route(), '/wp/v2/users' ) !== false ) {
            // Check if current user can edit users (typically administrators)
            if ( ! current_user_can( 'edit_users' ) ) {
                // Return a permission denied error
                 return '404 Forbidden';
                
            }
        }
        return $result;
    }
     public function baiduseo_thumb(){
        add_filter('pre_option_thumbnail_size_w',   '__return_zero');
        add_filter('pre_option_thumbnail_size_h',   '__return_zero');
        add_filter('pre_option_medium_size_w',      '__return_zero');
        add_filter('pre_option_medium_size_h',      '__return_zero');
        add_filter('pre_option_large_size_w',       '__return_zero');
        add_filter('pre_option_large_size_h',       '__return_zero');
    
        add_filter('intermediate_image_sizes_advanced', [$this,'disable_image_sizes']);

        
      
        add_filter('image_resize_dimensions', [$this,'disable_single_image_size'], 10, 6);
    }
    public  function disable_image_sizes($sizes) {
        unset($sizes['thumbnail']);
        unset($sizes['medium']);
        unset($sizes['large']);
        return $sizes;
    }
    //禁用特定图片尺寸生成
    public  function disable_single_image_size($size) {
        return false;
    }
    public function baiduseo_head_dy(){
        remove_action( 'wp_head', 'feed_links', 2 ); //移除feed
        remove_action( 'wp_head', 'feed_links_extra', 3 ); //移除feed
        remove_action( 'wp_head', 'rsd_link' ); //移除离线编辑器开放接口
        remove_action( 'wp_head', 'wlwmanifest_link' );  //移除离线编辑器开放接口
        remove_action( 'wp_head', 'index_rel_link' );//去除本页唯一链接信息
        remove_action('wp_head', 'parent_post_rel_link', 10, 0 );//清除前后文信息
        remove_action('wp_head', 'start_post_rel_link', 10, 0 );//清除前后文信息
        remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
        remove_action( 'wp_head', 'locale_stylesheet' );
        // remove_action('publish_future_post','check_and_publish_future_post',10, 1 );
        remove_action( 'wp_head', 'noindex', 1 );
        remove_action( 'wp_head', 'wp_generator' ); //移除WordPress版本
        remove_action( 'wp_head', 'rel_canonical' );
        remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
        remove_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
    }
    public function baiduseo_xml_rpc(){
        add_filter( 'xmlrpc_methods', [$this,'baiduseo_remove_xmlrpc_pingback_ping'] );
        
    }
    public function baiduseo_remove_xmlrpc_pingback_ping( $methods ) {
        unset( $methods['pingback.ping'] );
        return $methods;
    }
    public function baiduseo_feed(){
        add_action('do_feed', [$this,'baiduseo_digwp_disable_feed'], 1);
        add_action('do_feed_rdf', [$this,'baiduseo_digwp_disable_feed'], 1);
        add_action('do_feed_rss', [$this,'baiduseo_digwp_disable_feed'], 1);
        add_action('do_feed_rss2', [$this,'baiduseo_digwp_disable_feed'], 1);
        add_action('do_feed_atom', [$this,'baiduseo_digwp_disable_feed'], 1);
    }
    public function baiduseo_digwp_disable_feed(){
        wp_die('<h1>Feed已经关闭, 请访问网站<a href="'.esc_url(get_bloginfo('url')).'">首页</a>!</h1>');
    }
    public function baiduseo_post_thumb(){
        add_action('before_delete_post', [$this,'baiduseo_delete_post_and_attachments']);
    }
    public function baiduseo_delete_post_and_attachments($post_ID){
        global $wpdb;
    
        // ======================
        // 1. 处理特色图片
        // ======================
        $thumbnail_id = get_post_meta($post_ID, '_thumbnail_id', true);
        if ($thumbnail_id) {
            // 查询这个图片被多少篇文章使用
            $count = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(meta_id) FROM {$wpdb->postmeta} 
                WHERE meta_key = '_thumbnail_id' AND meta_value = %d",
                $thumbnail_id
            ));
    
            if ($count == 1) {
                // 只被当前文章使用 → 删除
                wp_delete_attachment($thumbnail_id, true);
            } else {
                // 被多篇使用 → 只删关联
                delete_post_meta($post_ID, '_thumbnail_id');
            }
        }
    
        // ======================
        // 2. 处理文章内附件
        // ======================
        $attachments = get_posts(array(
            'post_parent'    => $post_ID,
            'post_type'      => 'attachment',
            'posts_per_page' => -1
        ));
    
        foreach ($attachments as $attachment) {
            // 检查这个附件是否有其他父级文章（排除自己）
            $parent_count = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(ID) FROM {$wpdb->posts} 
                WHERE post_type != 'attachment' AND ID != %d AND post_parent = %d",
                $post_ID, $attachment->ID
            ));
    
            if ($parent_count == 0) {
                // 无其他文章使用 → 删除
                wp_delete_attachment($attachment->ID, true);
            } else {
                // 有其他文章使用 → 只解除关联
                wp_update_post(array(
                    'ID' => $attachment->ID,
                    'post_parent' => 0
                ));
            }
        }
    }
    public function baiduseo_gravatar(){
        add_filter( 'get_avatar', function ($avatar) {
            return '';
        }, 10, 3 );
    }
    public function baiduseo_lan(){
        add_filter( 'locale', [$this,'baiduseo_language'] );
    }
    public function baiduseo_language($locale) {
        $locale = ( is_admin() ) ? $locale : 'en_US';
        return $locale;
    }
    public function baiduseo_category(){
        register_activation_hook(__FILE__,    [$this,'baiduseo_refresh_rules']);
        register_deactivation_hook(__FILE__,  [$this,'baiduseo_deactivate']);
        
        /* actions */
        add_action('created_category',  [$this,'baiduseo_refresh_rules']);
        add_action('delete_category',   [$this,'baiduseo_refresh_rules']);
        add_action('edited_category',   [$this,'baiduseo_refresh_rules']);
        add_action('init',              [$this,'baiduseo_permastruct']);
        
        /* filters */
        add_filter('category_rewrite_rules', [$this,'baiduseo_rewrite_rules']);
        add_filter('query_vars',             [$this,'baiduseo_query_vars']);    // Adds 'category_redirect' query variable
        add_filter('request',                [$this,'baiduseo_request']);
    }
    public function baiduseo_refresh_rules() {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
    public function baiduseo_deactivate(){
        remove_filter( 'category_rewrite_rules', [$this,'baiduseo_rewrite_rules']); 
        $this->baiduseo_refresh_rules();
    }
    public function baiduseo_permastruct()
    {
        global $wp_rewrite;
        global $wp_version;
    
        if ( $wp_version >= 3.4 ) {
            $wp_rewrite->extra_permastructs['category']['struct'] = '%category%';
        } else {
            $wp_rewrite->extra_permastructs['category'][0] = '%category%';
        }
    }
    public function baiduseo_query_vars($public_query_vars) {
        $public_query_vars[] = 'category_redirect';
        return $public_query_vars;
    }
    function baiduseo_rewrite_rules($category_rewrite) {
        global $wp_rewrite;
        $category_rewrite=array();
    
        /* WPML is present: temporary disable terms_clauses filter to get all categories for rewrite */
        if ( class_exists( 'Sitepress' ) ) {
            global $sitepress;
    
            remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );
            $categories = get_categories( array( 'hide_empty' => false ) );
            //Fix provided by Albin here https://wordpress.org/support/topic/bug-with-wpml-2/#post-8362218
            //add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );
            add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ), 10, 4 );
        } else {
            $categories = get_categories( array( 'hide_empty' => false ) );
        }
    
        foreach( $categories as $category ) {
            $category_nicename = $category->slug;
    
            if ( $category->parent == $category->cat_ID ) {
                $category->parent = 0;
            } elseif ( $category->parent != 0 ) {
                $category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename;
            }
    
            $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
            $category_rewrite["({$category_nicename})/{$wp_rewrite->pagination_base}/?([0-9]{1,})/?$"] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
            $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';
        }
    
        // Redirect support from Old Category Base
        $old_category_base = get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category';
        $old_category_base = trim( $old_category_base, '/' );
        $category_rewrite[$old_category_base.'/(.*)$'] = 'index.php?category_redirect=$matches[1]';
        return $category_rewrite;
    }
    public function baiduseo_request($query_vars) {
        if( isset( $query_vars['category_redirect'] ) ) {
            $catlink = trailingslashit( get_option( 'home' ) ) . user_trailingslashit( $query_vars['category_redirect'], 'category' );
            status_header( 301 );
            header( "Location: $catlink" );
            exit();
        }
        return $query_vars;
    }
    
    
}