<?php
/**
 * Plugin Name: Disable External Resources (Server-wide)
 * Description: Blocks unreachable external resources (Iran network restrictions)
 */

// Hard-code unreachable domains
function _server_is_blocked_domain($url) {
    if (!is_string($url) || empty($url)) return false;
    $blocked = [
        'fonts.googleapis.com', 'fonts.gstatic.com', 'ajax.googleapis.com',
        'maps.googleapis.com', 'maps.google.com',
        'google-analytics.com', 'www.google-analytics.com',
        'googletagmanager.com', 'www.googletagmanager.com',
        'connect.facebook.net', 'graph.facebook.com', 'fbcdn.net',
        'platform.twitter.com',
        'cdn.jsdelivr.net', 'cdnjs.cloudflare.com', 'unpkg.com',
        'use.fontawesome.com',
        'gravatar.com', 'secure.gravatar.com',
        'api.wordpress.org', 'downloads.wordpress.org',
        'api.elementor.com', 'my.elementor.com', 'library.elementor.com',
        'woocommerce.com', 'api.woocommerce.com',
        'rankmath.com', 'api.rankmath.com',
        'api.zhaket.com',
        'www.google.com/recaptcha',
        'github.com', 'raw.githubusercontent.com',
        'stackoverflow.com',
    ];
    foreach ($blocked as $d) {
        if (strpos($url, $d) !== false) return true;
    }
    return false;
}

// Block external CSS
add_filter('style_loader_src', function($src) {
    return _server_is_blocked_domain($src) ? false : $src;
}, 999);

// Block external JS
add_filter('script_loader_src', function($src) {
    return _server_is_blocked_domain($src) ? false : $src;
}, 999);

// Disable Gravatar
add_filter('option_show_avatars', '__return_false');

// Block HTTP requests to unreachable domains
add_filter('pre_http_request', function($pre, $args, $url) {
    if (_server_is_blocked_domain($url)) {
        return new WP_Error('blocked', 'Unreachable: ' . parse_url($url, PHP_URL_HOST));
    }
    return $pre;
}, 1, 3);

// Reduce HTTP timeout globally
add_filter('http_request_timeout', function($t) { return min($t, 5); });
add_filter('http_request_args', function($args) {
    if (isset($args['timeout']) && $args['timeout'] > 5) $args['timeout'] = 5;
    return $args;
});

// Disable emoji CDN
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');

// Disable oEmbed
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');

// Skip update checks on frontend
if (!is_admin() && !wp_doing_cron()) {
    add_filter('pre_site_transient_update_core', function() { return new stdClass; });
    add_filter('pre_site_transient_update_plugins', function() { return new stdClass; });
    add_filter('pre_site_transient_update_themes', function() { return new stdClass; });
}
