<?php
/**
 * CacheLoop – Disable Emojis (Free)
 *
 * Removes the inline emoji-detection script and CSS that WordPress core
 * loads on every page to support browsers without native emoji support.
 * Virtually every modern browser renders emoji natively, so this is dead
 * weight on almost all sites.
 *
 * @package CacheLoop
 */

// Security: Prevent direct file access.
defined( 'ABSPATH' ) || exit;

/**
 * Class CACHELOOP_Disable_Emojis
 */
class CACHELOOP_Disable_Emojis {

	/**
	 * Constructor: removes WordPress core's emoji hooks.
	 */
	public function __construct() {
		remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
		remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
		remove_action( 'wp_print_styles', 'print_emoji_styles' );
		remove_action( 'admin_print_styles', 'print_emoji_styles' );
		remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
		remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
		remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );

		// Prevent the emoji <script> from being reintroduced via TinyMCE.
		add_filter( 'tiny_mce_plugins', array( $this, 'remove_tinymce_emoji' ) );

		// Remove the emoji DNS-prefetch hint for s.w.org.
		add_filter( 'wp_resource_hints', array( $this, 'remove_emoji_dns_prefetch' ), 10, 2 );
	}

	/**
	 * Removes the "wpemoji" plugin from TinyMCE's plugin list.
	 *
	 * @param  array $plugins List of active TinyMCE plugins.
	 * @return array
	 */
	public function remove_tinymce_emoji( $plugins ) {
		if ( is_array( $plugins ) ) {
			return array_diff( $plugins, array( 'wpemoji' ) );
		}
		return array();
	}

	/**
	 * Removes the s.w.org DNS-prefetch hint added for emoji support.
	 *
	 * @param  array  $urls          URLs to print for resource hints.
	 * @param  string $relation_type The relation type (e.g. 'dns-prefetch').
	 * @return array
	 */
	public function remove_emoji_dns_prefetch( $urls, $relation_type ) {
		if ( 'dns-prefetch' === $relation_type ) {
			$emoji_url = 'https://s.w.org/images/core/emoji/';
			foreach ( $urls as $key => $url ) {
				if ( is_string( $url ) && strpos( $url, $emoji_url ) === 0 ) {
					unset( $urls[ $key ] );
				}
			}
		}
		return $urls;
	}
}
