Plugin Directory

Changeset 3847091


Ignore:
Timestamp:
12/06/2026 03:19:29 AM (60 minutes ago)
Author:
tranduy258
Message:

Release 1.2.2: LiteSpeed server-cache-v4 WooCommerce bypass, closed-loop RUM preload, Live Speed Proof & WP.org hardening

Location:
vn-speed-optimizer/trunk
Files:
4 added
39 deleted
70 edited

Legend:

Unmodified
Added
Removed
  • vn-speed-optimizer/trunk/assets/admin.js

    r3810859 r3847091  
    3535    var cls =
    3636      type === "success" ? "vnspo-notice-success" : "vnspo-notice-error";
    37     var $n = $(
    38       '<div class="vnspo-notice ' +
    39         cls +
    40         '" style="margin:16px 28px 0">' +
    41         msg +
    42         "</div>",
    43     );
     37    var $n = $('<div class="vnspo-notice"></div>')
     38      .addClass(cls)
     39      .css("margin", "16px 28px 0")
     40      .text(String(msg || ""));
    4441    $(".vnspo-wrap").prepend($n);
    4542    setTimeout(function () {
  • vn-speed-optimizer/trunk/assets/aeo-dashboard.css

    r3810859 r3847091  
    1 /* VN-Nexus AEO Dashboard CSS */
     1/* VN Speed Optimizer AEO Dashboard CSS */
    22#vnspo-aeo-container {
    33    padding: 10px 0;
  • vn-speed-optimizer/trunk/readme.txt

    r3813133 r3847091  
    55Tested up to: 7.1
    66Requires PHP: 8.0
    7 Stable tag: 1.2.1
     7Stable tag: 1.2.2
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    3131Community asset sharing is optional and off by default. After pairing, enabling sharing, and confirming redistribution rights, an administrator may select eligible public raster images or WOFF2 files. The origin server uploads only those selected files and basic asset metadata to VN-Nexus Edge; quotas apply. Turning sharing off stops new uploads and queues revocation. This release does not share HTML, CSS, JavaScript, shop/customer/visitor data, or visitor-browser resources, and does not provide browser-to-browser delivery.
    3232
    33 Pro / Agency will be a separately installed add-on connected to VN-Nexus Global Edge. Paid Pro will not require resource sharing. This WordPress.org plugin does not contain hidden Pro code and does not download, install, or update executable Pro code. The Pro add-on and its account/download service are not available yet. Check the [VN Speed Optimizer product page](https://vn-nexus.com/vnspo-pro) for availability. Edge AI, package delivery, and other remote features remain subject to service terms, explicit setup, and documented data handling.
     33Pro / Agency (5+ sites, White-Label) is a separately installed add-on connected to VN-Nexus Global Edge. Paid Pro/Agency does not require resource sharing. This WordPress.org plugin contains no hidden Pro code and never downloads or runs remote PHP. See [VN Speed Optimizer Pro / Agency](https://vn-nexus.com/vnspo-pro) for details, terms, and data handling.
    3434
    3535= Compatibility and verification =
    … …  
    4949= Setup Wizard =
    5050
    51 The Setup Wizard guides you through initial configuration with three presets:
    52 
    53 * **Safe** - Minimal optimizations for compatibility
    54 * **Balanced** - A middle-ground starting point
    55 * **Aggressive** - More changes; test compatibility carefully
     51Choose an initial preset: **Safe**, **Balanced**, **Aggressive**, or **WooCommerce**.
    5652
    5753== Frequently Asked Questions ==
    … …  
    6965Yes. Cache and asset settings may interact with themes, plugins, or checkout flows. Start with Safe settings and verify on staging. Disable another page-cache plugin while comparing results.
    7066
    71 = Where can I get Pro? =
     67= Where can I get Pro or Agency? =
    7268
    73 A separate Pro add-on is planned and is not available yet. See the [product page](https://vn-nexus.com/vnspo-pro).
     69A separate Pro / Agency (5+ sites, White-Label) add-on is available at [vn-nexus.com/vnspo-pro](https://vn-nexus.com/vnspo-pro).
     70
     71== Screenshots ==
     72
     731. Dashboard overview with Cache Hit Rate, server readiness, and Live TTFB Before/After Speed Proof.
     742. Quick Speed Presets (Safe, Balanced, Aggressive, WooCommerce) and Simple/Advanced controls.
     753. CSS, JavaScript optimization, media, font, and preload controls.
     764. Site Diagnostics and Free vs Pro capability overview.
     775. WooCommerce and dynamic-request bypass status.
     786. Live LiteSpeed shared-hosting N=15 TTFB and tail-latency benchmark proof (2.81x median speedup, -64.42% TTFB).
     797. WooCommerce & authenticated 4/4 dynamic bypass verification and WordPress.org Plugin Check (0 errors).
     808. Closed-loop RUM to PreloadQueue architecture and Free 1.2.2 vs Pro 3.x capability overview.
    7481
    7582== Changelog ==
    7683
    77 = 1.2.0 - 2026-11-17 =
    78 * Added local page cache, cache controls, media tools, technical diagnostics, and optional Edge features.
     84= 1.2.2 - 2026-12-06 =
     85* Hardened LiteSpeed/Apache `server-cache-v4` rewrite rules with consistent WooCommerce bypass conditions and `Header merge Vary Accept-Encoding`.
     86* Added closed-loop RUM hot-path sanitization (`vnspo_rum_path_recorded`) feeding adaptive `PreloadQueue` load throttling and Live TTFB Before/After Speed Proof in Admin.
     87* Added real-data Site Diagnostics, Free vs Pro overview, opt-in Vietnam Speed Radar stats, Per-Script Auto-Heal Exclusion, 4 Speed Presets, Safe-Preview rollback, and security hardening (SSRF, CSV export, REST nonces, `uninstall.php`).
    7988
    8089== Upgrade Notice ==
    8190
    82 = 1.2.0 =
    83 Local-first performance tools with optional, administrator-initiated remote services.
     91= 1.2.2 =
     92Adds live site diagnostics, local RUM Auto-Priority Elements, opt-in Speed Radar, Safe-Preview rollback, and WordPress.org compliance hardening.
    8493
    8594== External Services ==
    … …  
    8796Local optimization works without remote services. No background Edge policy polling occurs. Remote services run only after the administrator enables a listed feature or starts the described action.
    8897
    89 = 1. VN-Nexus Edge (https://edge.vn-nexus.com) =
    90 * Used for pairing, optional aggregate metrics, selected public assets and admin-requested script rules. It receives standard connection data such as origin IP; policy requests contain no page URL/content.
    91 * Pairing sends a one-time code, random site reference and version. Asset sharing sends only files an administrator selects and confirms they may redistribute.
    92 * Privacy: https://vn-nexus.com/vnspo-pro/privacy
     98= 1. VN-Nexus Edge & Speed Radar (https://edge.vn-nexus.com, https://vn-nexus.com/radar) =
     99* Used for pairing, opt-in aggregate metrics, Speed Radar stats (`/api/v1/radar/stats`), admin-selected public assets, and script rules.
     100* Pairing sends a one-time code, random site reference, and version. Policy/Radar requests send no visitor PII. Privacy: https://vn-nexus.com/vnspo-pro/privacy | Terms: https://vn-nexus.com/vnspo-pro/terms
    93101
    94102= 2. AloNet administrator workspace (https://alonet.vn-nexus.com) =
    95 * Opens in a separate tab after an administrator clicks. The plugin sends no Matrix messages or session keys; the browser connects directly to AloNet. Privacy: https://vn-nexus.com/vnspo-pro/privacy
     103* Opens in a separate tab when clicked. Sends no Matrix messages or keys. Privacy: https://vn-nexus.com/vnspo-pro/privacy | Terms: https://vn-nexus.com/vnspo-pro/terms
    96104
    97105= 3. YouTube embeds (https://www.youtube-nocookie.com) =
    98 * The browser requests the selected video only after a visitor clicks play. YouTube receives the video ID and ordinary connection metadata. Privacy: https://policies.google.com/privacy
     106* Requested only when a visitor clicks play (video ID + connection metadata). Privacy: https://policies.google.com/privacy | Terms: https://www.youtube.com/t/terms
    99107
    100 = 4. Optional aggregate metrics =
    101 * Local RUM is off by default. When enabled, configured browser samples go to this WordPress site; URLs are not stored. Edge sharing separately requires consent and pairing, then sends a smoothed site-level LCP summary at most daily. Edge receives standard connection metadata, including origin IP, but no URL, page content, customer data or visitor IP.
    102 * Turn off Local RUM to stop new samples; turn off Aggregate metrics to stop Edge sends. Previously stored local history remains until retention or uninstall.
     108= 4. Optional aggregate metrics & Speed Radar =
     109* Local RUM is off by default; stored locally without full URLs. Edge metrics and Speed Radar require opt-in consent (`vnspeed_edge_metrics_consent`) and pairing, sending a smoothed site LCP summary at most daily. Disabling stops future sends.
    103110
    104111= 5. Google Fonts and Analytics (https://fonts.googleapis.com, https://www.googletagmanager.com, https://www.google-analytics.com) =
    105 * Fonts are requested when an administrator uses a Google Fonts feature. Local Analytics downloads Google's script only when enabled; configured analytics tags may send visitor events to Google. Privacy: https://policies.google.com/privacy
     112* Fonts/Analytics load only when enabled by the administrator. Privacy: https://policies.google.com/privacy | Terms: https://policies.google.com/terms
    106113
    107114= 6. Gravatar (https://www.gravatar.com) =
    108 * With Local Gravatar enabled, this site requests and caches avatars. Gravatar receives the avatar hash and ordinary connection metadata. Privacy: https://automattic.com/privacy/
     115* With Local Gravatar enabled, caches avatars using email hashes. Privacy: https://automattic.com/privacy/ | Terms: https://wordpress.com/tos/
    109116
    110117= 7. WebPageTest (https://www.webpagetest.org) =
    111 * A public page URL is sent only when the administrator starts a test. The service returns browser performance results under its own terms. Privacy: https://www.webpagetest.org/privacy.php
     118* Public URL is sent only when an admin triggers a test. Privacy: https://www.webpagetest.org/privacy.php
    112119
    113120= 8. Google Search Console (https://search.google.com/search-console) =
    114 * Optional read-only connection. Nothing is sent until an administrator connects an account or requests a property list or URL inspection. The plugin sends the site origin, selected property, and selected public URL to VN-Nexus Edge; Edge calls the Google Search Console API and keeps Google tokens on the Edge service. Google receives the API request for the selected property or URL.
    115 * Search Console reports are not added to community telemetry or AI prompts. Disconnecting removes this site's stored Edge tokens and reports, but does not revoke a Google application grant shared with other sites. Privacy: https://policies.google.com/privacy
     121* Optional read-only connection on explicit admin action; tokens stay on Edge and are not shared with telemetry/AI. Disconnecting clears stored site tokens/reports. Privacy: https://policies.google.com/privacy | Terms: https://policies.google.com/terms
    116122
    117123= Privacy Controls =
  • vn-speed-optimizer/trunk/src/Admin/AdminBarWidget.php

    r3810859 r3847091  
    316316        }
    317317
    318         $url = \esc_url_raw($_POST['url'] ?? '');
     318        $url = isset($_POST['url']) ? \esc_url_raw(\wp_unslash((string) $_POST['url'])) : '';
    319319        if (empty($url)) {
    320320            \wp_send_json_error(['message' => \__('Invalid URL', 'vn-speed-optimizer')]);
  • vn-speed-optimizer/trunk/src/Admin/ConflictManager.php

    r3810859 r3847091  
    6868    {
    6969        // Check on activation
    70         register_activation_hook(VNSPEED_PLUGIN_FILE, [$this, 'check_on_activation']);
     70        $plugin_file = defined('VNSPO_PLUGIN_FILE')
     71            ? VNSPO_PLUGIN_FILE
     72            : (defined('VNSPEED_PLUGIN_FILE') ? VNSPEED_PLUGIN_FILE : dirname(__DIR__, 2) . '/vn-speed-optimizer.php');
     73        register_activation_hook($plugin_file, [$this, 'check_on_activation']);
    7174
    7275        // Show admin notice
  • vn-speed-optimizer/trunk/src/Core/Application.php

    r3810859 r3847091  
    11<?php
    22namespace VNSPO\Core;
     3
     4if ( ! defined( 'ABSPATH' ) ) {
     5    exit;
     6}
    37
    48/**
  • vn-speed-optimizer/trunk/src/Core/Container.php

    r3813133 r3847091  
    11<?php
    22namespace VNSPO\Core;
     3
     4if ( ! defined( 'ABSPATH' ) ) {
     5    exit;
     6}
    37
    48/**
  • vn-speed-optimizer/trunk/src/Core/Facade.php

    r3810859 r3847091  
    11<?php
    22namespace VNSPO\Core;
     3
     4if ( ! defined( 'ABSPATH' ) ) {
     5    exit;
     6}
    37
    48/**
  • vn-speed-optimizer/trunk/src/Core/ServiceProvider.php

    r3810859 r3847091  
    11<?php
    22namespace VNSPO\Core;
     3
     4if ( ! defined( 'ABSPATH' ) ) {
     5    exit;
     6}
    37
    48/**
  • vn-speed-optimizer/trunk/src/Facades/Speed.php

    r3456323 r3847091  
    22
    33namespace VNSPO\Facades;
     4
     5if ( ! defined( 'ABSPATH' ) ) {
     6        exit;
     7}
    48
    59use VNSPO\Core\Facade;
  • vn-speed-optimizer/trunk/src/Providers/AIServiceProvider.php

    r3813133 r3847091  
    44
    55use VNSPO\Core\ServiceProvider;
    6 use VNSPO\Services\AI\SmartEyes;
    7 use VNSPO\Services\AI\NeuralCore;
    86use VNSPO\Services\SEO\AeoFrontend;
    97
    … …  
    1311
    1412        public function register() {
    15 
    16                 if ( class_exists( SmartEyes::class ) ) {
    17                         $this->app->singleton( 'smart.eyes', function () {
    18                                 return new SmartEyes();
    19                         } );
    20                 }
    21 
    22                 if ( class_exists( NeuralCore::class ) ) {
    23                         $this->app->singleton( 'neural.core', function () {
    24                                 return new NeuralCore();
    25                         } );
    26                 }
    27 
    2813                $this->app->singleton( 'aeo.frontend', function () {
    2914                        $aeo = new AeoFrontend();
    … …  
    3419
    3520        public function boot() {
    36 
    3721                self::ensureDefaultAiFlags();
    38                 $opts = \get_option( 'vnspo_options', array() );
    39 
    40                 // Smart Eyes / Visual AI can be stored either as standalone flags or dashboard aliases.
    41                 $smart_eyes_enabled = (bool) \get_option( 'vnspo_smart_eyes_enabled' )
    42                         || ! empty( $opts['vnspo_smart_eyes_enabled'] )
    43                         || ! empty( $opts['smart_eyes'] )
    44                         || ! empty( $opts['smart_eyes_enabled'] )
    45                         || ! empty( $opts['visual_ai'] )
    46                         || ! empty( $opts['visual_ai_enabled'] );
    47 
    48                 if ( $smart_eyes_enabled && class_exists( SmartEyes::class ) ) {
    49                         $this->app->make( 'smart.eyes' );
    50                 }
    51 
    52                 // Neural Core can be toggled by legacy standalone option or dashboard aliases.
    53                 $neural_core_enabled = (bool) \get_option( 'vnspo_neural_core_enabled' )
    54                         || ! empty( $opts['vnspo_neural_core_enabled'] )
    55                         || ! empty( $opts['neural_core'] )
    56                         || ! empty( $opts['neural_core_enabled'] );
    57 
    58                 if ( $neural_core_enabled && class_exists( NeuralCore::class ) ) {
    59                         $this->app->make( 'neural.core' );
    60                 }
    61 
    62                 // AI AutoPilot (v2.0) - reads 'ai_autopilot_enabled' (fixed from 'enable_autopilot').
    63                 if ( ! empty( $opts['ai_autopilot_enabled'] ) ) {
    64                         if ( class_exists( \VNSPO\Services\AI\AIAutoPilot::class ) ) {
    65                                 $autopilot = new \VNSPO\Services\AI\AIAutoPilot();
    66                                 $autopilot->boot();
    67                         }
    68                 }
    6922
    7023                // AEO Frontend (answer engine markup).
  • vn-speed-optimizer/trunk/src/Providers/AdminServiceProvider.php

    r3813133 r3847091  
    22
    33namespace VNSPO\Providers;
     4
     5if ( ! defined( 'ABSPATH' ) ) {
     6        exit;
     7}
    48
    59use VNSPO\Core\ServiceProvider;
  • vn-speed-optimizer/trunk/src/Providers/MainServiceProvider.php

    r3810859 r3847091  
    6363
    6464                $this->app->singleton( 'preconnect.hints', function ( $app ) {
     65                        $network_class = \VNSPO\Services\Optimization\Network\PreconnectHints::class;
     66                        if ( \class_exists( $network_class ) ) {
     67                                return $app->bound( $network_class )
     68                                        ? $app->make( $network_class )
     69                                        : new $network_class();
     70                        }
    6571                        return new \VNSPO\Services\Optimization\Tweaks\PreconnectHints();
    6672                } );
    … …  
    159165
    160166                $this->app->singleton( 'speculation.rules', function ( $app ) {
    161                         return new \VNSPO\Services\Optimization\Network\SpeculationRules();
     167                        $network_class = \VNSPO\Services\Optimization\Network\SpeculationRules::class;
     168                        return $app->bound( $network_class )
     169                                ? $app->make( $network_class )
     170                                : new $network_class();
    162171                } );
    163172
    … …  
    220229                                }
    221230                        } catch ( \Throwable $e ) {
    222                                 \error_log( '[VNSPO] vnspo_r2_verify_upload: ' . $e->getMessage() );
     231                                if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
     232                                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     233                                        \error_log( '[VNSPO] vnspo_r2_verify_upload: ' . $e->getMessage() );
     234                                }
    223235                        }
    224236                } );
    … …  
    245257                // ── AI + Image ────────────────────────────────────────────────────────
    246258
    247                 $this->app->singleton( 'adaptive.engine', function ( $app ) {
    248                         if ( class_exists( \VNSPO\Services\AI\AdaptiveEngine::class ) ) {
    249                                 return new \VNSPO\Services\AI\AdaptiveEngine();
    250                         }
     259                $this->app->singleton( 'adaptive.engine', function () {
    251260                        return null;
    252261                } );
    253262
    254                 $this->app->singleton( 'cwv.adaptive.engine', function ( $app ) {
    255                         if ( class_exists( \VNSPO\Services\Optimization\AdaptiveEngine::class ) ) {
    256                                 return new \VNSPO\Services\Optimization\AdaptiveEngine();
    257                         }
     263                $this->app->singleton( 'cwv.adaptive.engine', function () {
    258264                        return null;
    259265                } );
    … …  
    418424                $this->app->make( 'ObjectCache' );
    419425
    420                 // AI features (PRO - self-gate inside constructors)
    421                 $this->app->make( 'adaptive.engine' );
    422 
    423                 // CWV Adaptive Engine (Optimization namespace)
    424                 if ( $is_opt_on( 'adaptive_engine_enabled' ) ) {
    425                         $cwv = $this->app->make( 'cwv.adaptive.engine' );
    426                         if ( $cwv && method_exists( $cwv, 'boot' ) ) {
    427                                 $cwv->boot();
    428                         }
    429                 }
    430 
    431426                // Legacy R2 mirroring is intentionally not booted in the WordPress.org build.
    432427                // Public sharing runs through PublicAssetSharing after per-file selection and consent.
  • vn-speed-optimizer/trunk/src/Providers/OptimizationServiceProvider.php

    r3813133 r3847091  
    509509                \add_action( 'wp_enqueue_scripts', function () {
    510510                        if ( \current_user_can( 'manage_options' ) ) {
     511                                $plugin_url = \defined( 'VNSPO_PLUGIN_URL' ) ? VNSPO_PLUGIN_URL : ( \defined( 'VNSPEED_PLUGIN_URL' ) ? VNSPEED_PLUGIN_URL : '' );
     512                                $version    = \defined( 'VNSPO_VERSION' ) ? VNSPO_VERSION : ( \defined( 'VNSPEED_VERSION' ) ? VNSPEED_VERSION : '1.2.2' );
    511513                                \wp_enqueue_script(
    512514                                        'vnspo-admin-tracker',
    513                                         VNSPEED_PLUGIN_URL . 'assets/js/admin-tracker.js',
     515                                        $plugin_url . 'assets/js/admin-tracker.js',
    514516                                        array( 'jquery' ),
    515                                         VNSPEED_VERSION,
     517                                        $version,
    516518                                        true
    517519                                );
  • vn-speed-optimizer/trunk/src/Providers/PageSpeedOptimizationProvider.php

    r3810859 r3847091  
    6262                $this->try_singleton( 'speculation_optimizer',     'VNSPO\\Services\\Optimization\\SpeculationRulesOptimizer' );
    6363                $this->try_singleton( 'edge_cache_optimizer',      'VNSPO\\Services\\Optimization\\EdgeCacheOptimizer' );
    64                 $this->try_singleton( 'adaptive_engine',           'VNSPO\\Services\\Optimization\\AdaptiveEngine' );
    6564                $this->try_singleton( 'semantic_cache',            'VNSPO\\Services\\Optimization\\SemanticCacheLayer' );
    6665                $this->try_singleton( 'bot_intel',                 'VNSPO\\Services\\Optimization\\BotIntelligence' );
    … …  
    108107                $this->safe_boot( 'speculation_optimizer',     $on( 'speculation_enabled' ) );
    109108                $this->safe_boot( 'edge_cache_optimizer',      $on( 'edge_cache_enabled' ) );
    110                 $this->safe_boot( 'adaptive_engine',           $on( 'adaptive_engine_enabled' ) );
    111109                $this->safe_boot( 'semantic_cache',            $on( 'semantic_cache_enabled' ) );
    112110                $this->safe_boot( 'bot_intel',                 $on( 'bot_intel_enabled' ) );
    … …  
    141139                        }
    142140                } catch ( \Throwable $e ) {
    143                         \error_log( "[VNSPO] {$key} boot FAIL: " . $e->getMessage() );
     141                        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
     142                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     143                                \error_log( "[VNSPO] {$key} boot FAIL: " . $e->getMessage() );
     144                        }
    144145                }
    145146        }
    … …  
    166167                        }
    167168                } catch ( \Throwable $e ) {
    168                         \error_log( '[VNSPO] LiteSpeedPageCache boot FAIL: ' . $e->getMessage() );
     169                        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
     170                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     171                                \error_log( '[VNSPO] LiteSpeedPageCache boot FAIL: ' . $e->getMessage() );
     172                        }
    169173                }
    170174        }
  • vn-speed-optimizer/trunk/src/Services/AI/ReviewQueue.php

    r3810859 r3847091  
    117117    {
    118118        if (!$this->activePreviewItem()) return;
    119         $version = defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.9';
    120         \wp_enqueue_script('vnspeed-safe-preview', VNSPEED_PLUGIN_URL . 'assets/js/safe-preview.js', [], $version, true);
     119        $version    = defined('VNSPO_VERSION') ? VNSPO_VERSION : (defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
     120        $plugin_url = defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     121        \wp_enqueue_script('vnspeed-safe-preview', $plugin_url . 'assets/js/safe-preview.js', [], $version, true);
    121122        \wp_localize_script('vnspeed-safe-preview', 'vnspoSafePreview', [
    122123            'ajaxUrl' => \admin_url('admin-ajax.php'),
    … …  
    564565    {
    565566        if (!\current_user_can('manage_options')) return '';
    566         \wp_enqueue_script('vnspeed-ai-review', VNSPEED_PLUGIN_URL . 'assets/js/ai-review-queue.js', [], defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.9', true);
     567        $plugin_url = defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     568        $version    = defined('VNSPO_VERSION') ? VNSPO_VERSION : (defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
     569        \wp_enqueue_script('vnspeed-ai-review', $plugin_url . 'assets/js/ai-review-queue.js', [], $version, true);
    567570        $html = '<section class="vnspeed-ai-review" data-endpoint="' . \esc_url(\admin_url('admin-ajax.php')) . '"><h3>' . \esc_html__('AI proposals awaiting review', 'vn-speed-optimizer') . '</h3>';
    568571        $html .= '<p>' . \esc_html__('Background analysis only creates proposals. Review the current and proposed values before approving. Approved changes are checked after 24 hours only when at least 10 comparable administrator diagnostic samples exist for the required signals; otherwise they remain Applied. Verified means stable in those administrator checks, not a guarantee across visitor traffic. Rollback is available for seven days unless the setting changes again. Informational findings require manual investigation.', 'vn-speed-optimizer') . '</p><p role="status" aria-live="polite" class="vnspeed-review-status"></p>';
  • vn-speed-optimizer/trunk/src/Services/Admin/AdminPage.php

    r3813133 r3847091  
    1414class AdminPage
    1515{
     16    use AdminPageTabsTrait;
     17
    1618    private $tabs = array(
    1719        'dashboard'   => 'Dashboard',
    … …  
    3436    /**
    3537     * Get all option keys from OptionsRegistry.
    36      * This replaces the hardcoded $all_options array.
     38     * This replaces the static $all_options array.
    3739     *
    3840     * @return array
    … …  
    121123        \add_action('wp_ajax_vnspo_rum_beacon', array($this, 'ajaxRumBeacon'));
    122124        \add_action('wp_ajax_nopriv_vnspo_rum_beacon', array($this, 'ajaxRumBeacon'));
     125        \add_action('wp_ajax_vnspo_rollback_latest', array($this, 'ajaxRollbackLatest'));
     126        \add_action('wp_ajax_vnspo_cwv_report', array($this, 'ajaxCwvReport'));
     127        \add_action('wp_ajax_vnspo_preview_url', array($this, 'ajaxPreviewUrl'));
     128        \add_action('wp_ajax_vnspo_apply_preset', array($this, 'ajaxApplyPreset'));
     129        \add_action('wp_ajax_vnspo_toggle_ui_mode', array($this, 'ajaxToggleUiMode'));
     130        \add_action('wp_ajax_vnspo_clear_auto_heal_exclusions', array($this, 'ajaxClearAutoHealExclusions'));
     131        \add_action('wp_ajax_vnspo_reset_priority_elements', array($this, 'ajaxResetPriorityElements'));
    123132        \add_action('wp_footer', array($this, 'renderFrontendRumBeacon'), 99);
    124133        \add_action('vnspo_ota_policy_cron', array($this, 'syncOtaPolicyFromEdge'));
    … …  
    131140    public function addAdminMenu()
    132141    {
     142        $menu_title = (string) \apply_filters('vnspo_menu_title', __('VN Speed Optimizer', 'vn-speed-optimizer'));
    133143        \add_menu_page(
    134             __('VN Speed Optimizer', 'vn-speed-optimizer'),
    135             __('VN Speed Optimizer', 'vn-speed-optimizer'),
     144            $menu_title,
     145            $menu_title,
    136146            'manage_options',
    137147            'vn-speed-optimizer',
    … …  
    244254                // string — select, text, textarea
    245255                $options[$key] = isset($_POST['vnspo_options'][$key])
    246                     ? \sanitize_text_field($_POST['vnspo_options'][$key])
     256                    ? \sanitize_text_field((string) \wp_unslash($_POST['vnspo_options'][$key]))
    247257                    : (isset($def['default']) ? $def['default'] : '');
    248258            }
    … …  
    373383
    374384        $options = \get_option('vnspo_options', array());
     385        if (\is_array($options) && 1 === (int) $value && \in_array($option, array('delay_js', 'rucss', 'minify_js', 'minify_css', 'defer_js'), true)) {
     386            SafePreviewRollback::saveCheckpoint($options, $option);
     387        }
    375388
    376389        // Handle special options & keep community opt-in state mirrored cleanly
    … …  
    382395
    383396        if (in_array($option, array('vnspeed_edge_metrics_consent', 'vnspeed_edge_asset_consent', 'community_acceleration', 'community_cdn'), true)) {
    384             $is_any_opted_in = (bool) \get_option('vnspeed_edge_metrics_consent', false)
    385                 || (bool) \get_option('vnspeed_edge_asset_consent', false);
    386             if (class_exists('\VNSPO\Services\Cloud\LocalHubResponder')) {
    387                 \VNSPO\Services\Cloud\LocalHubResponder::registerLocalNodeHeartbeat($is_any_opted_in);
    388             }
    389397            \delete_transient('vnspo_community_mesh_status_v3');
    390398        }
    … …  
    979987
    980988    /**
     989     * Detect cache hit headers emitted by VNSPO Free, LiteSpeed, or Cloudflare.
     990     */
     991    public static function isCacheHitHeader(string $vnspo_hdr, string $ls_hdr = '', string $cf_hdr = ''): bool
     992    {
     993        return (0 === stripos(trim($vnspo_hdr), 'HIT'))
     994            || (0 === strcasecmp(trim($ls_hdr), 'hit'))
     995            || (0 === strcasecmp(trim($cf_hdr), 'HIT'));
     996    }
     997
     998    /**
    981999     * Measure real multi-page TTFB: Origin (nocache) vs Warm Cache (2nd hit).
    9821000     */
    … …  
    9931011        $sum_origin = 0;
    9941012        $sum_cached = 0;
     1013        $last_cache_header = '';
     1014        $last_vary_header  = '';
     1015        $sum_origin_bytes  = 0;
     1016        $sum_cached_bytes  = 0;
    9951017
    9961018        foreach ($targets as $target) {
    … …  
    10091031                continue;
    10101032            }
     1033            $origin_bytes = strlen((string) \wp_remote_retrieve_body($res_origin));
    10111034
    10121035            // Warm once then measure cached hit
    … …  
    10181041                continue;
    10191042            }
     1043            $cached_bytes = strlen((string) \wp_remote_retrieve_body($res_cached));
    10201044
    10211045            $vnspo_hdr = (string) \wp_remote_retrieve_header($res_cached, 'x-vnspo-cache');
    10221046            $ls_hdr    = (string) \wp_remote_retrieve_header($res_cached, 'x-litespeed-cache');
    10231047            $cf_hdr    = (string) \wp_remote_retrieve_header($res_cached, 'cf-cache-status');
    1024             $cache_hit = (0 === strcasecmp($vnspo_hdr, 'HIT'))
    1025                 || (0 === strcasecmp($ls_hdr, 'hit'))
    1026                 || (0 === strcasecmp($cf_hdr, 'HIT'));
     1048            $vary_hdr  = (string) \wp_remote_retrieve_header($res_cached, 'vary');
     1049            $cache_hit = self::isCacheHitHeader($vnspo_hdr, $ls_hdr, $cf_hdr);
     1050            $resolved_hdr = $vnspo_hdr ?: ($ls_hdr ?: $cf_hdr);
     1051            if ('' !== $resolved_hdr) {
     1052                $last_cache_header = $resolved_hdr;
     1053            }
     1054            if ('' !== $vary_hdr) {
     1055                $last_vary_header = $vary_hdr;
     1056            }
    10271057
    10281058            $saved = max(0, $origin_ms - $cached_ms);
    … …  
    10341064                'origin_ms'       => $origin_ms,
    10351065                'cached_ms'       => $cached_ms,
     1066                'origin_bytes'    => $origin_bytes,
     1067                'cached_bytes'    => $cached_bytes,
    10361068                'improvement_pct' => $pct,
    10371069                'cache_hit'       => $cache_hit,
    1038                 'cache_header'    => $vnspo_hdr ?: ($ls_hdr ?: $cf_hdr),
     1070                'cache_header'    => $resolved_hdr,
    10391071            );
    10401072            $sum_origin += $origin_ms;
    10411073            $sum_cached += $cached_ms;
     1074            $sum_origin_bytes += $origin_bytes;
     1075            $sum_cached_bytes += $cached_bytes;
    10421076        }
    10431077
    … …  
    10511085        $saved_ms = max(0, $avg_origin_ms - $avg_cached_ms);
    10521086        $improvement_pct = $avg_origin_ms > 0 ? (int) round(($saved_ms / $avg_origin_ms) * 100) : 0;
     1087        $speedup_factor  = $avg_cached_ms > 0 ? round($avg_origin_ms / $avg_cached_ms, 1) : 0.0;
    10531088
    10541089        $options = \get_option('vnspo_options', array());
    … …  
    10621097            'saved_ms'        => $saved_ms,
    10631098            'improvement_pct' => $improvement_pct,
     1099            'speedup_factor'  => $speedup_factor,
     1100            'cache_header'    => $last_cache_header,
     1101            'vary_header'     => $last_vary_header,
     1102            'origin_bytes'    => (int) round($sum_origin_bytes / $count),
     1103            'cached_bytes'    => (int) round($sum_cached_bytes / $count),
    10641104            'pages_count'     => $count,
    10651105            'pages'           => $pages,
    … …  
    11131153        if ('toplevel_page_vn-speed-optimizer' !== $hook) return;
    11141154
    1115         $plugin_dir = defined('VNSPEED_PATH') ? VNSPEED_PATH : dirname(__DIR__, 3) . '/';
    1116         $css_ver = VNSPEED_VERSION . '-' . (string) (@filemtime($plugin_dir . 'assets/admin.css') ?: '0');
    1117         $js_ver  = VNSPEED_VERSION . '-' . (string) (@filemtime($plugin_dir . 'assets/admin.js') ?: '0');
     1155        $plugin_dir = defined('VNSPO_PATH') ? VNSPO_PATH : (defined('VNSPEED_PATH') ? VNSPEED_PATH : dirname(__DIR__, 3) . '/');
     1156        $plugin_url = defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     1157        $version    = defined('VNSPO_VERSION') ? VNSPO_VERSION : (defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
     1158        $css_ver    = $version . '-' . (string) (@filemtime($plugin_dir . 'assets/admin.css') ?: '0');
     1159        $js_ver     = $version . '-' . (string) (@filemtime($plugin_dir . 'assets/admin.js') ?: '0');
    11181160
    11191161        \wp_enqueue_style(
    11201162            'vnspo-admin-css',
    1121             VNSPEED_PLUGIN_URL . 'assets/admin.css',
     1163            $plugin_url . 'assets/admin.css',
    11221164            array(),
    11231165            $css_ver
    … …  
    11261168        \wp_enqueue_script(
    11271169            'vnspo-admin-js',
    1128             VNSPEED_PLUGIN_URL . 'assets/admin.js',
     1170            $plugin_url . 'assets/admin.js',
    11291171            array('jquery'),
    11301172            $js_ver,
    … …  
    11911233        $db_size = $this->getDatabaseSizeMb();
    11921234
    1193         $eyes_active = class_exists('VNSPO\\Services\\AI\\SmartEyes') && (bool) \get_option('vnspo_smart_eyes_enabled');
     1235        $plugin_file = defined('VNSPO_PLUGIN_FILE')
     1236            ? VNSPO_PLUGIN_FILE
     1237            : (defined('VNSPEED_PLUGIN_FILE') ? VNSPEED_PLUGIN_FILE : dirname(__DIR__, 3) . '/vn-speed-optimizer.php');
    11941238        $plugin_header = function_exists('get_file_data')
    1195             ? \get_file_data(VNSPEED_PLUGIN_FILE, array('Version' => 'Version'), 'plugin')
     1239            ? \get_file_data($plugin_file, array('Version' => 'Version'), 'plugin')
    11961240            : array();
    1197         $display_version = ! empty($plugin_header['Version']) ? $plugin_header['Version'] : '1.2.0';
     1241        $display_version = ! empty($plugin_header['Version']) ? $plugin_header['Version'] : '1.2.2';
    11981242        $supported_langs = array('en', 'vi', 'de', 'fr', 'es', 'ja');
    11991243        $forced_lang = (\function_exists('get_current_user_id') && \get_current_user_id() > 0)
    … …  
    12411285            </svg>
    12421286        </div>
     1287        <?php
     1288        $brand_name        = (string) \apply_filters('vnspo_brand_name', 'VN Speed Optimizer');
     1289        $default_subtitle  = $pro_licensed
     1290            ? __('Pro Engine Active — RUCSS, Smart Delay JS, Bulk AVIF & Edge Purge', 'vn-speed-optimizer')
     1291            : __('Local-first optimization with optional Edge services', 'vn-speed-optimizer');
     1292        $brand_subtitle    = (string) \apply_filters('vnspo_brand_subtitle', $default_subtitle);
     1293        $hide_vendor_links = (bool) \apply_filters('vnspo_hide_vendor_links', false);
     1294        $support_url       = (string) \apply_filters('vnspo_support_url', 'https://wordpress.org/support/plugin/vn-speed-optimizer/');
     1295        ?>
    12431296        <div>
    12441297            <h1 class="vnspo-title" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
    1245                 VN Speed Optimizer
     1298                <?php echo esc_html($brand_name); ?>
    12461299                <?php if ($pro_licensed) : ?>
    12471300                    <span style="display:inline-flex;align-items:center;padding:3px 10px;border-radius:999px;font-size:12px;font-weight:700;letter-spacing:0.04em;line-height:1.2;background:linear-gradient(135deg,#f59e0b,#d97706);color:#fff;box-shadow:0 2px 6px rgba(217,119,6,.35);"><?php echo esc_html($pro_tier ?: 'PRO'); ?></span>
    … …  
    12511304            </h1>
    12521305            <p class="vnspo-subtitle">
    1253                 <?php echo $pro_licensed
    1254                     ? esc_html__('Pro Engine Active — RUCSS, Smart Delay JS, Bulk AVIF & Edge Purge', 'vn-speed-optimizer')
    1255                     : esc_html__('Local-first optimization with optional Edge services', 'vn-speed-optimizer'); ?>
     1306                <?php echo esc_html($brand_subtitle); ?>
    12561307            </p>
    12571308        </div>
    12581309    </div>
     1310<?php
     1311$ui_mode = 'advanced' === \get_option('vnspo_ui_mode', 'simple') ? 'advanced' : 'simple';
     1312$auto_heal_exclusions = class_exists(\VNSPO\Services\Optimization\Assets\DelayJsConfig::class)
     1313    ? \VNSPO\Services\Optimization\Assets\DelayJsConfig::get_auto_heal_exclusions()
     1314    : array();
     1315?>
    12591316    <div class="vnspo-header-actions">
    12601317        <span class="vnspo-version-badge">v<?php echo esc_html($display_version); ?></span>
     1318        <button type="button" class="vnspo-btn-ghost" id="vnspo-btn-ui-mode" data-mode="<?php echo esc_attr($ui_mode); ?>">
     1319            <?php echo 'advanced' === $ui_mode
     1320                ? esc_html__('Switch to Simple Mode', 'vn-speed-optimizer')
     1321                : esc_html__('Switch to Advanced Mode', 'vn-speed-optimizer'); ?>
     1322        </button>
    12611323        <span class="vnspo-language-switch" role="group" aria-label="<?php echo esc_attr__('Admin language', 'vn-speed-optimizer'); ?>" title="<?php echo esc_attr__('Switch plugin interface language', 'vn-speed-optimizer'); ?>">
    12621324            <?php foreach ($supported_langs as $lang_slug) :
    … …  
    12761338            <?php echo esc_html__('Recommended Setup', 'vn-speed-optimizer'); ?>
    12771339        </button>
     1340    </div>
     1341</div>
     1342
     1343<?php
     1344$cwv_report = SafePreviewRollback::getWeeklyCwvReport();
     1345$safe_preview_url = SafePreviewRollback::buildPreviewUrl();
     1346$cwv_lcp_text = null !== $cwv_report['avg_lcp_7d_ms']
     1347    ? sprintf('%d ms', (int) $cwv_report['avg_lcp_7d_ms'])
     1348    : __('No RUM samples yet', 'vn-speed-optimizer');
     1349$cwv_delta_text = null !== $cwv_report['delta_pct']
     1350    ? sprintf(' (%s%.1f%%)', ((float) $cwv_report['delta_pct']) >= 0 ? '+' : '', (float) $cwv_report['delta_pct'])
     1351    : '';
     1352$cwv_badge_color = 'regression_alert' === $cwv_report['status'] ? '#b91c1c' : ('healthy' === $cwv_report['status'] ? '#15803d' : '#475569');
     1353?>
     1354<div id="vnspo-cwv-safety-bar" style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding:10px 14px;margin:0 0 14px;border-radius:10px;border:1px solid #cbd5e1;background:#f8fafc;font-size:13px;">
     1355    <div>
     1356        <strong style="color:<?php echo esc_attr($cwv_badge_color); ?>;">
     1357            <?php echo esc_html__('Core Web Vitals (7d RUM LCP):', 'vn-speed-optimizer'); ?>
     1358            <?php echo esc_html($cwv_lcp_text . $cwv_delta_text); ?>
     1359        </strong>
     1360        <?php if (!empty($cwv_report['last_rollback']['rolled_back_at'])) : ?>
     1361            <span style="margin-left:8px;color:#b45309;">
     1362                <?php echo esc_html(sprintf(__('Last rollback: %s', 'vn-speed-optimizer'), \gmdate('Y-m-d H:i', (int) $cwv_report['last_rollback']['rolled_back_at']))); ?>
     1363            </span>
     1364        <?php endif; ?>
     1365        <?php if (!empty($auto_heal_exclusions)) : ?>
     1366            <span id="vnspo-ah-exclusions-badge" style="margin-left:8px;color:#1d4ed8;">
     1367                <?php echo esc_html(sprintf(__('Auto-excluded JS: %s', 'vn-speed-optimizer'), implode(', ', $auto_heal_exclusions))); ?>
     1368            </span>
     1369        <?php endif; ?>
     1370    </div>
     1371    <div style="display:flex;gap:8px;flex-wrap:wrap;">
     1372        <a class="vnspo-btn-ghost" href="<?php echo esc_url($safe_preview_url); ?>" target="_blank" rel="noopener noreferrer">
     1373            <?php echo esc_html__('Safe-Preview Homepage', 'vn-speed-optimizer'); ?>
     1374        </a>
     1375        <button type="button" class="vnspo-btn-ghost" id="vnspo-btn-rollback-latest">
     1376            <?php echo esc_html__('Rollback Last Safe Snapshot', 'vn-speed-optimizer'); ?>
     1377        </button>
     1378        <?php if (!empty($auto_heal_exclusions)) : ?>
     1379            <button type="button" class="vnspo-btn-ghost" id="vnspo-btn-clear-ah-exclusions">
     1380                <?php echo esc_html__('Reset Exclusions', 'vn-speed-optimizer'); ?>
     1381            </button>
     1382        <?php endif; ?>
    12781383    </div>
    12791384</div>
    … …  
    13001405        break;
    13011406    }
     1407}
     1408if ('simple' === $ui_mode) {
     1409    $simple_groups = array('overview', 'performance', 'cache', 'media', 'pro');
     1410    $navigation_groups = array_filter(
     1411        $navigation_groups,
     1412        function ($group, $group_id) use ($simple_groups, $active_group) {
     1413            return in_array($group_id, $simple_groups, true) || $group_id === $active_group;
     1414        },
     1415        ARRAY_FILTER_USE_BOTH
     1416    );
    13021417}
    13031418?>
    … …  
    13891504        echo $this->renderProComparisonAndPlans('VI' === $language_code); ?>
    13901505<?php endif; ?>
     1506<?php
     1507$speed_presets = $this->getSpeedPresets();
     1508$active_preset = isset($options['active_preset']) ? \sanitize_key((string) $options['active_preset']) : '';
     1509?>
     1510<section id="vnspo-presets-bar" style="margin:0 0 16px;padding:14px 16px;border:1px solid #cbd5e1;border-radius:12px;background:#ffffff;" aria-label="<?php echo esc_attr__('1-Click Speed Presets', 'vn-speed-optimizer'); ?>">
     1511    <div style="display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px;">
     1512        <strong style="font-size:14px;color:#0f172a;"><?php echo esc_html__('1-Click Speed Presets', 'vn-speed-optimizer'); ?></strong>
     1513        <span style="font-size:12px;color:#64748b;"><?php echo esc_html__('Creates an automatic Safe-Rollback checkpoint before switching.', 'vn-speed-optimizer'); ?></span>
     1514    </div>
     1515    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px;">
     1516        <?php foreach ($speed_presets as $preset_id => $preset) :
     1517            $is_active_preset = $active_preset === $preset_id;
     1518            $border_color     = $is_active_preset ? '#2563eb' : '#e2e8f0';
     1519            $bg_color         = $is_active_preset ? '#eff6ff' : '#f8fafc';
     1520        ?>
     1521            <div style="padding:12px;border-radius:10px;border:1px solid <?php echo esc_attr($border_color); ?>;background:<?php echo esc_attr($bg_color); ?>;display:flex;flex-direction:column;justify-content:space-between;gap:8px;">
     1522                <div>
     1523                    <div style="display:flex;align-items:center;justify-content:space-between;gap:6px;margin-bottom:4px;">
     1524                        <strong style="font-size:13px;color:#0f172a;"><?php echo esc_html($preset['label']); ?></strong>
     1525                        <?php if (!empty($preset['badge'])) : ?>
     1526                            <span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:999px;background:#dbeafe;color:#1d4ed8;"><?php echo esc_html($preset['badge']); ?></span>
     1527                        <?php endif; ?>
     1528                    </div>
     1529                    <p style="margin:0;font-size:12px;line-height:1.4;color:#475569;"><?php echo esc_html($preset['desc']); ?></p>
     1530                </div>
     1531                <button type="button" class="button <?php echo $is_active_preset ? 'button-primary' : 'button-secondary'; ?> vnspo-preset-apply" data-preset="<?php echo esc_attr($preset_id); ?>">
     1532                    <?php echo $is_active_preset ? esc_html__('Active Preset', 'vn-speed-optimizer') : esc_html(sprintf(__('Apply %s', 'vn-speed-optimizer'), $preset['label'])); ?>
     1533                </button>
     1534            </div>
     1535        <?php endforeach; ?>
     1536    </div>
     1537</section>
     1538<?php
     1539$speed_proof = SafePreviewRollback::getBeforeAfterSpeedProof();
     1540$priority_summary = class_exists(\VNSPO\Services\Optimization\PriorityElementsService::class)
     1541    ? \VNSPO\Services\Optimization\PriorityElementsService::vnspo_get_summary()
     1542    : array('count' => 0, 'items' => array());
     1543?>
     1544<section id="vnspo-speed-proof-card" style="margin:0 0 16px;padding:14px 16px;border:1px solid #cbd5e1;border-radius:12px;background:#ffffff;" aria-label="<?php echo esc_attr__('Before and After RUM Speed Proof', 'vn-speed-optimizer'); ?>">
     1545    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:14px;">
     1546        <div style="padding:12px;border-radius:10px;border:1px solid #e2e8f0;background:#f8fafc;">
     1547            <strong style="display:block;font-size:13px;color:#0f172a;margin-bottom:6px;"><?php echo esc_html__('Before / After RUM Speed Proof', 'vn-speed-optimizer'); ?></strong>
     1548            <?php if (!empty($speed_proof['has_data'])) : ?>
     1549                <div style="display:flex;gap:14px;flex-wrap:wrap;align-items:baseline;font-size:13px;color:#334155;">
     1550                    <span><?php echo esc_html__('Baseline LCP:', 'vn-speed-optimizer'); ?> <strong><?php echo esc_html((string) $speed_proof['baseline_lcp_ms']); ?> ms</strong></span>
     1551                    <span><?php echo esc_html__('Current LCP:', 'vn-speed-optimizer'); ?> <strong><?php echo esc_html((string) $speed_proof['current_lcp_ms']); ?> ms</strong></span>
     1552                    <span style="font-weight:700;color:<?php echo ((float) $speed_proof['lcp_improvement_pct']) >= 0 ? '#15803d' : '#b91c1c'; ?>;">
     1553                        <?php echo esc_html(sprintf('%s%.1f%%', ((float) $speed_proof['lcp_improvement_pct']) >= 0 ? '+' : '', (float) $speed_proof['lcp_improvement_pct'])); ?>
     1554                    </span>
     1555                </div>
     1556                <p style="margin:6px 0 0;font-size:12px;color:#64748b;">
     1557                    <?php echo esc_html(sprintf(__('Calculated from %d real browser RUM samples (no synthetic estimates).', 'vn-speed-optimizer'), (int) $speed_proof['sample_count'])); ?>
     1558                </p>
     1559            <?php else : ?>
     1560                <p style="margin:0;font-size:12px;color:#64748b;">
     1561                    <?php echo esc_html__('No real before/after RUM samples yet — enable Local RUM and browse your site to capture live baseline vs optimized LCP.', 'vn-speed-optimizer'); ?>
     1562                </p>
     1563            <?php endif; ?>
     1564        </div>
     1565        <div style="padding:12px;border-radius:10px;border:1px solid #e2e8f0;background:#f8fafc;display:flex;flex-direction:column;justify-content:space-between;gap:8px;">
     1566            <div>
     1567                <strong style="display:block;font-size:13px;color:#0f172a;margin-bottom:6px;"><?php echo esc_html__('RUM Auto-Priority Elements', 'vn-speed-optimizer'); ?></strong>
     1568                <?php if (!empty($priority_summary['count'])) :
     1569                    $learned_names = array();
     1570                    foreach ($priority_summary['items'] as $tpl_key => $tpl_info) {
     1571                        $path_only = !empty($tpl_info['lcp_url']) ? wp_parse_url((string) $tpl_info['lcp_url'], PHP_URL_PATH) : '';
     1572                        $learned_names[] = $tpl_key . ': ' . ($path_only ? basename((string) $path_only) : 'image');
     1573                    }
     1574                ?>
     1575                    <p style="margin:0;font-size:12px;color:#334155;">
     1576                        <?php echo esc_html(sprintf(__('%d learned templates: %s', 'vn-speed-optimizer'), (int) $priority_summary['count'], implode(' | ', array_slice($learned_names, 0, 4)))); ?>
     1577                    </p>
     1578                <?php else : ?>
     1579                    <p style="margin:0;font-size:12px;color:#64748b;">
     1580                        <?php echo esc_html__('0 templates learned yet — visits will automatically detect hero LCP images.', 'vn-speed-optimizer'); ?>
     1581                    </p>
     1582                <?php endif; ?>
     1583            </div>
     1584            <?php if (!empty($priority_summary['count'])) : ?>
     1585                <div>
     1586                    <button type="button" class="button button-secondary" id="vnspo-btn-reset-priority"><?php echo esc_html__('Reset Learned Elements', 'vn-speed-optimizer'); ?></button>
     1587                </div>
     1588            <?php endif; ?>
     1589        </div>
     1590        <?php
     1591        $live_ttfb_hist = \get_option('vnspo_ttfb_history', array());
     1592        $live_ttfb_last = (\is_array($live_ttfb_hist) && !empty($live_ttfb_hist[0]) && \is_array($live_ttfb_hist[0])) ? $live_ttfb_hist[0] : null;
     1593        ?>
     1594        <div id="vnspo-live-ttfb-proof-box" style="padding:12px;border-radius:10px;border:1px solid #e2e8f0;background:#f8fafc;display:flex;flex-direction:column;justify-content:space-between;gap:8px;">
     1595            <div>
     1596                <strong style="display:block;font-size:13px;color:#0f172a;margin-bottom:6px;"><?php echo esc_html__('Live TTFB Before / After Proof', 'vn-speed-optimizer'); ?></strong>
     1597                <div id="vnspo-live-proof-body" style="font-size:12px;color:#334155;">
     1598                    <?php if ($live_ttfb_last && isset($live_ttfb_last['origin_ms'], $live_ttfb_last['cached_ms'])) :
     1599                        $orig_v = (int) $live_ttfb_last['origin_ms'];
     1600                        $cach_v = (int) $live_ttfb_last['cached_ms'];
     1601                        $pct_v  = (int) ($live_ttfb_last['improvement_pct'] ?? 0);
     1602                        $spd_v  = $cach_v > 0 ? round($orig_v / $cach_v, 1) : 0.0;
     1603                        $hdr_v  = (string) ($live_ttfb_last['cache_header'] ?? '');
     1604                    ?>
     1605                        <span><?php echo esc_html(sprintf('%d ms -> %d ms (-%d%%, %.1fx)', $orig_v, $cach_v, $pct_v, $spd_v)); ?></span>
     1606                        <?php if ('' !== $hdr_v) : ?>
     1607                            <span style="display:inline-block;margin-left:6px;padding:1px 6px;border-radius:999px;background:#dcfce7;color:#166534;font-weight:600;"><?php echo esc_html($hdr_v); ?></span>
     1608                        <?php endif; ?>
     1609                    <?php else : ?>
     1610                        <span style="color:#64748b;"><?php echo esc_html__('No live origin vs cached measurement recorded yet — run a real 1-click measurement below.', 'vn-speed-optimizer'); ?></span>
     1611                    <?php endif; ?>
     1612                </div>
     1613            </div>
     1614            <div>
     1615                <button type="button" class="button button-secondary" id="vnspo-btn-run-speed-proof"><?php echo esc_html__('Measure Live Before / After TTFB', 'vn-speed-optimizer'); ?></button>
     1616            </div>
     1617        </div>
     1618    </div>
     1619</section>
    13911620<?php endif; ?>
    13921621    <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping.
    … …  
    13961625<!-- FOOTER -->
    13971626<div class="vnspo-footer">
    1398     <span><?php echo esc_html__('VN Speed Optimizer — Edge-powered performance', 'vn-speed-optimizer'); ?></span>
     1627    <span><?php echo esc_html($brand_name . ' — ' . __('Local-first performance engine', 'vn-speed-optimizer')); ?></span>
    13991628    <div class="vnspo-footer-links">
    1400         <a href="https://wordpress.org/support/plugin/vn-speed-optimizer/" target="_blank"><?php echo esc_html__('Support', 'vn-speed-optimizer'); ?></a>
    1401         <span>&middot;</span>
    1402         <a href="https://wordpress.org/plugins/vn-speed-optimizer/#reviews" target="_blank"><?php echo esc_html__('Rate', 'vn-speed-optimizer'); ?></a>
     1629        <?php if (! $hide_vendor_links) : ?>
     1630            <a href="<?php echo esc_url($support_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Support', 'vn-speed-optimizer'); ?></a>
     1631            <span>&middot;</span>
     1632            <a href="<?php echo esc_url('https://wordpress.org/plugins/vn-speed-optimizer/#reviews'); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Rate', 'vn-speed-optimizer'); ?></a>
     1633        <?php elseif ('' !== $support_url && false === strpos($support_url, 'wordpress.org/support/plugin/vn-speed-optimizer')) : ?>
     1634            <a href="<?php echo esc_url($support_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Support', 'vn-speed-optimizer'); ?></a>
     1635        <?php endif; ?>
    14031636    </div>
    14041637</div>
    … …  
    14461679        }).always(function() {
    14471680            $btn.prop('disabled', false).find('svg').removeClass('spin');
     1681        });
     1682    });
     1683
     1684    // Safe Rollback Latest Checkpoint
     1685    $('#vnspo-btn-rollback-latest').on('click', function() {
     1686        var $btn = $(this);
     1687        $btn.prop('disabled', true);
     1688        $.post(vnspo_vars.ajax_url, {
     1689            action: 'vnspo_rollback_latest',
     1690            nonce: vnspo_vars.nonce
     1691        }, function(res) {
     1692            if (res.success) {
     1693                showNotice('<?php echo esc_js(__('Configuration rolled back to last safe checkpoint.', 'vn-speed-optimizer')); ?>', 'success');
     1694                window.location.reload();
     1695            } else {
     1696                showNotice((res.data && res.data.message) ? res.data.message : 'No checkpoint available', 'error');
     1697            }
     1698        }).always(function() {
     1699            $btn.prop('disabled', false);
     1700        });
     1701    });
     1702
     1703    // One-click Live TTFB Proof button in #vnspo-speed-proof-card
     1704    $(document).on('click', '#vnspo-btn-run-speed-proof', function() {
     1705        var $btn = $(this);
     1706        var origText = $btn.text();
     1707        $btn.prop('disabled', true).text('<?php echo esc_js(__('Measuring...', 'vn-speed-optimizer')); ?>');
     1708        $.post(vnspo_vars.ajax_url, {
     1709            action: 'vnspo_measure_ttfb',
     1710            nonce: vnspo_vars.nonce
     1711        }, function(res) {
     1712            if (res && res.success && res.data) {
     1713                var d = res.data;
     1714                var $body = $('#vnspo-live-proof-body');
     1715                $body.empty();
     1716                var summary = Number(d.origin_ms || 0) + ' ms -> ' + Number(d.cached_ms || 0) + ' ms (-' + Number(d.improvement_pct || 0) + '%, ' + Number(d.speedup_factor || 0) + 'x)';
     1717                $body.append($('<span>').text(summary));
     1718                if (d.cache_header) {
     1719                    $body.append($('<span>').css({display:'inline-block',marginLeft:'6px',padding:'1px 6px',borderRadius:'999px',background:'#dcfce7',color:'#166534',fontWeight:'600'}).text(String(d.cache_header)));
     1720                }
     1721                $('#vnspo-ttfb-origin').text(d.origin_ms + ' ms');
     1722                $('#vnspo-ttfb-cached').text(d.cached_ms + ' ms');
     1723                $('#vnspo-ttfb-gain').text(d.improvement_pct + '%');
     1724                $('#vnspo-ttfb-empty').hide();
     1725                $('#vnspo-ttfb-results').css('display', 'grid');
     1726            } else {
     1727                showNotice((res && res.data && res.data.message) ? res.data.message : vnspo_vars.strings.error, 'error');
     1728            }
     1729        }).fail(function() {
     1730            showNotice(vnspo_vars.strings.error, 'error');
     1731        }).always(function() {
     1732            $btn.prop('disabled', false).text(origText);
    14481733        });
    14491734    });
    … …  
    16231908            });
    16241909            html += '</tbody></table></div>';
     1910            <?php if (! $hide_vendor_links) : ?>
    16251911            html += '<div style="margin-top:10px;padding:10px 12px;border:1px solid var(--v-border);border-radius:8px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;background:rgba(59,130,246,0.06);">' +
    16261912                '<span style="color:var(--v-text);"><strong>Pro Tip:</strong> Auto-compress all ' + Number(data.total_count || items.length) + ' images in 1 click, auto-optimize on upload &amp; generate AVIF + Mobile responsive sizes.</span>' +
    1627                 '<a href="<?php echo esc_url('https://vn-nexus.com/vnspo-pro'); ?>" target="_blank" rel="noopener noreferrer" class="button button-primary button-small"><?php echo esc_js(__('Upgrade to Pro', 'vn-speed-optimizer')); ?></a>' +
     1913                '<a href="<?php echo esc_url('https://vn-nexus.com/vnspo-pro?src=wp-free-images'); ?>" target="_blank" rel="noopener noreferrer" class="button button-primary button-small"><?php echo esc_js(__('Upgrade to Pro', 'vn-speed-optimizer')); ?></a>' +
    16281914                '</div>';
     1915            <?php endif; ?>
    16291916            $out.html(html);
    16301917        }).fail(function() {
    … …  
    18522139    function showNotice(msg, type) {
    18532140        var cls = type === 'success' ? 'vnspo-notice-success' : 'vnspo-notice-error';
    1854         var $n = $('<div class="vnspo-notice ' + cls + '">' + msg + '</div>');
     2141        var $n = $('<div class="vnspo-notice"></div>').addClass(cls).text(String(msg || ''));
    18552142        $('.vnspo-wrap').prepend($n);
    18562143        setTimeout(function() { $n.fadeOut(300, function() { $(this).remove(); }); }, 3000);
    … …  
    18612148        $(this).next('.vnspo-card-body').slideToggle(200);
    18622149        $(this).find('.vnspo-chevron').toggleClass('rotated');
     2150    });
     2151
     2152    // 1-Click Speed Presets
     2153    $(document).on('click', '.vnspo-preset-apply', function() {
     2154        var $btn = $(this);
     2155        var preset = $btn.data('preset');
     2156        if (!preset) return;
     2157        $btn.prop('disabled', true);
     2158        $.post(vnspo_vars.ajax_url, {
     2159            action: 'vnspo_apply_preset',
     2160            nonce: vnspo_vars.nonce,
     2161            preset: preset
     2162        }, function(res) {
     2163            if (res && res.success) {
     2164                window.location.reload();
     2165            } else {
     2166                $btn.prop('disabled', false);
     2167                showNotice((res && res.data && res.data.message) ? res.data.message : vnspo_vars.strings.error, 'error');
     2168            }
     2169        }).fail(function() {
     2170            $btn.prop('disabled', false);
     2171            showNotice(vnspo_vars.strings.error, 'error');
     2172        });
     2173    });
     2174
     2175    // Simple / Advanced UI Mode Toggle
     2176    $(document).on('click', '#vnspo-btn-ui-mode', function() {
     2177        var $btn = $(this);
     2178        var current = $btn.data('mode') || 'simple';
     2179        var next = current === 'advanced' ? 'simple' : 'advanced';
     2180        $btn.prop('disabled', true);
     2181        $.post(vnspo_vars.ajax_url, {
     2182            action: 'vnspo_toggle_ui_mode',
     2183            nonce: vnspo_vars.nonce,
     2184            mode: next
     2185        }, function(res) {
     2186            if (res && res.success) {
     2187                window.location.reload();
     2188            } else {
     2189                $btn.prop('disabled', false);
     2190                showNotice(vnspo_vars.strings.error, 'error');
     2191            }
     2192        }).fail(function() {
     2193            $btn.prop('disabled', false);
     2194            showNotice(vnspo_vars.strings.error, 'error');
     2195        });
     2196    });
     2197
     2198    // Clear Auto-Heal JS Exclusions
     2199    $(document).on('click', '#vnspo-btn-clear-ah-exclusions', function() {
     2200        var $btn = $(this);
     2201        $btn.prop('disabled', true);
     2202        $.post(vnspo_vars.ajax_url, {
     2203            action: 'vnspo_clear_auto_heal_exclusions',
     2204            nonce: vnspo_vars.nonce
     2205        }, function(res) {
     2206            if (res && res.success) {
     2207                window.location.reload();
     2208            } else {
     2209                $btn.prop('disabled', false);
     2210                showNotice(vnspo_vars.strings.error, 'error');
     2211            }
     2212        }).fail(function() {
     2213            $btn.prop('disabled', false);
     2214            showNotice(vnspo_vars.strings.error, 'error');
     2215        });
     2216    });
     2217
     2218    // Reset RUM Auto-Priority Elements
     2219    $(document).on('click', '#vnspo-btn-reset-priority', function() {
     2220        var $btn = $(this);
     2221        $btn.prop('disabled', true);
     2222        $.post(vnspo_vars.ajax_url, {
     2223            action: 'vnspo_reset_priority_elements',
     2224            nonce: vnspo_vars.nonce
     2225        }, function(res) {
     2226            if (res && res.success) {
     2227                window.location.reload();
     2228            } else {
     2229                $btn.prop('disabled', false);
     2230                showNotice(vnspo_vars.strings.error, 'error');
     2231            }
     2232        }).fail(function() {
     2233            $btn.prop('disabled', false);
     2234            showNotice(vnspo_vars.strings.error, 'error');
     2235        });
    18632236    });
    18642237})(jQuery);
    … …  
    19312304    private function renderProComparisonAndPlans($is_vi)
    19322305    {
     2306        if ((bool) \apply_filters('vnspo_hide_vendor_links', false)) {
     2307            return '';
     2308        }
     2309
    19332310        $is_pro_active = (bool) \apply_filters('vnspo_is_pro_active', false);
    19342311        if ($is_pro_active) {
    … …  
    19382315                : 'Your Pro license is active on this website. Extended modules (Bulk AVIF, RUCSS, Smart Delay JS, SEO & Ads Booster) are enabled.';
    19392316        } else {
    1940             $title = $is_vi ? 'Gói Pro chưa được kích hoạt' : 'Pro add-on is not activated';
     2317            $title = $is_vi ? 'Giá trị thực tế & So sánh Free vs Pro / Agency' : 'Measured Site Value & Free vs Pro / Agency';
    19412318            $message = $is_vi
    1942                 ? 'Website này đang chạy bản Free. Cài đặt add-on Pro và kích hoạt license để mở khóa Bulk AVIF, RUCSS, Smart Delay JS và SEO & Ads Booster.'
    1943                 : 'This website is running the Free edition. Install the Pro add-on and activate a license to unlock Bulk AVIF, RUCSS, Smart Delay JS, and SEO & Ads Booster.';
    1944         }
    1945         $product_url = 'https://vn-nexus.com/vnspo-pro';
     2319                ? 'Bản Free chạy hoàn toàn trên hosting của bạn. Chỉ nâng cấp lên Pro / Agency khi bạn cần giảm tải CPU host qua Cloudflare Edge, nén AVIF hàng loạt hoặc quản trị 5+ website White-Label.'
     2320                : 'Free runs locally on your hosting. Upgrade to Pro / Agency only when you need Cloudflare Edge offloading, bulk AVIF compression, or 5+ site White-Label management.';
     2321        }
     2322
     2323        $img_counts_raw = \function_exists('wp_count_attachments') ? \wp_count_attachments('image') : array();
     2324        $total_images   = 0;
     2325        if (\is_object($img_counts_raw) || \is_array($img_counts_raw)) {
     2326            foreach ((array) $img_counts_raw as $cnt) {
     2327                $total_images += (int) $cnt;
     2328            }
     2329        }
     2330
     2331        $has_local_avif = \function_exists('imageavif');
     2332        if (! $has_local_avif && \class_exists('Imagick') && \method_exists('Imagick', 'queryFormats')) {
     2333            try {
     2334                $formats = \Imagick::queryFormats('AVIF');
     2335                $has_local_avif = \is_array($formats) && \in_array('AVIF', $formats, true);
     2336            } catch (\Throwable $e) {
     2337                $has_local_avif = false;
     2338            }
     2339        }
     2340
     2341        $active_plugins_count = \count((array) \get_option('active_plugins', array()));
     2342        $detected_stacks      = array();
     2343        if (\class_exists('WooCommerce')) {
     2344            $detected_stacks[] = 'WooCommerce';
     2345        }
     2346        if (\defined('ELEMENTOR_VERSION')) {
     2347            $detected_stacks[] = 'Elementor';
     2348        }
     2349        if (false !== \stripos((string) \get_stylesheet(), 'flatsome')) {
     2350            $detected_stacks[] = 'Flatsome';
     2351        }
     2352        $stack_label = ! empty($detected_stacks)
     2353            ? \implode(', ', $detected_stacks)
     2354            : ($is_vi ? 'WordPress chuẩn' : 'Standard WordPress');
     2355
     2356        $ah_excl_count = \class_exists(\VNSPO\Services\Optimization\Assets\DelayJsConfig::class)
     2357            ? \count(\VNSPO\Services\Optimization\Assets\DelayJsConfig::get_auto_heal_exclusions())
     2358            : 0;
     2359        $speed_proof   = SafePreviewRollback::getBeforeAfterSpeedProof();
     2360        $rum_samples   = isset($speed_proof['sample_count']) ? (int) $speed_proof['sample_count'] : 0;
     2361
     2362        $local_cache   = $this->getLocalCacheStats();
     2363        $ttfb_history  = \get_option('vnspo_ttfb_history', array());
     2364        $latest_ttfb   = (\is_array($ttfb_history) && ! empty($ttfb_history[0]) && \is_array($ttfb_history[0])) ? $ttfb_history[0] : null;
     2365        $ttfb_summary  = $latest_ttfb
     2366            ? sprintf('%d ms -> %d ms (-%d%%)', (int) ($latest_ttfb['origin_ms'] ?? 0), (int) ($latest_ttfb['cached_ms'] ?? 0), (int) ($latest_ttfb['improvement_pct'] ?? 0))
     2367            : ($is_vi ? 'Chưa đo TTFB thực tế' : 'Not measured yet');
     2368
     2369        $product_url = 'https://vn-nexus.com/vnspo-pro?src=wp-free-dashboard';
     2370        $agency_url  = 'https://vn-nexus.com/vnspo-pro?src=wp-free-dashboard&plan=agency';
     2371        $radar_url   = 'https://vn-nexus.com/radar';
    19462372
    19472373        ob_start();
    … …  
    19502376            <h2 id="vnspo-plans-title"><?php echo esc_html($title); ?></h2>
    19512377            <p><?php echo esc_html($message); ?></p>
    1952             <p><a class="button button-secondary" href="<?php echo esc_url($product_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($is_vi ? 'Xem thông tin gói Pro' : 'Explore VNSPO Pro'); ?></a></p>
     2378            <div id="vnspo-pro-diagnostics" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;margin:12px 0;">
     2379                <div style="padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
     2380                    <div style="font-size:11px;color:#64748b;"><?php echo esc_html($is_vi ? 'Hiệu quả Cache & TTFB thực tế' : 'Real Cache & TTFB Measured'); ?></div>
     2381                    <strong style="font-size:14px;color:#0f172a;"><?php echo esc_html(sprintf($is_vi ? '%s | %d trang (%s)' : '%s | %d pages (%s)', $ttfb_summary, (int) $local_cache['count'], $this->formatBytesShort($local_cache['bytes']))); ?></strong>
     2382                </div>
     2383                <div style="padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
     2384                    <div style="font-size:11px;color:#64748b;"><?php echo esc_html($is_vi ? 'Thư viện ảnh thật trên site' : 'Site Media Library'); ?></div>
     2385                    <strong style="font-size:14px;color:#0f172a;"><?php echo esc_html(sprintf($is_vi ? '%d ảnh (AVIF cục bộ: %s)' : '%d images (Local AVIF: %s)', $total_images, $has_local_avif ? ($is_vi ? 'Hỗ trợ' : 'Supported') : ($is_vi ? 'Chưa hỗ trợ' : 'Unavailable'))); ?></strong>
     2386                </div>
     2387                <div style="padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
     2388                    <div style="font-size:11px;color:#64748b;"><?php echo esc_html($is_vi ? 'Plugin & Theme phát hiện' : 'Active Plugins & Stack'); ?></div>
     2389                    <strong style="font-size:14px;color:#0f172a;"><?php echo esc_html(sprintf($is_vi ? '%d plugin (%s)' : '%d plugins (%s)', $active_plugins_count, $stack_label)); ?></strong>
     2390                </div>
     2391                <div style="padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
     2392                    <div style="font-size:11px;color:#64748b;"><?php echo esc_html($is_vi ? 'Dữ liệu tự học cục bộ' : 'Local Learning Signals'); ?></div>
     2393                    <strong style="font-size:14px;color:#0f172a;"><?php echo esc_html(sprintf($is_vi ? '%d JS Auto-Heal | %d mẫu RUM' : '%d Auto-Heal JS | %d RUM samples', $ah_excl_count, $rum_samples)); ?></strong>
     2394                </div>
     2395            </div>
     2396            <table class="widefat striped" style="margin:10px 0 14px;">
     2397                <thead>
     2398                    <tr>
     2399                        <th><?php echo esc_html($is_vi ? 'Công nghệ lõi' : 'Core Engine'); ?></th>
     2400                        <th><?php echo esc_html__('Free (Local Host)', 'vn-speed-optimizer'); ?></th>
     2401                        <th><?php echo esc_html__('Pro / Agency (Cloudflare Edge)', 'vn-speed-optimizer'); ?></th>
     2402                    </tr>
     2403                </thead>
     2404                <tbody>
     2405                    <tr>
     2406                        <td><strong><?php echo esc_html($is_vi ? 'Cắt CSS thừa (Edge RUCSS)' : 'Remove Unused CSS (Edge RUCSS)'); ?></strong></td>
     2407                        <td><?php echo esc_html($is_vi ? 'Chỉ Async CSS' : 'Async CSS only'); ?></td>
     2408                        <td><?php echo esc_html($is_vi ? 'Phân tích trên Cloudflare (0% CPU host)' : 'Computed on Cloudflare (0% origin CPU)'); ?></td>
     2409                    </tr>
     2410                    <tr>
     2411                        <td><strong><?php echo esc_html($is_vi ? 'Nén ảnh hàng loạt AVIF/WebP' : 'Bulk AVIF / WebP Optimizer'); ?></strong></td>
     2412                        <td><?php echo esc_html($has_local_avif ? ($is_vi ? 'Dùng GD/Imagick host' : 'Origin GD/Imagick only') : ($is_vi ? 'Host chưa có AVIF' : 'No local AVIF support')); ?></td>
     2413                        <td><?php echo esc_html($is_vi ? 'Xử lý trên Edge + tạo định dạng AVIF/WebP tự động' : 'Offloaded Edge AVIF/WebP pipeline'); ?></td>
     2414                    </tr>
     2415                    <tr>
     2416                        <td><strong><?php echo esc_html($is_vi ? 'Miễn dịch xung đột Delay JS' : 'JS Conflict Immunity'); ?></strong></td>
     2417                        <td><?php echo esc_html($is_vi ? 'Tự học sau lỗi tại site này' : 'Single-site local Auto-Heal'); ?></td>
     2418                        <td><?php echo esc_html($is_vi ? 'Đồng bộ rule miễn dịch toàn mạng lưới Pro' : 'Global multi-site Edge conflict rules'); ?></td>
     2419                    </tr>
     2420                    <tr>
     2421                        <td><strong><?php echo esc_html($is_vi ? 'Ads Speed, AEO Schema & Agency White-Label' : 'Ads Speed, AEO & Agency White-Label'); ?></strong></td>
     2422                        <td><?php echo esc_html($is_vi ? 'Cache đĩa cục bộ + RUM cơ bản' : 'Local disk cache + basic RUM'); ?></td>
     2423                        <td><?php echo esc_html($is_vi ? 'Edge Purge, Ads Probe, Auto AEO & Agency (5+ site, White-Label)' : 'Edge Purge, Ads Probe, Auto AEO & Agency (5+ sites, White-Label)'); ?></td>
     2424                    </tr>
     2425                </tbody>
     2426            </table>
     2427            <p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
     2428                <a class="button button-primary" href="<?php echo esc_url($product_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($is_vi ? 'Nâng cấp VN Speed Optimizer Pro' : 'Upgrade to VNSPO Pro'); ?></a>
     2429                <a class="button button-secondary" href="<?php echo esc_url($agency_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($is_vi ? 'Gói Agency (5+ sites & White-Label)' : 'Agency Plan (5+ sites & White-Label)'); ?></a>
     2430                <a class="button button-secondary" href="<?php echo esc_url($radar_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($is_vi ? 'Mở Vietnam Speed Radar' : 'Open Speed Radar'); ?></a>
     2431            </p>
    19532432        </section>
    19542433        <?php
    … …  
    19712450        return '<div class="vnspo-row">' .
    19722451            '<div class="vnspo-row-info">' .
    1973                 '<label for="' . $id . '" class="vnspo-row-label">' . esc_html($this->tr($label)) . '</label>' .
     2452                '<label for="' . esc_attr($id) . '" class="vnspo-row-label">' . esc_html($this->tr($label)) . '</label>' .
    19742453                '<span class="vnspo-row-desc">' . esc_html($this->tr($desc)) . '</span>' .
    19752454            '</div>' .
    19762455            '<label class="vnspo-switch">' .
    1977                 '<input type="checkbox" id="' . $id . '" class="vnspo-toggle-cb" data-option="' . esc_attr($option) . '" value="1" ' . $checked . '>' .
     2456                '<input type="checkbox" id="' . esc_attr($id) . '" class="vnspo-toggle-cb" data-option="' . esc_attr($option) . '" value="1" ' . $checked . '>' .
    19782457                '<span class="vnspo-slider"></span>' .
    19792458            '</label>' .
    … …  
    19872466        return '<div class="vnspo-row">' .
    19882467            '<div class="vnspo-row-info">' .
    1989                 '<label for="' . $id . '" class="vnspo-row-label">' . esc_html($this->tr($label)) . '</label>' .
     2468                '<label for="' . esc_attr($id) . '" class="vnspo-row-label">' . esc_html($this->tr($label)) . '</label>' .
    19902469                '<span class="vnspo-row-desc">' . esc_html($this->tr($desc)) . '</span>' .
    19912470            '</div>' .
    1992             '<input type="number" id="' . $id . '" name="vnspo_options[' . esc_attr($option) . ']" ' .
    1993                 'value="' . esc_attr($value) . '" min="' . $min . '" max="' . $max . '" step="' . $step . '" ' .
     2471            '<input type="number" id="' . esc_attr($id) . '" name="vnspo_options[' . esc_attr($option) . ']" ' .
     2472                'value="' . esc_attr($value) . '" min="' . intval($min) . '" max="' . intval($max) . '" step="' . intval($step) . '" ' .
    19942473                'class="vnspo-number-input" style="width:80px;padding:4px 8px;border:1px solid var(--v-border);border-radius:6px;">' .
    19952474        '</div>';
    … …  
    20032482        return '<div class="vnspo-row">' .
    20042483            '<div class="vnspo-row-info">' .
    2005                 '<label for="' . $id . '" class="vnspo-row-label">' . esc_html($this->tr($label)) . '</label>' .
     2484                '<label for="' . esc_attr($id) . '" class="vnspo-row-label">' . esc_html($this->tr($label)) . '</label>' .
    20062485                '<span class="vnspo-row-desc">' . esc_html($this->tr($desc)) . '</span>' .
    20072486            '</div>' .
    2008             '<input type="url" id="' . $id . '" name="vnspo_options[' . esc_attr($option) . ']" data-option="' . esc_attr($option) . '" ' .
     2487            '<input type="url" id="' . esc_attr($id) . '" name="vnspo_options[' . esc_attr($option) . ']" data-option="' . esc_attr($option) . '" ' .
    20092488                'value="' . esc_attr($value) . '" placeholder="' . esc_attr($placeholder) . '" ' .
    20102489                'class="vnspo-input" style="min-width:260px;max-width:360px;padding:6px 10px;border:1px solid var(--v-border);border-radius:6px;">' .
    … …  
    20292508    }
    20302509
    2031     private function tabDashboard($options)
    2032     {
    2033         // Use new Dashboard V2
    2034         return $this->renderDashboardV2($options);
    2035     }
    2036 
    2037     private function tabCleanup($options)
    2038     {
    2039         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>';
    2040 
    2041         $content  = '<div class="vnspo-section-title">Head Cleanup</div>';
    2042         $content .= $this->toggleHtml('disable_emojis', 'Disable Emojis', 'Remove wp-emoji.js from frontend to save bandwidth', $options);
    2043         $content .= $this->toggleHtml('disable_embeds', 'Disable Embeds', 'Prevent others from embedding your site (oEmbed)', $options);
    2044         $content .= $this->toggleHtml('smart_cleanup_head', 'Smart Head Cleanup', 'Remove Shortlink, RSD, WLW manifest, and Windows Live Writer tags', $options);
    2045         $content .= $this->toggleHtml('disable_dashicons', 'Disable Dashicons', 'Remove dashicons.min.css from frontend', $options);
    2046 
    2047         $content .= '<div class="vnspo-section-title">Advanced Bloat</div>';
    2048         $content .= $this->toggleHtml('disable_xmlrpc', 'Disable XML-RPC', 'Block XML-RPC pingbacks and trackbacks for security', $options);
    2049         $content .= $this->toggleHtml('disable_jquery_migrate', 'Disable jQuery Migrate', 'Remove legacy jQuery migration script', $options);
    2050         $content .= $this->toggleHtml('disable_block_css', 'Disable Block CSS', 'Remove Gutenberg block library CSS if using Page Builder', $options);
    2051         $content .= $this->toggleHtml('disable_rss_feeds', 'Disable RSS Feeds', 'Disable site feeds to save CPU cycles', $options);
    2052         if (class_exists('WooCommerce')) {
    2053             $content .= $this->toggleHtml('woo_optimize', 'Smart WooCommerce', 'Unload WooCommerce scripts and styles on non-shop pages', $options);
    2054         }
    2055 
    2056         $content .= '<div class="vnspo-section-title">Database Cleanup</div>';
    2057         $content .= $this->toggleHtml('db_auto_revisions', 'Auto-Revisions', 'Automatically clean post revisions on schedule', $options);
    2058         $content .= $this->toggleHtml('db_auto_drafts', 'Auto-Drafts', 'Remove auto-drafts periodically', $options);
    2059         $content .= $this->toggleHtml('db_auto_trash', 'Auto-Trash', 'Auto-purge items in trash', $options);
    2060         $content .= $this->toggleHtml('db_auto_spam', 'Auto-Spam', 'Automatically delete comments already marked as spam', $options);
    2061         $content .= $this->toggleHtml('db_auto_transients', 'Auto-Transients', 'Clean expired transients automatically', $options);
    2062         $content .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">' . esc_html__('Immediate Database & Log Cleanup', 'vn-speed-optimizer') . '</label><span class="vnspo-row-desc">' . esc_html__('Delete revisions, auto-drafts, expired transients, completed ActionScheduler logs, optimize tables, and truncate oversized error_log files (>5MB).', 'vn-speed-optimizer') . '</span></div><button type="button" class="button button-secondary" onclick="vnspo_db_bulk(\'clean_all\')">' . esc_html__('Clean Database, ActionScheduler & Error Logs Now', 'vn-speed-optimizer') . '</button></div>';
    2063 
    2064         $content .= '<div class="vnspo-section-title">Heartbeat Control</div>';
    2065         $hb = $options['heartbeat_control'] ?? '';
    2066         $content .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">Heartbeat Frequency</label><span class="vnspo-row-desc">Control WordPress heartbeat (admin-ajax.php usage)</span></div>' .
    2067             '<select name="vnspo_options[heartbeat_control]" class="vnspo-select">' .
    2068             '<option value=""' . ($hb === '' ? ' selected' : '') . '>Default (WP)</option>' .
    2069             '<option value="limit"' . ($hb === 'limit' ? ' selected' : '') . '>Limit (60s)</option>' .
    2070             '<option value="aggressive"' . ($hb === 'aggressive' ? ' selected' : '') . '>Aggressive (120s)</option>' .
    2071             '<option value="disable_dashboard"' . ($hb === 'disable_dashboard' ? ' selected' : '') . '>Disable Dashboard</option>' .
    2072             '<option value="desktop_only"' . ($hb === 'desktop_only' ? ' selected' : '') . '>Desktop Only</option>' .
    2073             '</select></div>';
    2074 
    2075         return $this->card('Cleanup & Optimization', $icon, $content);
    2076     }
    2077 
    2078     private function tabPerformance($options)
    2079     {
    2080         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>';
    2081 
    2082         $t1  = '<div class="vnspo-section-title">Render Blocking Elimination</div>';
    2083         $t1 .= $this->toggleHtml('async_css', 'Async CSS Loading', 'Load stylesheets asynchronously to eliminate render-blocking (preload+onload pattern)', $options);
    2084         $t1 .= $this->urlInputHtml('lcp_preload_url', 'LCP Preload URL', 'Full image URL of the hero/LCP image to preload in head (leave empty when unused)', $options, 'https://example.com/wp-content/uploads/hero.webp');
    2085         $t1 .= $this->toggleHtml('interaction_delay_v2', 'Delay Non-Critical JS', 'Delay non-critical JS until user interaction with automatic fallback', $options);
    2086         $t1 .= $this->numberInputHtml('delay_js_timeout', 'Auto-Trigger Delay (seconds)', 'Automatically trigger delayed JS after this many seconds (default: 10)', $options, 5, 120);
    2087         $t1 .= $this->toggleHtml('speculation_rules', 'Speculation Rules API', 'Instant page navigation on hover using Chrome\'s native Speculation Rules API', $options);
    2088         $t1 .= $this->toggleHtml('instant_touch', 'Instant Touch', 'Prefetch next page when user hovers a link for zero-latency navigation', $options);
    2089 
    2090         $t1 .= '<div class="vnspo-section-title">DNS & Connection Hints</div>';
    2091         $t1 .= $this->toggleHtml('dns_prefetch', 'DNS Prefetch', 'Pre-resolve DNS for external domains to speed up connections', $options);
    2092         $t1 .= $this->toggleHtml('dns_prefetch_enhancer', 'DNS Prefetch Enhancer', 'Auto-detect external domains in HTML and add preconnect hints for 50+ services', $options);
    2093         $t1 .= $this->toggleHtml('preconnect', 'Preconnect Hints', 'Pre-establish TCP/TLS connections to third-party origins', $options);
    2094 
    2095         $t1 .= '<div class="vnspo-section-title">Browser Caching</div>';
    2096         $t1 .= $this->toggleHtml('browser_cache', 'Browser Cache', 'Set Cache-Control and Expires headers via .htaccess for static assets', $options);
    2097         $t1 .= $this->toggleHtml('browser_cache_aggressive', 'Aggressive Browser Cache', 'Extend cache duration for images, fonts, and media files', $options);
    2098         $t1 .= $this->toggleHtml('browser_cache_immutable', 'Immutable Cache Headers', 'Mark versioned assets as immutable to prevent unnecessary revalidation', $options);
    2099         $t1 .= $this->toggleHtml('browser_cache_stale_while_revalidate', 'Stale-While-Revalidate', 'Serve cached content immediately while fetching updates in background', $options);
    2100 
    2101         $t1 .= '<div class="vnspo-section-title">Core</div>';
    2102         $t1 .= $this->toggleHtml('lazy_render', 'Native Lazy Render', 'Use CSS content-visibility:auto to skip rendering off-screen elements', $options);
    2103         $t1 .= $this->toggleHtml('minify_html', 'Minify HTML', 'Remove whitespace and HTML comments from page output', $options);
    2104         $t1 .= $this->toggleHtml('fast_llms_txt', 'Fast /llms.txt (Agentic Ready)', 'Serve a lightweight cached /llms.txt compliant with llmstxt.org without SEO-plugin timeouts', $options);
    2105 
    2106         return $this->card('Performance', $icon, $t1);
    2107     }
    2108 
    2109     private function tabFonts($options)
    2110     {
    2111         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>';
    2112 
    2113         $content  = '<div class="vnspo-section-title">Font Optimization</div>';
    2114         $content .= $this->toggleHtml('font_display_swap', 'Font Display Swap', 'Add font-display:swap to prevent Flash of Invisible Text (FOIT)', $options);
    2115         $content .= $this->toggleHtml('smart_fonts', 'Smart Fonts (Local Google Fonts)', 'Download and self-host Google Fonts to eliminate external requests', $options);
    2116         $content .= $this->toggleHtml('smart_fonts_local', 'Font CLS Fix', 'Fix Cumulative Layout Shift from font loading', $options);
    2117 
    2118         $content .= '<div class="vnspo-section-title">Self-Host CDN</div>';
    2119         $content .= $this->toggleHtml('local_cdn_enabled', 'Enable Self-Host CDN', 'Self-host remote icon/JS libraries (Font Awesome, jsDelivr, cdnjs) locally to eliminate external requests', $options);
    2120         $content .= $this->toggleHtml('local_cdn_fontawesome', 'Local CDN: Font Awesome', 'Mirror Font Awesome locally', $options);
    2121         $content .= $this->toggleHtml('local_cdn_jsdelivr', 'Local CDN: jsDelivr', 'Mirror jsDelivr assets locally', $options);
    2122         $content .= $this->toggleHtml('local_cdn_cdnjs', 'Local CDN: cdnjs', 'Mirror cdnjs assets locally', $options);
    2123 
    2124         return $this->card('Fonts & CDN Assets', $icon, $content);
    2125     }
    2126 
    2127     private function tabMedia($options)
    2128     {
    2129         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>';
    2130 
    2131         $content  = '<div class="vnspo-section-title">Lazy Loading</div>';
    2132         $content .= $this->toggleHtml('lazy_load', 'Lazy Load Images', 'Load images only when scrolled into viewport using IntersectionObserver', $options);
    2133         $content .= $this->toggleHtml('lazy_load_v2', 'Enhanced Lazy Load v2', 'Use native lazy loading with IntersectionObserver fallback for older browsers', $options);
    2134         $content .= $this->toggleHtml('lazy_images', 'Lazy Images', 'Lazy load all images including background images and picture sources', $options);
    2135         $content .= $this->toggleHtml('lazy_iframes', 'Lazy Load Iframes', 'Lazy load all iframes (video embeds, widgets)', $options);
    2136         $content .= $this->toggleHtml('lazy_backgrounds', 'Lazy Load Backgrounds', 'Lazy load CSS background-image with IntersectionObserver', $options);
    2137         $content .= $this->toggleHtml('lazy_vpi', 'Viewport Images Priority (VPI)', 'Eager load first 3 above-the-fold images for faster LCP', $options);
    2138         $content .= $this->toggleHtml('lqip_placeholder', 'LQIP Placeholders', 'Generate Low Quality Image Placeholders to prevent CLS during lazy load', $options);
    2139 
    2140         $content .= '<div class="vnspo-section-title">Video Optimization</div>';
    2141         $content .= $this->toggleHtml('youtube_lazy', 'YouTube Lazy Load', 'Replace iframes with clickable preview thumbnail (privacy-enhanced)', $options);
    2142         $yt_quality = $options['youtube_thumb_quality'] ?? 'hq';
    2143         $content .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">YouTube Thumbnail Quality</label><span class="vnspo-row-desc">Image quality for YouTube thumbnails</span></div>' .
    2144             '<select name="vnspo_options[youtube_thumb_quality]" class="vnspo-select">' .
    2145             '<option value="default"' . ($yt_quality === 'default' ? ' selected' : '') . '>Default</option>' .
    2146             '<option value="mqdefault"' . ($yt_quality === 'mqdefault' ? ' selected' : '') . '>Medium</option>' .
    2147             '<option value="hqdefault"' . ($yt_quality === 'hqdefault' ? ' selected' : '') . '>High</option>' .
    2148             '<option value="sddefault"' . ($yt_quality === 'sddefault' ? ' selected' : '') . '>Standard</option>' .
    2149             '<option value="maxresdefault"' . ($yt_quality === 'maxresdefault' ? ' selected' : '') . '>Max Resolution</option>' .
    2150             '</select></div>';
    2151 
    2152         $content .= '<div class="vnspo-section-title">Other Media</div>';
    2153         $content .= $this->toggleHtml('smart_images', 'Smart Image Priority & Local WebP', 'Prioritize hero image (fetchpriority=high) and serve local .webp files when available on disk', $options);
    2154         $content .= $this->toggleHtml('google_maps_lazy', 'Smart Maps (Click-to-Load)', 'Replace Google Maps with clickable preview', $options);
    2155         $content .= $this->toggleHtml('local_gravatar', 'Local Gravatar Cache', 'Cache avatars locally to reduce DNS lookups', $options);
    2156         $content .= $this->toggleHtml('smart_embeds', 'Smart Embeds', 'Optimize embedded content (videos, maps, social posts)', $options);
    2157         $content .= $this->toggleHtml('fix_img_dimensions', 'Fix Image Dimensions', 'Add width/height attributes to prevent CLS', $options);
    2158 
    2159         return $this->card('Media & Images', $icon, $content);
    2160     }
    2161 
    2162     private function tabImageOptimizer($options)
    2163     {
    2164         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>';
    2165 
    2166         $imagick_formats = array();
    2167         if (\class_exists('\\Imagick')) {
    2168             try {
    2169                 $imagick_formats = array_map('strtoupper', \Imagick::queryFormats());
    2170             } catch (\Throwable $e) {
    2171                 $imagick_formats = array();
    2172             }
    2173         }
    2174         $imagick_jpeg = in_array('JPEG', $imagick_formats, true) || in_array('JPG', $imagick_formats, true);
    2175         $imagick_png  = in_array('PNG', $imagick_formats, true);
    2176         $imagick_webp = in_array('WEBP', $imagick_formats, true);
    2177         $imagick_avif = in_array('AVIF', $imagick_formats, true);
    2178         $gd_jpeg = \function_exists('imagecreatefromjpeg') && \function_exists('imagejpeg');
    2179         $gd_png  = \function_exists('imagecreatefrompng') && \function_exists('imagepng');
    2180         $gd_webp = \function_exists('imagecreatefromwebp') && \function_exists('imagewebp');
    2181         $gd_avif = \function_exists('imageavif');
    2182         $status_text = static function ($available) {
    2183             return $available ? __('Available', 'vn-speed-optimizer') : __('Not detected', 'vn-speed-optimizer');
    2184         };
    2185 
    2186         $is_pro_licensed  = (bool) \apply_filters('vnspo_is_pro_active', false);
    2187         $is_pro_installed = \defined('VNSPO_PRO_VERSION');
    2188 
    2189         if ($is_pro_licensed) {
    2190             $pro_action_btn = '<button type="button" id="vnspo-pro-bulk-images-btn" class="button button-primary">' . esc_html__('Bulk Compress + AVIF (Pro)', 'vn-speed-optimizer') . '</button>';
    2191         } elseif ($is_pro_installed) {
    2192             $pro_action_btn = '<a href="' . esc_url(admin_url('admin.php?page=vn-speed-optimizer&tab=pro')) . '" class="button button-secondary">' . esc_html__('Activate Pro for Bulk + AVIF', 'vn-speed-optimizer') . '</a>';
    2193         } else {
    2194             $pro_action_btn = '<a href="' . esc_url('https://vn-nexus.com/vnspo-pro') . '" target="_blank" rel="noopener noreferrer" class="button button-secondary">' . esc_html__('Bulk + AVIF + Auto-Resize (Pro)', 'vn-speed-optimizer') . '</a>';
    2195         }
    2196 
    2197         $scanner  = '<div class="vnspo-row" style="flex-direction:column;align-items:stretch;gap:12px;">';
    2198         $scanner .= '<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">' .
    2199             '<div class="vnspo-row-info">' .
    2200                 '<span class="vnspo-row-label">' . esc_html($is_pro_licensed ? __('Pro Bulk Image & AVIF Optimizer (> 80 KB)', 'vn-speed-optimizer') : __('Local WebP / Image Compressor (> 80 KB)', 'vn-speed-optimizer')) . '</span>' .
    2201                 '<span class="vnspo-row-desc">' . esc_html($is_pro_licensed
    2202                     ? __('Scan wp-content/uploads, run 1-click Bulk Compress + AVIF (25 images/batch), or auto-compress on upload using hosting Imagick/GD.', 'vn-speed-optimizer')
    2203                     : __('Scan wp-content/uploads for oversized images and manually re-compress individual files locally using hosting Imagick/GD (only overwrites when smaller).', 'vn-speed-optimizer')) . '</span>' .
    2204             '</div>' .
    2205             '<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">' .
    2206                 '<input type="search" id="vnspo-scan-image-search" placeholder="' . esc_attr__('Filter filename (e.g. hero-mobile)...', 'vn-speed-optimizer') . '" class="vnspo-input" style="min-width:210px;padding:4px 10px;border:1px solid var(--v-border);border-radius:6px;">' .
    2207                 '<button type="button" id="vnspo-scan-images-btn" class="button button-primary">' . esc_html__('Scan Oversized Images', 'vn-speed-optimizer') . '</button>' .
    2208                 $pro_action_btn .
    2209             '</div>' .
    2210         '</div>';
    2211         $scanner .= '<div id="vnspo-oversized-results" style="font-size:13px;color:var(--v-muted);">' . esc_html__('Click "Scan Oversized Images" to inspect real file sizes in wp-content/uploads.', 'vn-speed-optimizer') . '</div>';
    2212         $scanner .= '<div class="notice notice-info inline" style="margin:12px 0;padding:8px 12px;">';
    2213         $scanner .= '<p><strong>' . esc_html__('PHP image support detected on this site', 'vn-speed-optimizer') . '</strong></p><ul style="list-style:disc;margin-left:20px;">';
    2214         /* translators: Dynamic value placeholder. */
    2215         $scanner .= '<li><strong>JPEG:</strong> ' . esc_html(sprintf(__('Imagick: %1$s; GD: %2$s', 'vn-speed-optimizer'), $status_text($imagick_jpeg), $status_text($gd_jpeg))) . '</li>';
    2216         /* translators: Dynamic value placeholder. */
    2217         $scanner .= '<li><strong>PNG:</strong> ' . esc_html(sprintf(__('Imagick: %1$s; GD: %2$s', 'vn-speed-optimizer'), $status_text($imagick_png), $status_text($gd_png))) . '</li>';
    2218         /* translators: Dynamic value placeholder. */
    2219         $scanner .= '<li><strong>WebP:</strong> ' . esc_html(sprintf(__('Imagick: %1$s; GD: %2$s', 'vn-speed-optimizer'), $status_text($imagick_webp), $status_text($gd_webp))) . '</li>';
    2220         /* translators: Dynamic value placeholder. */
    2221         $scanner .= '<li><strong>AVIF generation:</strong> ' . esc_html(sprintf(__('Imagick: %1$s; GD: %2$s', 'vn-speed-optimizer'), $status_text($imagick_avif), $status_text($gd_avif))) . '</li>';
    2222         $scanner .= '</ul>';
    2223         if ($is_pro_licensed) {
    2224             $scanner .= '<p><strong>' . esc_html__('Pro Bulk + AVIF Engine Active:', 'vn-speed-optimizer') . '</strong> ' . esc_html__('Batch compression (up to 25 images/click), automatic upload optimization, and .avif sibling generation are enabled. Configure quality in the Pro Engine tab.', 'vn-speed-optimizer') . '</p></div>';
    2225         } else {
    2226             $scanner .= '<p>' . esc_html__('The Free compressor handles one image at a time and needs Imagick or GD support for that format. In cPanel, enable imagick or gd for the PHP version used by this site; GD must include WebP support to process WebP. If an extension is unavailable, ask your hosting provider to enable it. VN Speed Optimizer cannot enable PHP extensions itself.', 'vn-speed-optimizer') . '</p></div>';
    2227         }
    2228         $scanner .= '</div>';
    2229 
    2230         if ($is_pro_licensed) {
    2231             $settings  = '<p style="margin:0;">' . esc_html__('Automatic WebP/AVIF conversion on upload, bulk compression, and frontend AVIF delivery are active via VNSPO Pro.', 'vn-speed-optimizer') . ' ';
    2232             $settings .= '<a href="' . esc_url(admin_url('admin.php?page=vn-speed-optimizer&tab=pro')) . '">' . esc_html__('Configure in Pro Engine →', 'vn-speed-optimizer') . '</a></p>';
    2233         } else {
    2234             $settings  = '<p style="margin:0;">' . esc_html__('The Free edition provides manual per-image scanning and compression above. Automatic compression on upload, bulk library optimization, and AVIF generation require VNSPO Pro.', 'vn-speed-optimizer') . ' ';
    2235             $settings .= '<a href="' . esc_url('https://vn-nexus.com/vnspo-pro') . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Learn more about VNSPO Pro →', 'vn-speed-optimizer') . '</a></p>';
    2236         }
    2237 
    2238         return $this->card('Image Optimizer (Scanner & Compressor)', $icon, $scanner) .
    2239             $this->card('Automatic WebP & AVIF (Pro)', $icon, $settings);
    2240     }
    2241 
    2242     private function tabCache($options)
    2243     {
    2244         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>';
    2245 
    2246         $content  = '<div class="vnspo-section-title">Cache Preload</div>';
    2247         $content .= $this->toggleHtml('preload_queue_enabled', 'Preload Queue', 'Database-backed persistent queue for preloading pages via sitemap', $options);
    2248         $content .= $this->toggleHtml('preloader_enabled', 'Cache Preloader', 'Warm up page cache by crawling your XML sitemap automatically', $options);
    2249         $content .= $this->numberInputHtml('preload_queue_concurrent', 'Concurrent Requests', 'Simultaneous preload requests (default: 3)', $options, 1, 20);
    2250         $content .= $this->numberInputHtml('preload_queue_batch_size', 'Batch Size', 'URLs to preload per batch (default: 10)', $options, 1, 100);
    2251 
    2252         $content .= '<div class="vnspo-section-title">Critical CSS</div>';
    2253         $content .= $this->toggleHtml('critical_css', 'Inline Critical CSS', 'Eliminate render-blocking CSS by inlining critical styles', $options);
    2254         $content .= '<div class="vnspo-section-title">Object Cache (Redis)</div>';
    2255         $content .= $this->toggleHtml('object_cache_enabled', 'Object Cache (Redis/Memcached)', 'Install object-cache.php drop-in for persistent object caching', $options);
    2256         $redis_host = isset($options['object_cache_redis_host']) ? esc_attr($options['object_cache_redis_host']) : '127.0.0.1';
    2257         $redis_port = isset($options['object_cache_redis_port']) ? esc_attr($options['object_cache_redis_port']) : '6379';
    2258         $redis_db = isset($options['object_cache_redis_database']) ? esc_attr($options['object_cache_redis_database']) : '0';
    2259         $redis_pass = isset($options['object_cache_redis_password']) ? esc_attr($options['object_cache_redis_password']) : '';
    2260         $redis_prefix = isset($options['object_cache_redis_prefix']) ? esc_attr($options['object_cache_redis_prefix']) : '';
    2261         $content .= '<div class="vnspo-field"><label>Redis Host</label><input type="text" name="vnspo_options[object_cache_redis_host]" value="' . $redis_host . '" placeholder="127.0.0.1" class="vnspo-input"></div>';
    2262         $content .= '<div class="vnspo-field"><label>Redis Port</label><input type="number" name="vnspo_options[object_cache_redis_port]" value="' . $redis_port . '" placeholder="6379" class="vnspo-input" style="width:100px;"></div>';
    2263         $content .= '<div class="vnspo-field"><label>Redis Password</label><input type="password" name="vnspo_options[object_cache_redis_password]" value="' . $redis_pass . '" placeholder="Leave empty for no auth" class="vnspo-input"></div>';
    2264         $content .= '<div class="vnspo-field"><label>Redis Database</label><input type="number" name="vnspo_options[object_cache_redis_database]" value="' . $redis_db . '" placeholder="0" class="vnspo-input" style="width:80px;"></div>';
    2265         $content .= '<div class="vnspo-field"><label>Redis Key Prefix</label><input type="text" name="vnspo_options[object_cache_redis_prefix]" value="' . $redis_prefix . '" placeholder="vnspo_" class="vnspo-input"></div>';
    2266 
    2267         $content .= '<div class="vnspo-section-title">Varnish Integration</div>';
    2268         $content .= $this->toggleHtml('varnish_auto_purge', 'Varnish Auto-Purge', 'Automatically purge Varnish cache when content changes', $options);
    2269 
    2270         $content .= '<div class="vnspo-section-title">Static Caching</div>';
    2271         $content .= $this->toggleHtml('page_cache', 'Static Page Cache', 'Cache HTML pages to disk for instant delivery', $options);
    2272         $content .= $this->toggleHtml('defer_js', 'Defer JavaScript', 'Move non-critical JS to footer', $options);
    2273 
    2274         return $this->card('Cache & Preload', $icon, $content);
    2275     }
    2276 
    2277     private function tabDatabase($options)
    2278     {
    2279         $card = new AdvancedDatabaseCard($options);
    2280         $html = $card->render();
    2281         // Strip the outer <div class="vnspo-card"> wrapper added by the card class
    2282         $html = preg_replace('/^<div class="vnspo-card">/', '', $html);
    2283         $html = preg_replace('/<\/div>\s*$/s', '', $html);
    2284         return $html;
    2285     }
    2286 
    2287     private function tabSecurity($options)
    2288     {
    2289         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>';
    2290 
    2291         $content  = '<div class="vnspo-section-title">Core Security</div>';
    2292         $content .= $this->toggleHtml('security_headers_enabled', 'Enable Security Headers', 'Master toggle for all HTTP security headers', $options);
    2293         $content .= $this->toggleHtml('security_x_content_type', 'X-Content-Type-Options', 'Prevent MIME-type sniffing (nosniff)', $options);
    2294         $content .= $this->toggleHtml('security_hide_powered_by', 'Hide X-Powered-By', 'Remove server signature from HTTP headers', $options);
    2295 
    2296         $xframe = $options['security_xframe'] ?? 'sameorigin';
    2297         $content .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">X-Frame-Options</label><span class="vnspo-row-desc">Prevent clickjacking via iframe embedding</span></div>' .
    2298             '<select name="vnspo_options[security_xframe]" class="vnspo-select">' .
    2299             '<option value="sameorigin"' . ($xframe === 'sameorigin' ? ' selected' : '') . '>SameOrigin (Recommended)</option>' .
    2300             '<option value="deny"' . ($xframe === 'deny' ? ' selected' : '') . '>Deny (Most restrictive)</option>' .
    2301             '</select></div>';
    2302 
    2303         $content .= '<div class="vnspo-section-title">HSTS (Strict Transport Security)</div>';
    2304         $content .= $this->toggleHtml('security_hsts', 'Enable HSTS', 'Force browsers to connect via HTTPS only. Only enable if your site is fully HTTPS.', $options);
    2305         $hsts_age = $options['security_hsts_max_age'] ?? '31536000';
    2306         $content .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">HSTS Max-Age</label><span class="vnspo-row-desc">How long to remember HSTS setting</span></div>' .
    2307             '<select name="vnspo_options[security_hsts_max_age]" class="vnspo-select">' .
    2308             '<option value="15768000"' . ($hsts_age === '15768000' ? ' selected' : '') . '>6 months</option>' .
    2309             '<option value="31536000"' . ($hsts_age === '31536000' ? ' selected' : '') . '>1 year (Recommended)</option>' .
    2310             '<option value="63072000"' . ($hsts_age === '63072000' ? ' selected' : '') . '>2 years</option>' .
    2311             '</select></div>';
    2312         $content .= $this->toggleHtml('security_hsts_subdomains', 'Include Subdomains', 'Apply HSTS policy to all subdomains', $options);
    2313 
    2314         $content .= '<div class="vnspo-section-title">Advanced Headers</div>';
    2315         $ref_policy = $options['security_referrer_policy'] ?? 'no-referrer-when-downgrade';
    2316         $content .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">Referrer-Policy</label><span class="vnspo-row-desc">Controls information sent in the Referer header</span></div>' .
    2317             '<select name="vnspo_options[security_referrer_policy]" class="vnspo-select">' .
    2318             '<option value="no-referrer-when-downgrade"' . ($ref_policy === 'no-referrer-when-downgrade' ? ' selected' : '') . '>no-referrer-when-downgrade</option>' .
    2319             '<option value="strict-origin-when-cross-origin"' . ($ref_policy === 'strict-origin-when-cross-origin' ? ' selected' : '') . '>strict-origin-when-cross-origin</option>' .
    2320             '<option value="same-origin"' . ($ref_policy === 'same-origin' ? ' selected' : '') . '>same-origin</option>' .
    2321             '<option value="no-referrer"' . ($ref_policy === 'no-referrer' ? ' selected' : '') . '>no-referrer</option>' .
    2322             '<option value="strict-origin"' . ($ref_policy === 'strict-origin' ? ' selected' : '') . '>strict-origin</option>' .
    2323             '<option value="origin"' . ($ref_policy === 'origin' ? ' selected' : '') . '>origin</option>' .
    2324             '<option value="origin-when-cross-origin"' . ($ref_policy === 'origin-when-cross-origin' ? ' selected' : '') . '>origin-when-cross-origin</option>' .
    2325             '</select></div>';
    2326         $content .= $this->toggleHtml('security_permissions_policy', 'Permissions-Policy', 'Control browser features (camera, mic, geolocation, payments)', $options);
    2327         $content .= $this->toggleHtml('security_csp', 'Content-Security-Policy (CSP)', 'Advanced control over resource loading. May break site if misconfigured.', $options);
    2328 
    2329         return $this->card('Security & Headers', $icon, $content);
    2330     }
    2331 
    2332     private function tabAdvanced($options)
    2333     {
    2334         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"/></svg>';
    2335 
    2336         $html  = '<div class="vnspo-section-title">Asset Optimization</div>';
    2337         $html .= $this->toggleHtml('asset_combination', 'Combine CSS/JS Files', 'Merge multiple CSS/JS files into single requests for HTTP/1.x optimization', $options);
    2338         $html .= $this->numberInputHtml('inline_threshold', 'Inline Threshold (bytes)', 'Inline small CSS/JS files below this size (default: 500)', $options, 0, 10000, 100);
    2339         $html .= $this->toggleHtml('asset_organizer', 'Asset Organizer', 'Re-order and group CSS/JS by dependency for optimal loading sequence', $options);
    2340         $html .= $this->toggleHtml('asset_organizer_group', 'Group by Category', 'Group assets by source (core, theme, plugins) and type', $options);
    2341         $html .= $this->toggleHtml('asset_organizer_woo', 'WooCommerce Optimization', 'Special handling for WooCommerce asset loading order', $options);
    2342 
    2343         $html .= '<div class="vnspo-section-title">Prefetch & Navigation</div>';
    2344         $html .= $this->toggleHtml('smart_prefetch', 'Smart Prefetch', 'Prefetch pages based on hover intent, viewport visibility, and data-saver mode', $options);
    2345         $html .= $this->toggleHtml('prefetch_viewport', 'Viewport Prefetch', 'Prefetch links currently in or near the viewport', $options);
    2346         $html .= $this->toggleHtml('prefetch_prerender', 'Prerender Next Page', 'Full prerender of next likely page (uses more bandwidth)', $options);
    2347         $html .= $this->toggleHtml('prefetch_data_saver', 'Data Saver Aware', 'Only prefetch when user has not enabled data saver mode', $options);
    2348 
    2349         $prefetch_method = $options['prefetch_method'] ?? 'hover';
    2350         $html .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">Prefetch Method</label><span class="vnspo-row-desc">When to trigger prefetch</span></div>' .
    2351             '<select name="vnspo_options[prefetch_method]" class="vnspo-select">' .
    2352             '<option value="hover"' . ($prefetch_method === 'hover' ? ' selected' : '') . '>On Link Hover</option>' .
    2353             '<option value="viewport"' . ($prefetch_method === 'viewport' ? ' selected' : '') . '>On Viewport Entry</option>' .
    2354             '<option value="both"' . ($prefetch_method === 'both' ? ' selected' : '') . '>Both Hover + Viewport</option>' .
    2355             '</select></div>';
    2356 
    2357         $prefetch_eag = $options['prefetch_eagerness'] ?? 'moderate';
    2358         $html .= '<div class="vnspo-row"><div class="vnspo-row-info"><label class="vnspo-row-label">Prefetch Eagerness</label><span class="vnspo-row-desc">How aggressively to prefetch</span></div>' .
    2359             '<select name="vnspo_options[prefetch_eagerness]" class="vnspo-select">' .
    2360             '<option value="conservative"' . ($prefetch_eag === 'conservative' ? ' selected' : '') . '>Conservative</option>' .
    2361             '<option value="moderate"' . ($prefetch_eag === 'moderate' ? ' selected' : '') . '>Moderate</option>' .
    2362             '<option value="aggressive"' . ($prefetch_eag === 'aggressive' ? ' selected' : '') . '>Aggressive</option>' .
    2363             '</select></div>';
    2364 
    2365         $html .= $this->numberInputHtml('prefetch_hover_delay', 'Hover Delay (ms)', 'Wait this many ms after hover before prefetching (default: 200)', $options, 0, 2000, 50);
    2366 
    2367         $html .= '<div class="vnspo-section-title">Webmaster Verification</div>';
    2368         $google_val = isset($options['google_verify']) ? esc_attr($options['google_verify']) : '';
    2369         $bing_val = isset($options['bing_verify']) ? esc_attr($options['bing_verify']) : '';
    2370         $html .= '<div class="vnspo-field"><label>Google Verification ID</label><input type="text" name="vnspo_options[google_verify]" value="' . $google_val . '" placeholder="Google Search Console" class="vnspo-input"></div>';
    2371         $html .= '<div class="vnspo-field"><label>Bing Verification ID</label><input type="text" name="vnspo_options[bing_verify]" value="' . $bing_val . '" placeholder="Bing Webmaster" class="vnspo-input"></div>';
    2372 
    2373         return $this->card('Advanced', $icon, $html);
    2374     }
    2375 
    2376     private function tabCloudflare($options)
    2377     {
    2378         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>';
    2379         $local_edge_active = !empty($options['html_cache_headers'])
    2380             || !empty($options['smart_prefetch'])
    2381             || !empty($options['preload_queue_enabled'])
    2382             || !empty($options['browser_cache_immutable']);
    2383         $local_status = $local_edge_active
    2384             ? __('Enabled by settings', 'vn-speed-optimizer')
    2385             : __('Disabled by settings', 'vn-speed-optimizer');
    2386 
    2387         $ota_policy = \get_option('vnspo_ota_policy_v1', array());
    2388         $ota_ver = is_array($ota_policy) && !empty($ota_policy['version']) ? $ota_policy['version'] : __('Default local rules', 'vn-speed-optimizer');
    2389         $ota_js_count = (is_array($ota_policy) && !empty($ota_policy['delay_js_exclusions'])) ? count($ota_policy['delay_js_exclusions']) : 0;
    2390 
    2391         $content = '<div class="vnspo-cf-status icon-yellow">' .
    2392             '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>' .
    2393             '<div><strong>' . esc_html__('VN-Nexus Edge services', 'vn-speed-optimizer') . '</strong><span>' . esc_html__('This Free edition does not proxy page HTML through Edge. You can request compatibility exclusions for delayed scripts here; metrics and asset sharing have separate controls in Community settings.', 'vn-speed-optimizer') . '</span></div>' .
    2394         '</div>' .
    2395         '<div class="vnspo-edge-note" style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;">' .
    2396             '<div><strong>' . esc_html__('Delayed-script compatibility rules:', 'vn-speed-optimizer') . '</strong> <span id="vnspo-ota-status">' . esc_html($ota_ver) . ' (' . intval($ota_js_count) . ' script exclusions)</span></div>' .
    2397             '<button type="button" class="button button-secondary" id="btn-vnspo-sync-ota" data-nonce="' . esc_attr(\wp_create_nonce('vnspo_ota_sync_nonce')) . '">' . esc_html__('Fetch rules from Edge', 'vn-speed-optimizer') . '</button>' .
    2398         '</div>' .
    2399         '<p class="description">' . esc_html__('This administrator-initiated request sends no page URL or content. The returned script exclusion patterns are stored locally and used by Delay Non-Critical JS.', 'vn-speed-optimizer') . '</p>' .
    2400         '<script>(function(){var b=document.getElementById("btn-vnspo-sync-ota");if(!b)return;b.addEventListener("click",function(){b.disabled=true;var s=document.getElementById("vnspo-ota-status");if(s)s.textContent="Fetching...";var fd=new FormData();fd.append("action","vnspo_sync_ota_policy");fd.append("nonce",b.getAttribute("data-nonce")||"");fetch(ajaxurl,{method:"POST",body:fd}).then(function(r){return r.json();}).then(function(d){b.disabled=false;if(d&&d.success&&d.data&&s){s.textContent=d.data.version+" ("+d.data.js_count+" script exclusions)";}else if(s){s.textContent="Fetch failed";}}).catch(function(){b.disabled=false;if(s)s.textContent="Fetch failed";});});})();</script>' .
    2401         '<div class="vnspo-edge-note">' .
    2402             '<h4>' . esc_html__('Local optimization settings:', 'vn-speed-optimizer') . ' ' . esc_html($local_status) . '</h4>' .
    2403             '<p>' . esc_html__('These WordPress settings control local cache, preload, and navigation features. This screen does not verify runtime execution and does not disable local settings when remote health is unknown. Remote edge health will be shown separately after secure pairing and live health checks are available.', 'vn-speed-optimizer') . '</p>' .
    2404         '</div>' .
    2405         '<div class="vnspo-cf-toggles">' .
    2406             $this->toggleHtml('html_cache_headers', 'Edge Cache Headers', 'Send cache-friendly headers for static HTML and edge accelerators', $options) .
    2407         '</div>';
    2408 
    2409         return $this->card('VN-Nexus Edge', $icon, $content, false);
    2410     }
    2411 
    2412     /**
    2413      * Fetch aggregated community mesh status from Edge (cached 5 minutes).
    2414      *
    2415      * @return array{online_nodes:int,mesh_available:bool,mesh_version:string}
    2416      */
    2417     private function getCommunityMeshStatus()
    2418     {
    2419         $default = array(
    2420             'opted_in'       => false,
    2421             'online_nodes'   => 0,
    2422             'edge_requests'  => null,
    2423             'mesh_available' => false,
    2424             'mesh_version'   => '',
    2425             'regions'        => array(),
    2426             'edge_pops'      => array(),
    2427         );
    2428 
    2429         $options = \get_option('vnspo_options', array());
    2430         $opted_in = !empty($options['vnspeed_edge_metrics_consent'])
    2431             || (bool) \get_option('vnspeed_edge_metrics_consent', false);
    2432         if (!$opted_in) {
    2433             return $default;
    2434         }
    2435         $default['opted_in'] = true;
    2436 
    2437         $cached = \get_transient('vnspo_community_mesh_status_v3');
    2438         if (is_array($cached) && !empty($cached['online_nodes']) && !empty($cached['edge_pops'])) {
    2439             return $cached;
    2440         }
    2441 
    2442         $data = null;
    2443         $endpoint = (string) \apply_filters(
    2444             'vnspo_edge_endpoint',
    2445             \get_option('vnspo_edge_endpoint', 'https://edge.vn-nexus.com')
    2446         );
    2447         $endpoint = rtrim($endpoint, '/');
    2448         if (!empty($endpoint)) {
    2449             $host = (string) \wp_parse_url($endpoint, PHP_URL_HOST);
    2450             if (!$host || !function_exists('gethostbyname') || @gethostbyname($host) !== $host) {
    2451                 $response = \wp_remote_get(
    2452                     $endpoint . '/api/v1/mesh/status',
    2453                     array(
    2454                         'timeout'    => 4,
    2455                         'sslverify'  => true,
    2456                         'user-agent' => 'VN-Speed-Optimizer/' . (\defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.1'),
    2457                     )
    2458                 );
    2459                 if (!\is_wp_error($response) && 200 === (int) \wp_remote_retrieve_response_code($response)) {
    2460                     $decoded = json_decode((string) \wp_remote_retrieve_body($response), true);
    2461                     if (is_array($decoded)) {
    2462                         $data = $decoded;
    2463                     }
    2464                 }
    2465             }
    2466         }
    2467 
    2468         if (!is_array($data)) {
    2469             \set_transient('vnspo_community_mesh_status_v3', $default, 5 * MINUTE_IN_SECONDS);
    2470             return $default;
    2471         }
    2472 
    2473         $regions = isset($data['regions']) && is_array($data['regions']) ? $data['regions'] : array();
    2474         $edge_pops = isset($data['edge_pops']) && is_array($data['edge_pops']) ? $data['edge_pops'] : array();
    2475         $unified_total = 0;
    2476         foreach ($edge_pops as $pop) {
    2477             if (!empty($pop['count'])) {
    2478                 $unified_total += (int) $pop['count'];
    2479             }
    2480         }
    2481         $edge_requests = isset($data['edge_pop_requests'])
    2482             ? (int) $data['edge_pop_requests']
    2483             : (!empty($edge_pops) ? $unified_total : null);
    2484 
    2485         $online_count = isset($data['online_peers'])
    2486             ? (int) $data['online_peers']
    2487             : (isset($data['online_nodes']) ? (int) $data['online_nodes'] : 0);
    2488 
    2489         $result = array(
    2490             'online_nodes'   => max(0, $online_count),
    2491             'edge_requests'  => null === $edge_requests ? null : max(0, $edge_requests),
    2492             'mesh_available' => (!empty($data['available']) || !empty($data['mesh_available'])) && $online_count > 0,
    2493             'mesh_version'   => isset($data['version'])
    2494                 ? \sanitize_text_field((string) $data['version'])
    2495                 : (isset($data['mesh_version']) ? \sanitize_text_field((string) $data['mesh_version']) : ''),
    2496             'regions'        => $regions,
    2497             'edge_pops'      => $edge_pops,
    2498         );
    2499         \set_transient('vnspo_community_mesh_status_v3', $result, 5 * MINUTE_IN_SECONDS);
    2500 
    2501         return $result;
    2502     }
    2503 
    2504     /**
    2505      * Show the opt-in sharing state and privacy-safe node map summary.
    2506      */
    2507     private function tabCommunity($options)
    2508     {
    2509         $metrics_on = (bool) \get_option('vnspeed_edge_metrics_consent', false) || !empty($options['vnspeed_edge_metrics_consent']);
    2510         $asset_on   = (bool) \get_option('vnspeed_edge_asset_consent', false) || !empty($options['vnspeed_edge_asset_consent']);
    2511         $options['vnspeed_edge_metrics_consent'] = $metrics_on ? 1 : 0;
    2512         $options['vnspeed_edge_asset_consent']   = $asset_on ? 1 : 0;
    2513         $enabled = $metrics_on || $asset_on || !empty($options['community_acceleration']) || !empty($options['community_cdn']);
    2514         $mesh_status = $this->getCommunityMeshStatus();
    2515         $online_nodes = (int) $mesh_status['online_nodes'];
    2516         $regions = !empty($mesh_status['regions']) && is_array($mesh_status['regions']) ? $mesh_status['regions'] : array();
    2517         $edge_pops = !empty($mesh_status['edge_pops']) && is_array($mesh_status['edge_pops']) ? $mesh_status['edge_pops'] : array();
    2518 
    2519         // Projection helper matching assets/world-map.svg (Equirectangular 1000x500, lat -60..85)
    2520         $proj = static function ($lon, $lat) {
    2521             $lat_c = max(-60.0, min(85.0, (float) $lat));
    2522             $x = round((((float) $lon + 180.0) / 360.0) * 1000.0, 1);
    2523             $y = round(((90.0 - $lat_c) / 150.0) * 500.0, 1);
    2524             return array('x' => $x, 'y' => $y);
    2525         };
    2526 
    2527         $region_latlon = array(
    2528             'vn'     => array('lat' => 16.0, 'lon' => 107.0, 'label' => 'Vietnam (VN)'),
    2529             'sg'     => array('lat' => 1.35, 'lon' => 103.8, 'label' => 'Singapore (SG)'),
    2530             'ap'     => array('lat' => 22.3, 'lon' => 114.2, 'label' => 'Asia Pacific (AP)'),
    2531             'asia'   => array('lat' => 26.0, 'lon' => 108.0, 'label' => 'Asia (ASIA)'),
    2532             'jp'     => array('lat' => 35.7, 'lon' => 139.7, 'label' => 'Japan (JP)'),
    2533             'kr'     => array('lat' => 37.5, 'lon' => 127.0, 'label' => 'South Korea (KR)'),
    2534             'in'     => array('lat' => 20.6, 'lon' => 78.9, 'label' => 'India (IN)'),
    2535             'eu'     => array('lat' => 50.1, 'lon' => 8.7, 'label' => 'Europe (EU)'),
    2536             'uk'     => array('lat' => 51.5, 'lon' => -0.1, 'label' => 'London, GB (UK)'),
    2537             'us'     => array('lat' => 39.0, 'lon' => -77.5, 'label' => 'United States (US)'),
    2538             'na'     => array('lat' => 39.0, 'lon' => -98.0, 'label' => 'North America (NA)'),
    2539             'sa'     => array('lat' => -23.5, 'lon' => -46.6, 'label' => 'South America (SA)'),
    2540             'au'     => array('lat' => -33.9, 'lon' => 151.2, 'label' => 'Australia (AU)'),
    2541             'global' => array('lat' => 20.0, 'lon' => 0.0, 'label' => 'Global Edge'),
    2542         );
    2543 
    2544         // Public Cloudflare Data Center (IATA) coordinates for map pins (contains zero visitor/origin PII).
    2545         $colo_latlon = array(
    2546             'SIN' => array(1.35, 103.82), 'SGN' => array(10.82, 106.63), 'HAN' => array(21.03, 105.85),
    2547             'HKG' => array(22.31, 114.17), 'NRT' => array(35.76, 140.39), 'KIX' => array(34.43, 135.24),
    2548             'ICN' => array(37.46, 126.44), 'TPE' => array(25.08, 121.23), 'BKK' => array(13.69, 100.75),
    2549             'IAD' => array(38.95, -77.45), 'EWR' => array(40.69, -74.17), 'CMH' => array(40.00, -82.89),
    2550             'ATL' => array(33.64, -84.43), 'DFW' => array(32.90, -97.04), 'SJC' => array(37.36, -121.93),
    2551             'LAX' => array(33.94, -118.41), 'ORD' => array(41.97, -87.90), 'SEA' => array(47.45, -122.31),
    2552             'LHR' => array(51.47, -0.45),  'FRA' => array(50.03, 8.56),   'AMS' => array(52.31, 4.76),
    2553             'CDG' => array(49.01, 2.55),   'SYD' => array(-33.94, 151.18), 'BOM' => array(19.09, 72.87),
    2554         );
    2555 
    2556         // Merge Edge PoPs and Opt-in WordPress regions into unified global node list
    2557         $unified_nodes = array();
    2558         $total_hits_or_nodes = 0;
    2559         foreach ($edge_pops as $pop) {
    2560             $colo = isset($pop['colo']) ? strtoupper((string) $pop['colo']) : '';
    2561             $cnt = isset($pop['count']) ? (int) $pop['count'] : 0;
    2562             if (!$colo || $cnt <= 0) continue;
    2563             $lat = isset($pop['lat']) && is_numeric($pop['lat']) ? (float) $pop['lat'] : null;
    2564             $lon = isset($pop['lon']) && is_numeric($pop['lon']) ? (float) $pop['lon'] : null;
    2565             if (($lat === null || $lon === null) && isset($colo_latlon[$colo])) {
    2566                 $lat = $colo_latlon[$colo][0];
    2567                 $lon = $colo_latlon[$colo][1];
    2568             }
    2569             $country = isset($pop['country']) ? strtoupper((string) $pop['country']) : '';
    2570             $city = isset($pop['city']) ? (string) $pop['city'] : '';
    2571             $has_coordinates = $lat !== null && $lon !== null
    2572                 && is_finite($lat) && is_finite($lon)
    2573                 && $lat >= -90 && $lat <= 90 && $lon >= -180 && $lon <= 180;
    2574             $pt = $has_coordinates ? $proj($lon, $lat) : array('x' => null, 'y' => null);
    2575             $label = trim(($city ? $city . ', ' : '') . ($country ? $country . ' ' : '') . '(' . $colo . ')');
    2576             $unified_nodes[] = array(
    2577                 'label' => $label,
    2578                 'count' => $cnt,
    2579                 'x'     => $pt['x'],
    2580                 'y'     => $pt['y'],
    2581                 'kind'  => 'edge',
    2582             );
    2583             $total_hits_or_nodes += $cnt;
    2584         }
    2585         foreach ($regions as $reg) {
    2586             $code = isset($reg['region']) ? strtolower((string) $reg['region']) : 'global';
    2587             $cnt = isset($reg['count']) ? (int) $reg['count'] : 0;
    2588             if ($cnt <= 0) continue;
    2589             $ll = isset($region_latlon[$code]) ? $region_latlon[$code] : $region_latlon['global'];
    2590             $pt = isset($region_latlon[$code]) && 'global' !== $code
    2591                 ? $proj($ll['lon'], $ll['lat']) : array('x' => null, 'y' => null);
    2592             $unified_nodes[] = array(
    2593                 'label' => $ll['label'] . ' — WP',
    2594                 'count' => $cnt,
    2595                 'x'     => $pt['x'],
    2596                 'y'     => $pt['y'],
    2597                 'kind'  => 'wp',
    2598             );
    2599             $total_hits_or_nodes += $cnt;
    2600         }
    2601 
    2602         usort($unified_nodes, static function ($a, $b) {
    2603             return $b['count'] <=> $a['count'];
    2604         });
    2605         $max_node_count = !empty($unified_nodes) ? max(1, (int) $unified_nodes[0]['count']) : 1;
    2606         $edge_requests = isset($mesh_status['edge_requests']) ? (int) $mesh_status['edge_requests'] : 0;
    2607         $has_live_nodes = !empty($unified_nodes) || $online_nodes > 0;
    2608         $display_peers = max(0, $online_nodes);
    2609         $display_requests = max(0, $edge_requests);
    2610         $map_svg_url = \defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL . 'assets/world-map.svg' : '';
    2611         ob_start();
    2612         ?>
    2613         <section class="vnspo-community-page">
    2614             <header class="vnspo-community-heading">
    2615                 <div>
    2616                     <h2><?php echo esc_html__('Community network', 'vn-speed-optimizer'); ?></h2>
    2617                     <p><?php echo esc_html__('Optional, privacy-conscious sharing of public static assets.', 'vn-speed-optimizer'); ?></p>
    2618                 </div>
    2619                 <span class="vnspo-state-pill <?php echo $enabled ? 'is-on' : 'is-off'; ?>">
    2620                     <?php echo $enabled ? esc_html__('Participation on', 'vn-speed-optimizer') : esc_html__('Not participating', 'vn-speed-optimizer'); ?>
    2621                 </span>
    2622             </header>
    2623 
    2624             <!-- GLOBAL NODE MAP + DISTRIBUTION LIST (2 COLUMNS) -->
    2625             <section class="vnspo-community-panel vnspo-community-map-panel" aria-labelledby="vnspo-node-map-title" style="margin-bottom: 20px;">
    2626                 <div class="vnspo-community-panel-heading">
    2627                     <h3 id="vnspo-node-map-title"><?php echo esc_html__('Global Node Distribution', 'vn-speed-optimizer'); ?></h3>
    2628                     <span>
    2629                         <?php
    2630                         $is_vi = function_exists('get_user_locale') && 0 === strpos((string) \get_user_locale(), 'vi');
    2631                         if (empty($mesh_status['opted_in']) && !$enabled) {
    2632                             echo esc_html($is_vi
    2633                                 ? 'Chưa bật Speed Radar'
    2634                                 : __('Speed Radar is off', 'vn-speed-optimizer'));
    2635                         } elseif (!isset($mesh_status['edge_requests']) || null === $mesh_status['edge_requests']) {
    2636                             echo esc_html($is_vi
    2637                                 ? sprintf('%s node đã đăng ký • Không lấy được số liệu Edge', \number_format_i18n($display_peers))
    2638                                 : sprintf(__('%s registered peers • Could not fetch Edge metrics', 'vn-speed-optimizer'), \number_format_i18n($display_peers)));
    2639                         } elseif ($has_live_nodes || 0 === $display_requests) {
    2640                             /* translators: Dynamic value placeholder. */
    2641                             echo esc_html(sprintf(__('%1$s registered peers • %2$s Edge PoP requests', 'vn-speed-optimizer'), \number_format_i18n($display_peers), \number_format_i18n($display_requests)));
    2642                         } else {
    2643                             echo esc_html__('Node map', 'vn-speed-optimizer');
    2644                         }
    2645                         ?>
    2646                     </span>
    2647                 </div>
    2648 
    2649                 <div style="display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(260px, 1fr); gap: 20px; align-items: stretch;">
    2650                     <div class="vnspo-community-map" role="img" aria-label="<?php /* translators: Dynamic value placeholder. */ echo esc_attr($has_live_nodes ? sprintf(__('World map with %1$d peers and %2$d Edge requests', 'vn-speed-optimizer'), $display_peers, $display_requests) : __('World map with no live node locations reported yet', 'vn-speed-optimizer')); ?>">
    2651                         <div style="position:relative;width:100%;max-width:620px;aspect-ratio:2/1;margin:0 auto;">
    2652                         <?php if ($map_svg_url) : ?>
    2653                             <img src="<?php echo esc_url($map_svg_url); ?>" alt="" aria-hidden="true" style="position:absolute;inset:0;width:100%;height:100%;object-fit:contain;pointer-events:none;"/>
    2654                         <?php endif; ?>
    2655                         <svg viewBox="0 0 1000 500" preserveAspectRatio="xMidYMid meet" aria-hidden="true" focusable="false" style="position:absolute;inset:0;width:100%;height:100%;">
    2656                             <?php if (!empty($unified_nodes)) : ?>
    2657                                 <?php foreach (array_slice($unified_nodes, 0, 30) as $node) :
    2658                                     if ($node['x'] === null || $node['y'] === null) continue;
    2659                                     $cnt = (int) $node['count'];
    2660                                     $ratio = $cnt / $max_node_count;
    2661                                     $r = round(5 + $ratio * 16, 1);
    2662                                     $fill = 'wp' === $node['kind'] ? '#dc2626' : '#2563eb';
    2663                                 ?>
    2664                                     <g>
    2665                                         <title><?php echo esc_html($node['label'] . ': ' . \number_format_i18n($cnt)); ?></title>
    2666                                         <circle class="vnspo-map-pulse" cx="<?php echo esc_attr($node['x']); ?>" cy="<?php echo esc_attr($node['y']); ?>" r="<?php echo esc_attr($r + 6); ?>" fill="<?php echo esc_attr('wp' === $node['kind'] ? 'rgba(220, 38, 38, 0.22)' : 'rgba(37, 99, 235, 0.20)'); ?>"/>
    2667                                         <circle cx="<?php echo esc_attr($node['x']); ?>" cy="<?php echo esc_attr($node['y']); ?>" r="<?php echo esc_attr($r); ?>" fill="<?php echo esc_attr($fill); ?>" fill-opacity="0.82" stroke="#ffffff" stroke-width="1.5"/>
    2668                                     </g>
    2669                                 <?php endforeach; ?>
    2670                             <?php endif; ?>
    2671                         </svg>
    2672                         </div>
    2673                         <?php if (!$has_live_nodes) : ?>
    2674                         <div class="vnspo-community-empty">
    2675                             <span class="dashicons dashicons-location" aria-hidden="true"></span>
    2676                             <strong><?php echo esc_html__('No live node locations reported yet', 'vn-speed-optimizer'); ?></strong>
    2677                             <p><?php echo esc_html__('Only opted-in participants can appear here. Locations are grouped by broad region after privacy checks.', 'vn-speed-optimizer'); ?></p>
    2678                         </div>
    2679                         <?php endif; ?>
    2680                     </div>
    2681 
    2682                     <!-- RIGHT COLUMN: RANKED NODE DISTRIBUTION LIST (CLOUDFLARE STYLE) -->
    2683                     <div style="background: #ffffff; border: 1px solid var(--vnspo-border); border-radius: 12px; padding: 14px 16px; max-height: 310px; overflow-y: auto;">
    2684                         <div style="font-size: 0.8125rem; font-weight: 700; color: var(--vnspo-text-main); margin-bottom: 10px;">
    2685                             <?php echo esc_html__('Registered peers and observed Edge requests', 'vn-speed-optimizer'); ?>
    2686                         </div>
    2687                         <?php if (empty($unified_nodes)) : ?>
    2688                             <p style="font-size: 0.8125rem; color: var(--vnspo-text-muted); margin: 0;">
    2689                                 <?php echo esc_html__('Waiting for Edge node distribution data.', 'vn-speed-optimizer'); ?>
    2690                             </p>
    2691                         <?php else : ?>
    2692                             <div style="display: grid; gap: 10px;">
    2693                                 <?php foreach (array_slice($unified_nodes, 0, 15) as $node) :
    2694                                     $pct = max(4, (int) round(($node['count'] / $max_node_count) * 100));
    2695                                 ?>
    2696                                     <div style="display: grid; grid-template-columns: minmax(0, 1fr) 72px auto; gap: 10px; align-items: center; font-size: 0.8125rem;">
    2697                                         <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--vnspo-text-main);" title="<?php echo esc_attr($node['label']); ?>">
    2698                                             <?php echo esc_html($node['label']); ?>
    2699                                         </span>
    2700                                         <div style="height: 6px; background: #e2e8f0; border-radius: 999px; overflow: hidden;">
    2701                                             <div style="height: 100%; width: <?php echo esc_attr($pct); ?>%; background: <?php echo 'wp' === $node['kind'] ? '#dc2626' : '#2563eb'; ?>; border-radius: 999px;"></div>
    2702                                         </div>
    2703                                         <strong style="font-variant-numeric: tabular-nums; color: var(--vnspo-text-main);">
    2704                                             <?php echo esc_html(\number_format_i18n($node['count'])); ?>
    2705                                         </strong>
    2706                                     </div>
    2707                                 <?php endforeach; ?>
    2708                             </div>
    2709                         <?php endif; ?>
    2710                     </div>
    2711                 </div>
    2712                 <p class="vnspo-community-map-caption">
    2713                     <?php
    2714                     echo $has_live_nodes
    2715                         ? esc_html__('Aggregate Edge region counts are shown here. The public map does not show visitor IPs, site domains, or exact site locations; Cloudflare still receives ordinary connection metadata such as the origin server IP.', 'vn-speed-optimizer')
    2716                         : esc_html__('No participant counts or locations are shown until verified aggregate data is available.', 'vn-speed-optimizer');
    2717                     ?>
    2718                 </p>
    2719             </section>
    2720 
    2721             <div class="vnspo-community-layout">
    2722 
    2723                 <?php
    2724                 $is_vi = $this->isVietnameseLocale();
    2725                 ?>
    2726                 <aside class="vnspo-community-panel vnspo-community-privacy">
    2727                     <h3><?php echo esc_html($is_vi ? 'Tùy chọn chia sẻ cộng đồng' : __('Community sharing choices', 'vn-speed-optimizer')); ?></h3>
    2728 
    2729                     <div class="vnspo-community-toggle-box" style="margin-bottom: 14px;">
    2730                         <?php
    2731                         $rum_title     = $is_vi ? 'Thu thập số liệu hiệu năng cục bộ' : 'Collect local performance samples';
    2732                         $rum_desc      = $is_vi ? 'Tắt mặc định. Khi bật, trình duyệt gửi các mẫu hiệu năng đã cấu hình về website này để hiển thị trong quản trị; plugin không lưu URL. Chia sẻ số liệu cấp website với Edge cần bật quyền riêng bên dưới.' : 'Off by default. When enabled, configured performance samples are sent to this site for the admin dashboard; URLs are not stored. Sharing site-level metrics with Edge requires the separate consent below.';
    2733                         $metrics_title = $is_vi ? 'Speed Radar (Số liệu Edge công khai & Telemetry)' : 'Speed Radar (Public Edge Metrics & Telemetry)';
    2734                         $metrics_desc  = $is_vi ? 'Mặc định tắt. Khi bật, dashboard đọc số liệu Edge PoP công khai từ Edge; việc gửi telemetry cấp website (tối đa 1 mẫu LCP/ngày, không có URL/PII) yêu cầu ghép nối Edge riêng và chỉ tính là đã gửi khi Edge xác nhận. Có thể tắt bất cứ lúc nào.' : 'Off by default. When enabled, the dashboard reads public Edge PoP totals; sending site-level telemetry (at most one LCP summary per day, zero URLs/PII) requires separate Edge pairing and is only counted after Edge confirmation.';
    2735                         $shield_title  = $is_vi ? 'Community Threat Shield (Lá chắn WAF Cộng đồng)' : 'Community Threat Shield (Crowdsourced WAF)';
    2736                         $shield_bl     = \get_transient('vnspo_community_threat_blacklist');
    2737                         $shield_active = !empty($options['community_threat_shield_enabled']) && is_array($shield_bl) && !empty($shield_bl);
    2738                         $shield_state  = $shield_active
    2739                             ? ($is_vi ? ' [Đang tự chặn ' . count($shield_bl) . ' IP]' : ' [Active: ' . count($shield_bl) . ' IPs]')
    2740                             : '';
    2741                         $shield_desc   = $is_vi ? 'Mặc định tắt. Khi bật, website tải danh sách IP tấn công đã được xác thực từ Edge và chỉ gửi báo cáo IP khi phát hiện >= 5 lần đăng nhập sai trong 5 phút. Có thể tắt bất cứ lúc nào.' : 'Off by default. When enabled, the site fetches verified attacker IPs from Edge and reports an IP only after >= 5 failed logins within 5 minutes.';
    2742                         // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped inside toggleHtml().
    2743                         echo $this->toggleHtml('rum_enabled', $rum_title, $rum_desc, $options);
    2744                         // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped inside toggleHtml().
    2745                         echo $this->toggleHtml('vnspeed_edge_metrics_consent', $metrics_title, $metrics_desc, $options);
    2746                         // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped inside toggleHtml().
    2747                         echo $this->toggleHtml('community_threat_shield_enabled', $shield_title . $shield_state, $shield_desc, $options);
    2748                         ?>
    2749                     </div>
    2750                     <h3><?php echo esc_html($is_vi ? 'Quyền riêng tư mặc định' : __('Privacy by design', 'vn-speed-optimizer')); ?></h3>
    2751 
    2752                     <ul>
    2753                         <li><?php echo esc_html($is_vi ? 'Thu thập RUM cục bộ, chia sẻ metrics lên Edge và chia sẻ tài nguyên là ba quyền riêng biệt, đều tắt mặc định.' : __('Local RUM collection, Edge metrics sharing, and public-asset sharing are separate permissions, all off by default.', 'vn-speed-optimizer')); ?></li>
    2754 
    2755                         <li><?php echo esc_html($is_vi ? 'Trình duyệt chỉ gửi mẫu hiệu năng về website khi bật RUM; Edge chỉ nhận số liệu tổng hợp khi bật quyền chia sẻ riêng. Trình duyệt khách không chuyển tiếp tài nguyên cho nhau.' : __('Browsers send performance samples to your site only when RUM is enabled; Edge receives aggregates only with separate consent. Visitor browsers do not relay assets.', 'vn-speed-optimizer')); ?></li>
    2756 
    2757                         <li><?php echo esc_html($is_vi ? 'Bản đồ công khai không hiển thị IP, domain hoặc vị trí chính xác; Cloudflare vẫn nhận metadata kết nối thông thường.' : __('The public map does not show IPs, domains, or exact locations; Cloudflare still receives ordinary connection metadata.', 'vn-speed-optimizer')); ?></li>
    2758 
    2759                     </ul>
    2760                 </aside>
    2761             </div>
    2762         </section>
    2763         <?php
    2764         return \ob_get_clean();
    2765     }
    2766 
    2767     private function tabTools($options)
    2768     {
    2769         $icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"/></svg>';
    2770 
    2771         $content  = '<div class="vnspo-section-title">' . esc_html__('Error & Accessibility', 'vn-speed-optimizer') . '</div>';
    2772         $content .= $this->toggleHtml('enable_404_monitor', '404 Monitor', 'Track and log 404 errors for analysis', $options);
    2773         $content .= $this->toggleHtml('fix_touch_targets', 'Mobile Touch Targets', 'Expand small clickable areas for mobile accessibility', $options);
    2774         $content .= $this->toggleHtml('fix_empty_links', 'Fix Empty Links', 'Add aria-label to icon-only links', $options);
    2775 
    2776         $content .= '<div class="vnspo-section-title">' . esc_html__('SEO', 'vn-speed-optimizer') . '</div>';
    2777         $content .= $this->toggleHtml('auto_meta_desc', 'Auto Meta Description', 'Automatically generate meta descriptions from content', $options);
    2778         $content .= $this->toggleHtml('aeo_engine', 'AEO Answer Engine', 'AI-powered Quick Answers markup for search engines', $options);
    2779         $content .= $this->toggleHtml('aeo_speakable', 'Speakable Schema', 'Voice search optimization markup', $options);
    2780 
    2781         return $this->card('Tools & SEO', $icon, $content);
    2782     }
    2783 
    2784     /**
    2785      * Render 1-Click Settings Importer card (shared between Overview Dashboard and Tools tab).
    2786      */
    2787     private function renderSettingsImporterCard()
    2788     {
    2789         $is_vi  = $this->isVietnameseLocale();
    2790         $icon   = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>';
    2791 
    2792         $title      = $is_vi ? 'Chuyển đổi cấu hình 1-Click từ Plugin Tăng tốc khác' : __('1-Click Switch from Other Speed Plugins', 'vn-speed-optimizer');
    2793         $label      = $is_vi ? 'Nhập cấu hình 1-Click từ WP Rocket, LiteSpeed Cache, Autoptimize, WP-Optimize' : __('1-Click Switch from WP Rocket, LiteSpeed, Autoptimize, WP-Optimize', 'vn-speed-optimizer');
    2794         $desc       = $is_vi ? 'Tự động quét cấu hình plugin tăng tốc cũ trong cơ sở dữ liệu WordPress và chuyển đổi các tùy chọn tương thích mà không làm mất thiết lập.' : __('Detect existing speed plugin settings in your WordPress database and migrate compatible options cleanly without losing your setup.', 'vn-speed-optimizer');
    2795         $btnText    = $is_vi ? 'Quét Plugin Khác' : __('Scan Other Plugins', 'vn-speed-optimizer');
    2796         $deactText  = $is_vi ? 'Tự động tắt plugin cũ sau khi nhập thành công (tránh xung đột)' : __('Deactivate competitor plugin automatically after successful import (prevents conflicts)', 'vn-speed-optimizer');
    2797         $hintText   = $is_vi ? 'Bấm "Quét Plugin Khác" để kiểm tra các cấu hình đã lưu.' : __('Click "Scan Other Plugins" to detect saved settings.', 'vn-speed-optimizer');
    2798 
    2799         $importer_html  = '<div style="display:flex;flex-direction:column;gap:12px;">';
    2800         $importer_html .= '<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">';
    2801         $importer_html .= '<div class="vnspo-row-info"><span class="vnspo-row-label">' . esc_html($label) . '</span><span class="vnspo-row-desc">' . esc_html($desc) . '</span></div>';
    2802         $importer_html .= '<button type="button" id="vnspo-detect-import-btn" class="button button-primary">' . esc_html($btnText) . '</button>';
    2803         $importer_html .= '</div>';
    2804         $importer_html .= '<label style="display:inline-flex;align-items:center;gap:6px;font-size:13px;"><input type="checkbox" id="vnspo-import-deactivate" checked> ' . esc_html($deactText) . '</label>';
    2805         $importer_html .= '<div id="vnspo-import-results" style="font-size:13px;color:var(--v-muted);">' . esc_html($hintText) . '</div>';
    2806         $importer_html .= '</div>';
    2807 
    2808         return $this->card($title, $icon, $importer_html);
    2809     }
    2810 
    2811     /**
    2812      * Get cached database size in MB (5-minute transient to avoid repeated information_schema scans).
    2813      */
    2814     private function getDatabaseSizeMb()
    2815     {
    2816         $cached = \get_transient('vnspo_db_size_mb_v1');
    2817         if (false !== $cached && is_numeric($cached)) {
    2818             return (float) $cached;
    2819         }
    2820         global $wpdb;
    2821         // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Read-only aggregate cached via transient.
    2822         $db_size = $wpdb->get_var("SELECT ROUND(SUM(data_length) / 1024 / 1024, 2) FROM information_schema.tables WHERE table_schema = DATABASE()");
    2823         $val = $db_size ? (float) $db_size : 0.0;
    2824         \set_transient('vnspo_db_size_mb_v1', $val, 5 * MINUTE_IN_SECONDS);
    2825         return $val;
    2826     }
    2827 
    2828     /**
    2829      * Format byte count for human display (real values only).
    2830      */
    2831     private function formatBytesShort($bytes)
    2832     {
    2833         $bytes = max(0, (int) $bytes);
    2834         if ($bytes >= 1073741824) {
    2835             return number_format_i18n($bytes / 1073741824, 2) . ' GB';
    2836         }
    2837         if ($bytes >= 1048576) {
    2838             return number_format_i18n($bytes / 1048576, 2) . ' MB';
    2839         }
    2840         if ($bytes >= 1024) {
    2841             return number_format_i18n($bytes / 1024, 1) . ' KB';
    2842         }
    2843         return number_format_i18n($bytes) . ' B';
    2844     }
    2845 
    2846     /**
    2847      * Scan all supported local page-cache directories recursively.
    2848      *
    2849      * @return array{count:int,bytes:int}
    2850      */
    2851     private function getLocalCacheStats()
    2852     {
    2853         $upload_dir = \wp_upload_dir();
    2854         $cache_dirs = array(
    2855             $upload_dir['basedir'] . '/vnspo-cache/',
    2856             WP_CONTENT_DIR . '/cache/vnspo/',
    2857             WP_CONTENT_DIR . '/cache/vn-speed-optimizer/',
    2858         );
    2859         $cache_count = 0;
    2860         $cached_html_bytes = 0;
    2861         foreach ($cache_dirs as $c_dir) {
    2862             if (!is_dir($c_dir)) {
    2863                 continue;
    2864             }
    2865             try {
    2866                 $it = new \RecursiveIteratorIterator(
    2867                     new \RecursiveDirectoryIterator($c_dir, \FilesystemIterator::SKIP_DOTS)
    2868                 );
    2869                 foreach ($it as $file) {
    2870                     if ($file->isFile() && preg_match('/\.(html|html\.gz)$/i', $file->getFilename())) {
    2871                         $cache_count++;
    2872                         $cached_html_bytes += (int) $file->getSize();
    2873                     }
    2874                 }
    2875             } catch (\Throwable $e) {
    2876                 // Ignore unreadable cache directory.
    2877             }
    2878         }
    2879         return array('count' => $cache_count, 'bytes' => $cached_html_bytes);
    2880     }
    2881 
    2882     /**
    2883      * Top-of-page Hero Snapshot (Score Ring + 4 high-impact real metrics) placed right below primary tabs.
    2884      */
    2885     private function renderHeroSnapshot($options)
    2886     {
    2887         $score = $this->calculateScore($options);
    2888         $grade = $this->getScoreGrade($score);
    2889         $gradeClass = $this->getScoreGradeClass($grade);
    2890 
    2891         $local_cache = $this->getLocalCacheStats();
    2892         $cache_count = $local_cache['count'];
    2893         $cached_html_bytes = $local_cache['bytes'];
    2894 
    2895         $ttfb_history = \get_option('vnspo_ttfb_history', array());
    2896         $latest_ttfb = (is_array($ttfb_history) && !empty($ttfb_history[0]) && is_array($ttfb_history[0])) ? $ttfb_history[0] : null;
    2897         $ttfb_text = $latest_ttfb
    2898             ? ((int) $latest_ttfb['cached_ms'] . ' ms (-' . (int) $latest_ttfb['improvement_pct'] . '%)')
    2899             : __('Not measured', 'vn-speed-optimizer');
    2900 
    2901         $security_headers_active = !empty($options['security_headers_enabled']);
    2902         $security_headers_text = $security_headers_active
    2903             ? __('Enabled by settings', 'vn-speed-optimizer')
    2904             : __('Off', 'vn-speed-optimizer');
    2905 
    2906         $active_count = 0;
    2907         $dashboard_options = $this->getAllDashboardBoolOptionKeys();
    2908         foreach ($dashboard_options as $opt) {
    2909             if (!empty($options[$opt])) $active_count++;
    2910         }
    2911         $total_options = count($dashboard_options);
    2912 
    2913         $core_active = 0;
    2914         $core_keys = $this->getScoreOptionKeys();
    2915         foreach ($core_keys as $opt) {
    2916             if (!empty($options[$opt])) {
    2917                 $core_active++;
    2918             }
    2919         }
    2920         $core_total = count($core_keys);
    2921 
    2922         $circumference = 283;
    2923         $offset = $circumference - ($circumference * $score) / 100;
    2924         $ring_color = $this->getScoreRingColor($score);
    2925 
    2926         ob_start();
    2927         ?>
    2928         <div class="vnspo-dashboard-hero">
    2929             <div class="vnspo-hero-score">
    2930                 <div class="vnspo-score-ring" id="score-ring">
    2931                     <svg class="vnspo-score-ring-svg" viewBox="0 0 100 100">
    2932                         <circle class="vnspo-score-ring-bg" cx="50" cy="50" r="45"/>
    2933                         <circle class="vnspo-score-ring-circle vnspo-score-animate"
    2934                             cx="50" cy="50" r="45"
    2935                             style="stroke-dashoffset: <?php echo esc_attr($offset); ?>; stroke: <?php echo esc_attr($ring_color); ?>;"/>
    2936                     </svg>
    2937                     <div class="vnspo-score-ring-content">
    2938                         <div class="vnspo-score-ring-grade <?php echo esc_attr($gradeClass); ?>"><?php echo esc_html($grade); ?></div>
    2939                         <div class="vnspo-score-ring-percent" id="opt-score"><?php echo esc_html($score); ?>%</div>
    2940                     </div>
    2941                 </div>
    2942                 <p style="color: var(--vnspo-text-muted); font-size: 0.875rem; margin: 8px 0 0;">
    2943                     <?php
    2944                     /* translators: 1: active core options count, 2: total core options count, 3: total active options count, 4: total boolean options count */
    2945                     echo esc_html(sprintf(__('Core Optimization: %1$d/%2$d active (Total: %3$d/%4$d options)', 'vn-speed-optimizer'), $core_active, $core_total, $active_count, $total_options));
    2946                     ?>
    2947                 </p>
    2948             </div>
    2949 
    2950             <div class="vnspo-hero-metrics">
    2951                 <?php
    2952                 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped inside getMetricCardHtml().
    2953                 echo $this->getMetricCardHtml(
    2954                     __('Avg TTFB', 'vn-speed-optimizer'),
    2955                     $ttfb_text,
    2956                     'database',
    2957                     $latest_ttfb ? 'primary' : 'warning'
    2958                 );
    2959                 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped inside getMetricCardHtml().
    2960                 echo $this->getMetricCardHtml(
    2961                     __('Cached Pages', 'vn-speed-optimizer'),
    2962                     number_format_i18n($cache_count),
    2963                     'server',
    2964                     $cache_count > 0 ? 'primary' : 'warning'
    2965                 );
    2966                 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped inside getMetricCardHtml().
    2967                 echo $this->getMetricCardHtml(
    2968                     __('Cached Disk Size', 'vn-speed-optimizer'),
    2969                     $this->formatBytesShort($cached_html_bytes),
    2970                     'eye',
    2971                     $cached_html_bytes > 0 ? 'primary' : 'warning'
    2972                 );
    2973                 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped inside getMetricCardHtml().
    2974                 echo $this->getMetricCardHtml(
    2975                     __('Security headers', 'vn-speed-optimizer'),
    2976                     $security_headers_text,
    2977                     'shield',
    2978                     $security_headers_active ? 'primary' : 'warning'
    2979                 ); ?>
    2980             </div>
    2981         </div>
    2982         <?php
    2983         return ob_get_clean();
    2984     }
    2985 
    2986     /**
    2987      * Dashboard V2 - Premium SaaS-grade layout
    2988      */
    2989     private function renderDashboardV2($options)
    2990     {
    2991         $cache_layer = $this->getCacheLayerStatus($options);
    2992         $ttfb_history = \get_option('vnspo_ttfb_history', array());
    2993         if (!is_array($ttfb_history)) {
    2994             $ttfb_history = array();
    2995         }
    2996         $latest_ttfb = !empty($ttfb_history[0]) && is_array($ttfb_history[0]) ? $ttfb_history[0] : null;
    2997         $baseline = \get_option('vnspo_activation_baseline', null);
    2998         if (!is_array($baseline)) {
    2999             $baseline = null;
    3000         }
    3001         $activity_log = \get_option('vnspo_activity_log', array());
    3002         if (!is_array($activity_log)) {
    3003             $activity_log = array();
    3004         }
    3005         $activity_labels = array(
    3006             'setting_toggled'   => __('Setting updated', 'vn-speed-optimizer'),
    3007             'recommended_setup' => __('Recommended setup applied', 'vn-speed-optimizer'),
    3008             'ttfb_measured'     => __('TTFB benchmark measured', 'vn-speed-optimizer'),
    3009             'cache_cleared'     => __('Cache cleared', 'vn-speed-optimizer'),
    3010             'db_optimized'      => __('Database optimized', 'vn-speed-optimizer'),
    3011         );
    3012 
    3013         ob_start();
    3014 ?>
    3015 <div class="vnspo-dashboard-v2">
    3016 
    3017     <!-- REAL SPEED PROOF (MULTI-PAGE ORIGIN VS CACHE HIT) -->
    3018     <div class="vnspo-card-glass">
    3019         <div class="vnspo-card-glass-header">
    3020             <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--vnspo-primary)" stroke-width="2">
    3021                 <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
    3022             </svg>
    3023             <h3 style="margin: 0; font-size: 1rem; font-weight: 700;"><?php echo esc_html__('Real Site Speed (Multi-Page TTFB)', 'vn-speed-optimizer'); ?></h3>
    3024             <span class="vnspo-state-pill <?php echo $cache_layer['active'] ? 'is-on' : 'is-off'; ?>" style="margin-left: auto; margin-right: 10px;">
    3025                 <?php echo esc_html($cache_layer['label']); ?>
    3026             </span>
    3027             <button type="button" class="vnspo-btn-primary" id="btn-measure-ttfb" style="padding: 6px 14px; font-size: 0.8125rem;">
    3028                 <?php echo esc_html__('Measure Speed Now', 'vn-speed-optimizer'); ?>
    3029             </button>
    3030         </div>
    3031         <div class="vnspo-card-glass-body">
    3032             <div id="vnspo-ttfb-results" style="display: <?php echo $latest_ttfb ? 'grid' : 'none'; ?>; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px;">
    3033                 <div class="vnspo-metric-card">
    3034                     <div class="vnspo-metric-info">
    3035                         <div class="vnspo-metric-label"><?php echo esc_html__('Origin (Uncached)', 'vn-speed-optimizer'); ?></div>
    3036                         <div class="vnspo-metric-value" id="vnspo-ttfb-origin" style="color: var(--vnspo-danger);"><?php echo $latest_ttfb ? esc_html((int) $latest_ttfb['origin_ms'] . ' ms') : '—'; ?></div>
    3037                     </div>
    3038                 </div>
    3039                 <div class="vnspo-metric-card">
    3040                     <div class="vnspo-metric-info">
    3041                         <div class="vnspo-metric-label"><?php echo esc_html__('Cached (Warm Hit)', 'vn-speed-optimizer'); ?></div>
    3042                         <div class="vnspo-metric-value" id="vnspo-ttfb-cached" style="color: var(--vnspo-primary);"><?php echo $latest_ttfb ? esc_html((int) $latest_ttfb['cached_ms'] . ' ms') : '—'; ?></div>
    3043                     </div>
    3044                 </div>
    3045                 <div class="vnspo-metric-card">
    3046                     <div class="vnspo-metric-info">
    3047                         <div class="vnspo-metric-label"><?php echo esc_html__('Speed Improvement', 'vn-speed-optimizer'); ?></div>
    3048                         <div class="vnspo-metric-value" id="vnspo-ttfb-gain" style="color: var(--vnspo-primary);"><?php echo $latest_ttfb ? esc_html((int) $latest_ttfb['improvement_pct'] . '%') : '—'; ?></div>
    3049                         <div style="font-size: 0.72rem; color: var(--vnspo-text-muted); margin-top: 2px;">
    3050                             <?php echo esc_html__('Direct test: uncached Origin vs Page Cache', 'vn-speed-optimizer'); ?>
    3051                         </div>
    3052                     </div>
    3053                 </div>
    3054             </div>
    3055             <div id="vnspo-ttfb-details" style="margin-top: 12px; font-size: 0.8125rem; color: var(--vnspo-text-muted); <?php echo $latest_ttfb ? '' : 'display:none;'; ?>">
    3056                 <?php if ($baseline) : ?>
    3057                     <div id="vnspo-ttfb-baseline" style="margin-bottom: 6px;">
    3058                         <strong><?php echo esc_html__('Initial Baseline:', 'vn-speed-optimizer'); ?></strong>
    3059                         <?php
    3060                         /* translators: 1: origin TTFB in ms, 2: cached TTFB in ms */
    3061                         echo esc_html(sprintf(__('Origin %1$d ms / Cached %2$d ms', 'vn-speed-optimizer'), (int) $baseline['origin_ms'], (int) $baseline['cached_ms']));
    3062                         ?>
    3063                     </div>
    3064                 <?php endif; ?>
    3065                 <div id="vnspo-ttfb-pages">
    3066                     <?php if ($latest_ttfb && !empty($latest_ttfb['pages']) && is_array($latest_ttfb['pages'])) : ?>
    3067                         <?php foreach ($latest_ttfb['pages'] as $pg) :
    3068                             $pg_label = $this->getBenchmarkPageLabel($pg);
    3069                             if (empty($pg['key'])) {
    3070                                 $legacy_map = array(
    3071                                     'Trang chủ'         => __('Homepage', 'vn-speed-optimizer'),
    3072                                     'Bài viết mới nhất' => __('Latest Post', 'vn-speed-optimizer'),
    3073                                     'Cửa hàng'          => __('Shop', 'vn-speed-optimizer'),
    3074                                     'Chuyên mục'        => __('Category', 'vn-speed-optimizer'),
    3075                                 );
    3076                                 if (isset($legacy_map[$pg_label])) {
    3077                                     $pg_label = $legacy_map[$pg_label];
    3078                                 }
    3079                             }
    3080                         ?>
    3081                             <span style="display: inline-block; margin-right: 12px;">
    3082                                 <strong><?php echo esc_html($pg_label); ?>:</strong>
    3083                                 <?php echo esc_html((int) $pg['origin_ms'] . 'ms → ' . (int) $pg['cached_ms'] . 'ms (' . (int) $pg['improvement_pct'] . '%)'); ?>
    3084                             </span>
    3085                         <?php endforeach; ?>
    3086                     <?php endif; ?>
    3087                 </div>
    3088                 <div id="vnspo-ttfb-tips" style="margin-top: 6px; color: var(--vnspo-primary);">
    3089                     <?php if ($latest_ttfb && !empty($latest_ttfb['tip_keys']) && is_array($latest_ttfb['tip_keys'])) : ?>
    3090                         <?php echo esc_html($this->getSpeedTipText($latest_ttfb['tip_keys'][0])); ?>
    3091                     <?php elseif ($latest_ttfb && !empty($latest_ttfb['recommendations']) && is_array($latest_ttfb['recommendations'])) : ?>
    3092                         <?php
    3093                         $tip_raw = (string) $latest_ttfb['recommendations'][0];
    3094                         if (false !== strpos($tip_raw, 'Cấu hình hiện tại')) {
    3095                             $tip_raw = $this->getSpeedTipText('healthy');
    3096                         }
    3097                         echo esc_html($tip_raw);
    3098                         ?>
    3099                     <?php endif; ?>
    3100                 </div>
    3101             </div>
    3102             <?php if (!$latest_ttfb) : ?>
    3103                 <p id="vnspo-ttfb-empty" style="text-align: center; color: var(--vnspo-text-muted); font-size: 0.875rem; margin: 6px 0;">
    3104                     <?php echo esc_html__('No real measurement recorded yet. Click "Measure Speed Now" to compare uncached Origin vs cached response time across your pages.', 'vn-speed-optimizer'); ?>
    3105                 </p>
    3106             <?php endif; ?>
    3107         </div>
    3108     </div>
    3109 
    3110     <?php
    3111     $local_cache = $this->getLocalCacheStats();
    3112     $cached_html_bytes = $local_cache['bytes'];
    3113     $cache_pages_count = $local_cache['count'];
    3114     if ($cache_pages_count > 0) {
    3115         /* translators: Dynamic value placeholder. */
    3116         $cache_file_status = sprintf(__('%d static HTML files on disk', 'vn-speed-optimizer'), $cache_pages_count);
    3117     } elseif (!empty($options['page_cache'])) {
    3118         $cache_file_status = __('Enabled — no cached HTML files yet', 'vn-speed-optimizer');
    3119     } else {
    3120         $cache_file_status = __('Off', 'vn-speed-optimizer');
    3121     }
    3122 
    3123     $db_size = $this->getDatabaseSizeMb();
    3124     $db_cleaned_mb = (float) \get_option('vnspo_db_cleaned_mb', 0);
    3125 
    3126     $rum_lcp_ms = (int) \get_option('vnspo_rum_lcp_ms', 0);
    3127     $security_headers_active = !empty($options['security_headers_enabled']);
    3128     $woo_active = \class_exists('WooCommerce');
    3129 
    3130     $community_on = (bool) \get_option('vnspeed_edge_metrics_consent', false)
    3131         || (bool) \get_option('vnspeed_edge_asset_consent', false);
    3132     $mesh_status = $community_on ? $this->getCommunityMeshStatus() : array('online_nodes' => 0, 'mesh_available' => false);
    3133     $active_plugins = (array) \get_option('active_plugins', array());
    3134     $pro_active = in_array('vn-speed-optimizer-pro/vn-speed-optimizer-pro.php', $active_plugins, true);
    3135     ?>
    3136 
    3137     <!-- 4 CORE VALUE PILLARS (REAL DATA ONLY) -->
    3138     <div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; margin-bottom: 24px;">
    3139         <!-- 1. Speed Before & After -->
    3140         <div class="vnspo-card-glass">
    3141             <div class="vnspo-card-glass-header">
    3142                 <h3 style="margin: 0; font-size: 0.95rem; font-weight: 700;"><?php echo esc_html__('1. Before vs After Speed', 'vn-speed-optimizer'); ?></h3>
    3143             </div>
    3144             <div class="vnspo-card-glass-body" style="font-size: 0.875rem; line-height: 1.7;">
    3145                 <div><strong><?php echo esc_html__('TTFB:', 'vn-speed-optimizer'); ?></strong>
    3146                     <?php echo $latest_ttfb
    3147                         ? esc_html((int) $latest_ttfb['origin_ms'] . ' ms → ' . (int) $latest_ttfb['cached_ms'] . ' ms (-' . (int) $latest_ttfb['improvement_pct'] . '%)')
    3148                         : esc_html__('Click "Measure Speed Now" above', 'vn-speed-optimizer'); ?>
    3149                 </div>
    3150                 <div><strong><?php echo esc_html__('LCP (Real User / CWV):', 'vn-speed-optimizer'); ?></strong>
    3151                     <?php echo $rum_lcp_ms > 0 ? esc_html($rum_lcp_ms . ' ms') : esc_html__('Waiting for local RUM sample', 'vn-speed-optimizer'); ?>
    3152                 </div>
    3153                 <div><strong><?php echo esc_html__('HTML Cache Files:', 'vn-speed-optimizer'); ?></strong> <?php echo esc_html($cache_file_status); ?></div>
    3154             </div>
    3155         </div>
    3156 
    3157         <!-- 2. Hosting Resources Saved -->
    3158         <div class="vnspo-card-glass">
    3159             <div class="vnspo-card-glass-header">
    3160                 <h3 style="margin: 0; font-size: 0.95rem; font-weight: 700;"><?php echo esc_html__('2. Hosting Resources Saved', 'vn-speed-optimizer'); ?></h3>
    3161             </div>
    3162             <div class="vnspo-card-glass-body" style="font-size: 0.875rem; line-height: 1.7;">
    3163                 <div><strong><?php echo esc_html__('Cached Pages on Disk:', 'vn-speed-optimizer'); ?></strong> <?php echo esc_html(\number_format_i18n($cache_pages_count)); ?></div>
    3164                 <div><strong><?php echo esc_html__('Cached Disk Size:', 'vn-speed-optimizer'); ?></strong> <?php echo esc_html($this->formatBytesShort($cached_html_bytes)); ?></div>
    3165                 <div><strong><?php /* translators: Dynamic value placeholder. */ echo esc_html__('Database Size:', 'vn-speed-optimizer'); ?></strong> <?php echo esc_html($db_size . ' MB' . ($db_cleaned_mb > 0 ? ' (' . sprintf(__('Cleaned %s MB', 'vn-speed-optimizer'), $db_cleaned_mb) . ')' : '')); ?></div>
    3166             </div>
    3167         </div>
    3168 
    3169         <!-- 3. Safety & Automation Shield -->
    3170         <div class="vnspo-card-glass">
    3171             <div class="vnspo-card-glass-header">
    3172                 <h3 style="margin: 0; font-size: 0.95rem; font-weight: 700;"><?php echo esc_html__('3. Security & Compatibility', 'vn-speed-optimizer'); ?></h3>
    3173             </div>
    3174             <div class="vnspo-card-glass-body" style="font-size: 0.875rem; line-height: 1.7;">
    3175                 <div><strong><?php echo esc_html__('Security headers:', 'vn-speed-optimizer'); ?></strong>
    3176                     <?php echo $security_headers_active
    3177                         ? esc_html__('Enabled by settings', 'vn-speed-optimizer')
    3178                         : esc_html__('Off', 'vn-speed-optimizer'); ?>
    3179                 </div>
    3180                 <div><strong><?php echo esc_html__('WooCommerce Safe Bypass:', 'vn-speed-optimizer'); ?></strong>
    3181                     <?php echo $woo_active
    3182                         ? esc_html__('Protected (Cart, Checkout, Account)', 'vn-speed-optimizer')
    3183                         : esc_html__('Ready (No-cache rules active)', 'vn-speed-optimizer'); ?>
    3184                 </div>
    3185             </div>
    3186         </div>
    3187 
    3188         <!-- 4. Edge Services / Pro -->
    3189         <div class="vnspo-card-glass">
    3190             <div class="vnspo-card-glass-header">
    3191                 <h3 style="margin: 0; font-size: 0.95rem; font-weight: 700;"><?php echo esc_html__('4. Edge Services & Pro', 'vn-speed-optimizer'); ?></h3>
    3192             </div>
    3193             <div class="vnspo-card-glass-body" style="font-size: 0.875rem; line-height: 1.7;">
    3194                 <div><strong><?php echo esc_html__('Edge service status:', 'vn-speed-optimizer'); ?></strong>
    3195                     <?php if (!$community_on) : ?>
    3196                         <?php echo esc_html__('Off (Opt-in required)', 'vn-speed-optimizer'); ?>
    3197                     <?php elseif (empty($mesh_status['mesh_available'])) : ?>
    3198                         <?php echo esc_html__('Edge metrics unavailable', 'vn-speed-optimizer'); ?>
    3199                     <?php else : ?>
    3200                         <?php /* translators: 1: registered peers count, 2: edge PoP requests count */
    3201                         echo esc_html(sprintf(__('%1$s registered peers • %2$s Edge PoP requests', 'vn-speed-optimizer'), \number_format_i18n((int) $mesh_status['online_nodes']), \number_format_i18n((int) ($mesh_status['edge_pop_requests'] ?? 0)))); ?>
    3202                     <?php endif; ?>
    3203                 </div>
    3204                 <div><strong><?php echo esc_html__('Edge Delivery:', 'vn-speed-optimizer'); ?></strong>
    3205                     <?php echo esc_html__('Not measured', 'vn-speed-optimizer'); ?>
    3206                 </div>
    3207                 <?php if (empty($pro_licensed) && 'active' !== get_option('vnspo_pro_license_status', '')) : ?>
    3208                     <div style="margin-top:6px;padding-top:6px;border-top:1px solid var(--v-border, #e2e8f0);">
    3209                         <strong><?php echo esc_html__('Pro Add-on:', 'vn-speed-optimizer'); ?></strong>
    3210                         <?php if ($pro_active) : ?>
    3211                             <a href="<?php echo esc_url(admin_url('admin.php?page=vn-speed-optimizer&tab=pro')); ?>"><?php echo esc_html__('Installed — Activate License', 'vn-speed-optimizer'); ?></a>
    3212                         <?php else : ?>
    3213                             <a href="<?php echo esc_url('https://vn-nexus.com/vnspo-pro'); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Available (Bulk AVIF, Edge RUCSS, SEO & Ads Booster) →', 'vn-speed-optimizer'); ?></a>
    3214                         <?php endif; ?>
    3215                     </div>
    3216                 <?php endif; ?>
    3217             </div>
    3218         </div>
    3219     </div>
    3220 
    3221     <!-- 1-CLICK MIGRATION / SETTINGS IMPORTER (VISIBLE ON OVERVIEW) -->
    3222     <div style="margin-bottom: 24px;">
    3223         <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping.
    3224         echo $this->renderSettingsImporterCard(); ?>
    3225     </div>
    3226 
    3227     <!-- QUICK ACTIONS + ACTIVITY FEED -->
    3228     <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px;">
    3229         <?php if (!empty($_GET['tab']) && $_GET['tab'] === 'dashboard'): ?>
    3230         <!-- Quick Actions -->
    3231         <div class="vnspo-card-glass">
    3232             <div class="vnspo-card-glass-header">
    3233                 <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--vnspo-primary)" stroke-width="2">
    3234                     <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
    3235                 </svg>
    3236                 <h3 style="margin: 0; font-size: 1rem; font-weight: 700;"><?php echo esc_html__('Quick Actions', 'vn-speed-optimizer'); ?></h3>
    3237             </div>
    3238             <div class="vnspo-card-glass-body">
    3239                 <div class="vnspo-quick-grid">
    3240                     <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping.
    3241         echo $this->getQuickActionBtn(__('Performance', 'vn-speed-optimizer'), 'settings', 'tab=performance'); ?>
    3242                     <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping.
    3243         echo $this->getQuickActionBtn(__('Cache', 'vn-speed-optimizer'), 'database', 'tab=cache'); ?>
    3244                     <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping.
    3245         echo $this->getQuickActionBtn(__('Media', 'vn-speed-optimizer'), 'image', 'tab=media'); ?>
    3246                     <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping.
    3247         echo $this->getQuickActionBtn(__('Security', 'vn-speed-optimizer'), 'shield', 'tab=security'); ?>
    3248                 </div>
    3249             </div>
    3250         </div>
    3251 
    3252         <!-- Activity Feed (Real Events) -->
    3253         <div class="vnspo-card-glass">
    3254             <div class="vnspo-card-glass-header">
    3255                 <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--vnspo-primary)" stroke-width="2">
    3256                     <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
    3257                 </svg>
    3258                 <h3 style="margin: 0; font-size: 1rem; font-weight: 700;"><?php echo esc_html__('Recent Activity', 'vn-speed-optimizer'); ?></h3>
    3259             </div>
    3260             <div class="vnspo-card-glass-body">
    3261                 <div class="vnspo-activity-feed">
    3262                     <?php if (empty($activity_log)) : ?>
    3263                         <p style="color: var(--vnspo-text-muted); font-size: 0.875rem; margin: 0;">
    3264                             <?php echo esc_html__('No real optimization activity recorded yet.', 'vn-speed-optimizer'); ?>
    3265                         </p>
    3266                     <?php else : ?>
    3267                         <?php foreach (array_slice($activity_log, 0, 4) as $item) :
    3268                             $ev_type = isset($item['type']) ? (string) $item['type'] : '';
    3269                             $ev_title = isset($activity_labels[$ev_type]) ? $activity_labels[$ev_type] : $ev_type;
    3270                             if (!empty($item['detail'])) {
    3271                                 $ev_title .= ' (' . $item['detail'] . ')';
    3272                             }
    3273                             $ev_time = !empty($item['time'])
    3274                                 /* translators: Dynamic value placeholder. */
    3275                                 ? sprintf(__('%s ago', 'vn-speed-optimizer'), \human_time_diff((int) $item['time'], time()))
    3276                                 : __('Just now', 'vn-speed-optimizer');
    3277         // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping.
    3278                             echo $this->getActivityItem($ev_title, $ev_time, 'info');
    3279                         endforeach; ?>
    3280                     <?php endif; ?>
    3281                 </div>
    3282             </div>
    3283         </div>
    3284         <?php endif; ?>
    3285     </div>
    3286 
    3287 </div>
    3288 <?php
    3289         return ob_get_clean();
    3290     }
    3291 
    3292     /**
    3293      * Get score grade letter
    3294      */
    3295     private function getScoreGrade($score)
    3296     {
    3297         if ($score >= 90) return 'A';
    3298         if ($score >= 70) return 'B';
    3299         if ($score >= 50) return 'C';
    3300         if ($score >= 30) return 'D';
    3301         return 'F';
    3302     }
    3303 
    3304     /**
    3305      * Get score grade CSS class
    3306      */
    3307     private function getScoreGradeClass($grade)
    3308     {
    3309         return 'vnspo-grade-' . strtolower($grade);
    3310     }
    3311 
    3312     /**
    3313      * Get score ring SVG color
    3314      */
    3315     private function getScoreRingColor($score)
    3316     {
    3317         if ($score >= 70) return '#2563eb'; // Blue
    3318         return '#dc2626'; // Red
    3319     }
    3320 
    3321     /**
    3322      * Generate metric card HTML
    3323      */
    3324     private function getMetricCardHtml($label, $value, $icon, $type = 'primary')
    3325     {
    3326         $icons = array(
    3327             'database' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>',
    3328             'server' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>',
    3329             'shield' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>',
    3330             'eye' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
    3331         );
    3332 
    3333         $iconSvg = isset($icons[$icon]) ? $icons[$icon] : $icons['database'];
    3334 
    3335         return sprintf(
    3336             '<div class="vnspo-metric-card">
    3337                 <div class="vnspo-metric-icon icon-%s">%s</div>
    3338                 <div class="vnspo-metric-info">
    3339                     <div class="vnspo-metric-value">%s</div>
    3340                     <div class="vnspo-metric-label">%s</div>
    3341                 </div>
    3342             </div>',
    3343             esc_attr($type),
    3344             $iconSvg,
    3345             esc_html($value),
    3346             esc_html($label)
    3347         );
    3348     }
    3349 
    3350     /**
    3351      * Generate quick action button HTML
    3352      */
    3353     private function getQuickActionBtn($label, $icon, $tab)
    3354     {
    3355         $icons = array(
    3356             'settings' => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',
    3357             'database' => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>',
    3358             'image' => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',
    3359             'shield' => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>',
    3360         );
    3361 
    3362         $iconSvg = isset($icons[$icon]) ? $icons[$icon] : $icons['settings'];
    3363 
    3364         return sprintf(
    3365             '<a href="%s" class="vnspo-quick-btn">%s<span>%s</span></a>',
    3366             esc_url(admin_url('admin.php?page=vn-speed-optimizer&' . $tab)),
    3367             $iconSvg,
    3368             esc_html($label)
    3369         );
    3370     }
    3371 
    3372     /**
    3373      * Generate activity item HTML
    3374      */
    3375     private function getActivityItem($title, $time, $type = 'info')
    3376     {
    3377         $icons = array(
    3378             'success' => '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',
    3379             'warning' => '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
    3380             'info' => '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
    3381         );
    3382 
    3383         $iconSvg = isset($icons[$type]) ? $icons[$type] : $icons['info'];
    3384 
    3385         return sprintf(
    3386             '<div class="vnspo-activity-item">
    3387                 <div class="vnspo-activity-icon %s">%s</div>
    3388                 <div class="vnspo-activity-content">
    3389                     <div class="vnspo-activity-title">%s</div>
    3390                     <div class="vnspo-activity-time">%s</div>
    3391                 </div>
    3392             </div>',
    3393             esc_attr($type),
    3394             $iconSvg,
    3395             esc_html($title),
    3396             esc_html($time)
    3397         );
    3398     }
    3399 
    3400 
    34012510    /**
    34022511     * AJAX: Manually sync OTA JSON exclusions/policy from VN-Nexus Edge.
    … …  
    34322541            'timeout'   => 4,
    34332542            'sslverify' => true,
    3434             'user-agent' => 'VN-Speed-Optimizer/' . (\defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.0'),
     2543            'user-agent' => 'VN-Speed-Optimizer/' . (\defined('VNSPO_VERSION') ? (string) VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.2')),
    34352544        ));
    34362545
    … …  
    35062615        \update_option('vnspo_rum_lcp_ms', $next, false);
    35072616        \update_option('vnspo_rum_lcp_updated_at', \time(), false);
    3508         \wp_send_json_success(array('lcp_ms' => $next));
     2617        $cwv = SafePreviewRollback::recordCwvSample($lcp_ms);
     2618        \wp_send_json_success(array(
     2619            'lcp_ms'           => $next,
     2620            'auto_rolled_back' => $cwv['auto_rolled_back'],
     2621        ));
     2622    }
     2623
     2624    /**
     2625     * AJAX: Restore latest Safe-Rollback options checkpoint.
     2626     */
     2627    public function ajaxRollbackLatest()
     2628    {
     2629        \check_ajax_referer('vnspo_toggle', 'nonce');
     2630        if (!\current_user_can('manage_options')) {
     2631            \wp_send_json_error(array('message' => 'Unauthorized'), 403);
     2632        }
     2633        $restored = SafePreviewRollback::rollbackLatest();
     2634        if (null === $restored) {
     2635            \wp_send_json_error(array('message' => 'No rollback checkpoint available'), 404);
     2636        }
     2637        \wp_send_json_success(array('restored' => true, 'trigger' => $restored['trigger'] ?? 'manual'));
     2638    }
     2639
     2640    /**
     2641     * AJAX: Return weekly Core Web Vitals trend report from recorded RUM samples.
     2642     */
     2643    public function ajaxCwvReport()
     2644    {
     2645        \check_ajax_referer('vnspo_toggle', 'nonce');
     2646        if (!\current_user_can('manage_options')) {
     2647            \wp_send_json_error(array('message' => 'Unauthorized'), 403);
     2648        }
     2649        \wp_send_json_success(SafePreviewRollback::getWeeklyCwvReport());
     2650    }
     2651
     2652    /**
     2653     * AJAX: Generate an admin-only Safe-Preview URL for testing JS/CSS optimization.
     2654     */
     2655    public function ajaxPreviewUrl()
     2656    {
     2657        \check_ajax_referer('vnspo_toggle', 'nonce');
     2658        if (!\current_user_can('manage_options')) {
     2659            \wp_send_json_error(array('message' => 'Unauthorized'), 403);
     2660        }
     2661        $target = isset($_POST['url']) && is_scalar($_POST['url']) ? \esc_url_raw((string) \wp_unslash($_POST['url'])) : '';
     2662        \wp_send_json_success(array('preview_url' => SafePreviewRollback::buildPreviewUrl($target)));
     2663    }
     2664
     2665    /**
     2666     * Define 4 curated local speed presets for 1-click setup.
     2667     *
     2668     * @return array<string, array<string, mixed>>
     2669     */
     2670    private function getSpeedPresets(): array
     2671    {
     2672        $safe_options = array(
     2673            'page_cache'                 => 1,
     2674            'browser_cache'              => 1,
     2675            'htaccess_gzip'              => 1,
     2676            'htaccess_expires'           => 1,
     2677            'htaccess_etag'              => 1,
     2678            'font_display_swap'          => 1,
     2679            'lazy_load'                  => 1,
     2680            'lazy_iframes'               => 1,
     2681            'disable_emojis'             => 1,
     2682            'disable_embeds'             => 1,
     2683            'smart_cleanup_head'         => 1,
     2684            'fix_img_dimensions'         => 1,
     2685            'defer_js'                   => 0,
     2686            'interaction_delay_v2'       => 0,
     2687            'enable_interaction_delay'   => 0,
     2688            'async_css'                  => 0,
     2689            'minify_html'                => 0,
     2690            'speculation_rules'          => 0,
     2691            'instant_touch'              => 0,
     2692        );
     2693
     2694        $balanced_options = array_merge($safe_options, array(
     2695            'minify_html'              => 1,
     2696            'youtube_lazy'             => 1,
     2697            'disable_dashicons'        => 1,
     2698            'disable_jquery_migrate'   => 1,
     2699            'defer_js'                 => 1,
     2700            'interaction_delay_v2'     => 1,
     2701            'fast_llms_txt'            => 1,
     2702            'fix_touch_targets'        => 1,
     2703            'fix_empty_links'          => 1,
     2704            'security_headers_enabled' => 1,
     2705            'smart_security_headers'   => 1,
     2706            'lazy_render'              => 1,
     2707            'dns_prefetch'             => 1,
     2708            'preconnect'               => 1,
     2709        ));
     2710
     2711        $aggressive_options = array_merge($balanced_options, array(
     2712            'async_css'                              => 1,
     2713            'speculation_rules'                      => 1,
     2714            'instant_touch'                          => 1,
     2715            'browser_cache_aggressive'               => 1,
     2716            'browser_cache_stale_while_revalidate'   => 1,
     2717            'lazy_vpi'                               => 1,
     2718            'smart_fonts'                            => 1,
     2719        ));
     2720
     2721        $woocommerce_options = array_merge($balanced_options, array(
     2722            'woo_optimize'      => 1,
     2723            'speculation_rules' => 0,
     2724            'async_css'         => 0,
     2725            'heartbeat_control' => 'limit',
     2726        ));
     2727
     2728        return array(
     2729            'safe' => array(
     2730                'label'   => __('Safe', 'vn-speed-optimizer'),
     2731                'badge'   => '',
     2732                'desc'    => __('Zero-risk caching, browser cache, font-display & safe cleanup (no JS/CSS rewriting).', 'vn-speed-optimizer'),
     2733                'options' => $safe_options,
     2734            ),
     2735            'balanced' => array(
     2736                'label'   => __('Balanced', 'vn-speed-optimizer'),
     2737                'badge'   => __('Recommended', 'vn-speed-optimizer'),
     2738                'desc'    => __('Best speed-to-stability ratio: Page Cache, Delay JS with Auto-Heal, HTML minify & security headers.', 'vn-speed-optimizer'),
     2739                'options' => $balanced_options,
     2740            ),
     2741            'aggressive' => array(
     2742                'label'   => __('Aggressive', 'vn-speed-optimizer'),
     2743                'badge'   => '',
     2744                'desc'    => __('Maximum Core Web Vitals: Async CSS, Speculation Rules, Instant Touch, Smart Local Fonts & VPI.', 'vn-speed-optimizer'),
     2745                'options' => $aggressive_options,
     2746            ),
     2747            'woocommerce' => array(
     2748                'label'   => __('WooCommerce', 'vn-speed-optimizer'),
     2749                'badge'   => '',
     2750                'desc'    => __('Store-safe speed: unloads shop bloat on non-store pages, limits Heartbeat, protects checkout & cart scripts.', 'vn-speed-optimizer'),
     2751                'options' => $woocommerce_options,
     2752            ),
     2753        );
     2754    }
     2755
     2756    /**
     2757     * AJAX: Apply one of the curated 1-click speed presets after saving a rollback checkpoint.
     2758     */
     2759    public function ajaxApplyPreset()
     2760    {
     2761        \check_ajax_referer('vnspo_toggle', 'nonce');
     2762        if (!\current_user_can('manage_options')) {
     2763            \wp_send_json_error(array('message' => 'Unauthorized'), 403);
     2764        }
     2765
     2766        $preset_id = isset($_POST['preset']) ? \sanitize_key(\wp_unslash($_POST['preset'])) : '';
     2767        $presets   = $this->getSpeedPresets();
     2768        if (!isset($presets[$preset_id])) {
     2769            \wp_send_json_error(array('message' => 'Unknown preset'), 400);
     2770        }
     2771
     2772        $options = \get_option('vnspo_options', array());
     2773        if (!is_array($options)) {
     2774            $options = array();
     2775        }
     2776
     2777        SafePreviewRollback::saveCheckpoint($options, 'preset_' . $preset_id);
     2778
     2779        $preserve = array(
     2780            'object_cache_enabled',
     2781            'vnspeed_edge_metrics_consent',
     2782            'vnspeed_edge_asset_consent',
     2783            'community_acceleration',
     2784            'community_cdn',
     2785        );
     2786        $preserved = array();
     2787        foreach ($preserve as $pk) {
     2788            if (array_key_exists($pk, $options)) {
     2789                $preserved[$pk] = $options[$pk];
     2790            }
     2791        }
     2792
     2793        foreach ($presets[$preset_id]['options'] as $key => $val) {
     2794            $options[$key] = $val;
     2795        }
     2796        foreach ($preserved as $pk => $pv) {
     2797            $options[$pk] = $pv;
     2798        }
     2799        $options['active_preset'] = $preset_id;
     2800
     2801        \update_option('vnspo_options', $options);
     2802        \do_action('vnspo_flush_cache');
     2803        if (function_exists('wp_cache_flush')) {
     2804            \wp_cache_flush();
     2805        }
     2806
     2807        $this->recordActivity('preset_applied', $preset_id);
     2808
     2809        \wp_send_json_success(array(
     2810            'preset' => $preset_id,
     2811            'label'  => $presets[$preset_id]['label'],
     2812            'score'  => $this->calculateScore($options),
     2813        ));
     2814    }
     2815
     2816    /**
     2817     * AJAX: Switch between Simple and Advanced admin interface modes.
     2818     */
     2819    public function ajaxToggleUiMode()
     2820    {
     2821        \check_ajax_referer('vnspo_toggle', 'nonce');
     2822        if (!\current_user_can('manage_options')) {
     2823            \wp_send_json_error(array('message' => 'Unauthorized'), 403);
     2824        }
     2825
     2826        $raw  = isset($_POST['mode']) ? \sanitize_key(\wp_unslash($_POST['mode'])) : 'simple';
     2827        $mode = 'advanced' === $raw ? 'advanced' : 'simple';
     2828        \update_option('vnspo_ui_mode', $mode, false);
     2829
     2830        \wp_send_json_success(array('ui_mode' => $mode));
     2831    }
     2832
     2833    /**
     2834     * AJAX: Clear scripts automatically excluded by AutoHealService.
     2835     */
     2836    public function ajaxClearAutoHealExclusions()
     2837    {
     2838        \check_ajax_referer('vnspo_toggle', 'nonce');
     2839        if (!\current_user_can('manage_options')) {
     2840            \wp_send_json_error(array('message' => 'Unauthorized'), 403);
     2841        }
     2842
     2843        \delete_option('vnspo_auto_heal_exclusions');
     2844        \do_action('vnspo_flush_cache');
     2845
     2846        \wp_send_json_success(array('cleared' => true));
     2847    }
     2848
     2849    /**
     2850     * AJAX: Clear learned RUM Auto-Priority LCP/ATF elements.
     2851     */
     2852    public function ajaxResetPriorityElements()
     2853    {
     2854        \check_ajax_referer('vnspo_toggle', 'nonce');
     2855        if (!\current_user_can('manage_options')) {
     2856            \wp_send_json_error(array('message' => 'Unauthorized'), 403);
     2857        }
     2858
     2859        \delete_option('vnspo_priority_elements');
     2860        \do_action('vnspo_flush_cache');
     2861
     2862        \wp_send_json_success(array('cleared' => true));
    35092863    }
    35102864}
  • vn-speed-optimizer/trunk/src/Services/Admin/CloudflarePairingController.php

    r3810859 r3847091  
    131131        $metricsConsent = $this->client->getMetricsConsent();
    132132        $assetConsent = $this->client->getAssetSharingConsent();
    133         $baseUrl = \defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '';
     133        $baseUrl = \defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (\defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     134        $version = \defined('VNSPO_VERSION') ? VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
    134135
    135136        if (\function_exists('wp_enqueue_script') && '' !== $baseUrl) {
    136             \wp_enqueue_script('vnspeed-edge-pairing', $baseUrl . 'assets/js/edge-pairing.js', [], \defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.0', true);
     137            \wp_enqueue_script('vnspeed-edge-pairing', $baseUrl . 'assets/js/edge-pairing.js', [], $version, true);
    137138        }
    138139
  • vn-speed-optimizer/trunk/src/Services/Admin/PublicAssetSharing.php

    r3810859 r3847091  
    5151        if ('vn-speed-optimizer_page_vnspo-public-assets' !== $hook) return;
    5252        \wp_enqueue_media();
    53         $version = \defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.0.0';
    54         $baseUrl = \defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '';
     53        $version = \defined('VNSPO_VERSION') ? VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
     54        $baseUrl = \defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (\defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
    5555        \wp_enqueue_script(
    5656            'vnspo-public-assets',
  • vn-speed-optimizer/trunk/src/Services/Admin/SetupWizard.php

    r3810859 r3847091  
    3939                'heartbeat_control' => 'limit',
    4040            ],
    41             'expected_lcp' => '-15%',
    42             'expected_tti' => '-10%',
     41            'expected_lcp' => 'Measure live',
     42            'expected_tti' => 'Safe scope',
    4343        ],
    4444        'balanced' => [
    … …  
    5656                'auto_meta_desc' => 1,
    5757            ],
    58             'expected_lcp' => '-40%',
    59             'expected_tti' => '-35%',
     58            'expected_lcp' => 'Measure live',
     59            'expected_tti' => 'Balanced scope',
    6060        ],
    6161        'aggressive' => [
    … …  
    7777                'preload_lcp' => 1,
    7878            ],
    79             'expected_lcp' => '-60%',
    80             'expected_tti' => '-50%',
     79            'expected_lcp' => 'Measure live',
     80            'expected_tti' => 'Full scope',
    8181        ],
    8282    ];
    … …  
    122122        // Output a standalone HTML page with all required assets inline.
    123123        // We cannot use wp_enqueue_* here because wp_head() has not fired.
    124         $css_url  = VNSPEED_PLUGIN_URL . 'assets/css/wizard.css';
    125         $nonce    = \wp_create_nonce( 'vnspo_wizard_nonce' );
    126         $ajax_url = \admin_url( 'admin-ajax.php' );
    127         $version  = VNSPEED_VERSION;
     124        $plugin_url = \defined( 'VNSPO_PLUGIN_URL' ) ? VNSPO_PLUGIN_URL : ( \defined( 'VNSPEED_PLUGIN_URL' ) ? VNSPEED_PLUGIN_URL : '' );
     125        $css_url    = $plugin_url . 'assets/css/wizard.css';
     126        $nonce      = \wp_create_nonce( 'vnspo_wizard_nonce' );
     127        $ajax_url   = \admin_url( 'admin-ajax.php' );
     128        $version    = \defined( 'VNSPO_VERSION' ) ? VNSPO_VERSION : ( \defined( 'VNSPEED_VERSION' ) ? VNSPEED_VERSION : '1.2.2' );
    128129        $wizard_data = [
    129130            'ajaxUrl' => $ajax_url,
    … …  
    329330                        <div class="vnspo-preset" data-preset="<?php echo esc_attr($key); ?>">
    330331                            <div class="vnspo-preset-header">
    331                                 <h3><?php /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ echo $preset['label']; ?></h3>
     332                                <h3><?php echo esc_html($preset['label']); ?></h3>
    332333                                <p><?php echo esc_html($preset['desc']); ?></p>
    333334                            </div>
    … …  
    420421                        </div>
    421422                        <div class="vnspo-cloud-actions">
    422                             <a class="vnspo-btn vnspo-btn-red" href="<?php echo esc_url('https://vn-nexus.com/vnspo-pro/?plan=pro'); ?>" target="_blank" rel="noopener noreferrer" style="text-decoration:none;text-align:center;">
     423                            <a class="vnspo-btn vnspo-btn-red" href="<?php echo esc_url('https://vn-nexus.com/vnspo-pro?src=wp-free-wizard&plan=pro'); ?>" target="_blank" rel="noopener noreferrer" style="text-decoration:none;text-align:center;">
    423424                                <?php echo esc_html__('Explore Pro Early Access', 'vn-speed-optimizer'); ?>
    424425                            </a>
    … …  
    450451                        </div>
    451452                        <div class="vnspo-success-stat">
    452                             <span class="number" id="expected-lcp">-40%</span>
    453                             <span class="label">Expected LCP improvement</span>
     453                            <span class="number" id="expected-lcp">&mdash;</span>
     454                            <span class="label"><?php echo esc_html__('Run real Speed Proof on Dashboard', 'vn-speed-optimizer'); ?></span>
    454455                        </div>
    455456                    </div>
    456457
    457458                    <div class="vnspo-success-actions">
    458                         <a href="<?php /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ echo admin_url('admin.php?page=vn-speed-optimizer'); ?>" class="vnspo-btn vnspo-btn-primary vnspo-btn-large">
     459                        <a href="<?php echo esc_url(admin_url('admin.php?page=vn-speed-optimizer')); ?>" class="vnspo-btn vnspo-btn-primary vnspo-btn-large">
    459460                            📊 View Dashboard
    460461                        </a>
  • vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/BaseComponent.php

    r3810859 r3847091  
    11<?php /** * Base Component Class * * Abstract base class for all UI components in VN Speed Optimizer admin interface. * Provides common functionality for rendering, option handling, and escaping. * * @package VNSPO\Services\Admin\Views\Components * @since 1.1.0 */
    22 namespace VNSPO\Services\Admin\Views\Components;
     3 if ( ! defined( 'ABSPATH' ) ) { exit; }
    34 abstract class BaseComponent {
    45 /** * Plugin options array * * @var array */
  • vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/Input.php

    r3810859 r3847091  
    11<?php /** * Input Component * * Renders a text input field with label and description. * * @package VNSPO\Services\Admin\Views\Components * @since 1.1.0 */
    22 namespace VNSPO\Services\Admin\Views\Components;
     3 if ( ! defined( 'ABSPATH' ) ) { exit; }
    34 class Input extends BaseComponent {
    45 /** * Component configuration * * @var array */
  • vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/Textarea.php

    r3810859 r3847091  
    11<?php /** * Textarea Component * * Renders a textarea input with label and description. * * @package VNSPO\Services\Admin\Views\Components * @since 1.1.0 */
    22 namespace VNSPO\Services\Admin\Views\Components;
     3 if ( ! defined( 'ABSPATH' ) ) { exit; }
    34 class Textarea extends BaseComponent {
    45 /** * Component configuration * * @var array */
  • vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/Toggle.php

    r3810859 r3847091  
    11<?php /** * Toggle Component * * Renders a checkbox toggle with label and description. * * @package VNSPO\Services\Admin\Views\Components * @since 1.1.0 */
    22 namespace VNSPO\Services\Admin\Views\Components;
     3 if ( ! defined( 'ABSPATH' ) ) { exit; }
    34 class Toggle extends BaseComponent {
    45 /** * Component configuration * * @var array */
  • vn-speed-optimizer/trunk/src/Services/Analytics/PerformanceMonitor.php

    r3810859 r3847091  
    296296
    297297    /**
     298     * Sanitize a relative request path submitted via RUM beacon (zero query/PII/traversal).
     299     */
     300    public static function sanitizeRumPath(string $raw_path): string {
     301        $path = trim((string) preg_split('/[?#]/', $raw_path, 2)[0]);
     302        if ('' === $path || '/' !== $path[0]) {
     303            return '';
     304        }
     305        if (strlen($path) > 200 || preg_match('/[\x00-\x20\x7f\\\\]/', $path) || false !== strpos($path, '..')) {
     306            return '';
     307        }
     308
     309        $lower = strtolower($path);
     310        foreach (['/wp-admin', '/wp-login', '/wp-register', '/wp-json', '/wc-api', '/cart', '/checkout', '/my-account', '/gio-hang', '/thanh-toan', '/tai-khoan'] as $blocked) {
     311            if (0 === strpos($lower, $blocked)) {
     312                return '';
     313            }
     314        }
     315
     316        return '/' === $path ? '/' : rtrim($path, '/') . '/';
     317    }
     318
     319    /**
    298320     * Record real browser CWV beacon into local performance history.
    299321     */
    … …  
    343365        }
    344366
     367        $safe_path = isset($params['path']) && is_string($params['path'])
     368            ? self::sanitizeRumPath($params['path'])
     369            : '';
     370        if ('' !== $safe_path) {
     371            $hot = get_option('vnspo_rum_hot_paths', []);
     372            if (!is_array($hot)) {
     373                $hot = [];
     374            }
     375            $prev      = isset($hot[$safe_path]) && is_array($hot[$safe_path]) ? $hot[$safe_path] : [];
     376            $prev_hits = (int) ($prev['hits'] ?? 0);
     377            $new_hits  = $prev_hits + 1;
     378            $prev_ttfb = (float) ($prev['avg_ttfb'] ?? 0);
     379            $prev_lcp  = (float) ($prev['avg_lcp'] ?? 0);
     380            $hot[$safe_path] = [
     381                'hits'      => $new_hits,
     382                'avg_ttfb'  => (int) round((($prev_ttfb * $prev_hits) + $sample['ttfb']) / $new_hits),
     383                'avg_lcp'   => (int) round((($prev_lcp * $prev_hits) + $sample['lcp']) / $new_hits),
     384                'last_seen' => time(),
     385            ];
     386            uasort($hot, static function ($a, $b) {
     387                $hd = ((int) ($b['hits'] ?? 0)) <=> ((int) ($a['hits'] ?? 0));
     388                return 0 !== $hd ? $hd : (((int) ($b['avg_ttfb'] ?? 0)) <=> ((int) ($a['avg_ttfb'] ?? 0)));
     389            });
     390            if (count($hot) > 20) {
     391                $hot = array_slice($hot, 0, 20, true);
     392            }
     393            update_option('vnspo_rum_hot_paths', $hot, false);
     394            if (function_exists('do_action')) {
     395                do_action('vnspo_rum_path_recorded', $safe_path, $sample);
     396            }
     397        }
     398
    345399        $history = get_option(self::HISTORY_OPTION, []);
    346400        if (!is_array($history)) {
  • vn-speed-optimizer/trunk/src/Services/Cloud/AggregateMetricsSender.php

    r3810859 r3847091  
    9191        $aggregate = [
    9292            'period_start' => (int) (\floor(\time() / 86400) * 86400),
    93             'plugin_version' => \defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.0',
     93            'plugin_version' => \defined('VNSPO_VERSION') ? (string) VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.2'),
    9494            // This is one smoothed site-level LCP summary, not an individual visit record.
    9595            'lcp_ms' => $lcpMs,
  • vn-speed-optimizer/trunk/src/Services/Cloud/BrainClient.php

    r3810859 r3847091  
    66
    77/**
    8  * Server-to-server client for the private VN-Nexus Qwen recommendation API.
     8 * Server-to-server client for the optional VN-Nexus Edge recommendation API.
    99 * Credentials stay in WordPress options and are never exposed to browser code.
    1010 */
    … …  
    157157        if ('disconnect' === $operation) return ['contract_version' => 1, 'status' => 'disconnected', 'google_grant_revoked' => false];
    158158        if ('drafts' === $operation) {
    159             if ('google_ads' !== ($data['provider'] ?? null) || true !== ($data['review_required'] ?? false) || !\in_array($data['generation_mode'] ?? '', ['qwen', 'rules'], true) || !\is_array($data['drafts'] ?? null)) return new \WP_Error('vnspeed_ads_invalid_response', \__('Edge returned invalid Google Ads review drafts.', 'vn-speed-optimizer'));
     159            if ('google_ads' !== ($data['provider'] ?? null) || true !== ($data['review_required'] ?? false) || !\in_array($data['generation_mode'] ?? '', ['ai', 'edge', 'rules'], true) || !\is_array($data['drafts'] ?? null)) return new \WP_Error('vnspeed_ads_invalid_response', \__('Edge returned invalid Google Ads review drafts.', 'vn-speed-optimizer'));
    160160            $drafts = [];
    161161            foreach (\array_slice($data['drafts'], 0, 5) as $draft) {
    … …  
    581581                'pairing_code' => $pairingCode,
    582582                'site_ref' => $siteRef,
    583                 'plugin_version' => \defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '0.0.0',
     583                'plugin_version' => \defined('VNSPO_VERSION') ? VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '0.0.0'),
    584584            ]),
    585585        ]);
    … …  
    744744
    745745    /**
    746      * Backward-compatible method used by NeuralCore and other existing callers.
     746     * Backward-compatible method used by legacy review callers.
    747747     */
    748748    public function evaluate(array $payload, string $reason = 'background'): array
    … …  
    765765        }
    766766
    767         // NeuralCore treats ai_rules as an informational snapshot and stores it
     767        // Legacy callers treat ai_rules as an informational snapshot and store it
    768768        // for the administrator; it does not apply arbitrary remote settings.
    769769        $policy['ai_rules'] = $policy['recommendations'] ?? [];
    … …  
    779779        }
    780780
    781         // Bridge only recommendations with exact, pre-existing AIAutoPilot-safe values.
     781        // Bridge only recommendations with exact, pre-existing safe local keys.
    782782        $safeFixes = [
    783783            'critical_css' => ['fix' => 'critical_css_enabled', 'value' => true],
    … …  
    803803    private function remotePost(string $url, array $args)
    804804    {
    805         $version = \defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.0';
     805        $version = \defined('VNSPO_VERSION') ? (string) VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.2');
    806806        $args['user-agent'] = 'VN-Speed-Optimizer/' . $version;
    807807        return \wp_remote_post($url, $args);
  • vn-speed-optimizer/trunk/src/Services/Core/BaseService.php

    r3810859 r3847091  
    121121        protected function log($message, $context = array())
    122122        {
    123                 if (! WP_DEBUG || ! WP_DEBUG_LOG) {
     123                if (! defined('WP_DEBUG') || ! WP_DEBUG || ! defined('WP_DEBUG_LOG') || ! WP_DEBUG_LOG) {
    124124                        return;
    125125                }
    … …  
    297297                $real_allowed = \realpath($allowed_dir);
    298298                if (! $real_allowed || ! \is_dir($real_allowed)) {
    299                         // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    300                         \error_log('VNSPO Security: Invalid allowed directory - ' . $allowed_dir);
     299                        $this->log('VNSPO Security: Invalid allowed directory - ' . $allowed_dir);
    301300                        return false;
    302301                }
    … …  
    311310                        // Directory doesn't exist - try to create it
    312311                        if (! \wp_mkdir_p($dir_name)) {
    313                                 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    314                                 \error_log('VNSPO Security: Cannot create directory - ' . $dir_name);
     312                                $this->log('VNSPO Security: Cannot create directory - ' . $dir_name);
    315313                                return false;
    316314                        }
    … …  
    318316                }
    319317
    320                 if (\strpos($real_dir, $real_allowed) !== 0) {
    321                         // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    322                         \error_log('VNSPO Security: Path traversal blocked - ' . $file);
    323                         return false;
    324                 }
    325 
    326                 $real_file = $real_dir . '/' . $base_name;
     318                $allowed_prefix = rtrim($real_allowed, '/\\') . DIRECTORY_SEPARATOR;
     319                if ($real_dir !== $real_allowed && \strpos($real_dir, $allowed_prefix) !== 0) {
     320                        $this->log('VNSPO Security: Path traversal blocked - ' . $file);
     321                        return false;
     322                }
     323
     324                $real_file = $real_dir . DIRECTORY_SEPARATOR . $base_name;
    327325
    328326                // ✅ 3. Check for symlink attacks
    329327                if (\is_link($real_file)) {
    330                         // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    331                         \error_log('VNSPO Security: Symlink detected - ' . $real_file);
     328                        $this->log('VNSPO Security: Symlink detected - ' . $real_file);
    332329                        return false;
    333330                }
    … …  
    340337                $bytes = \file_put_contents($temp, $content, LOCK_EX);
    341338                if ($bytes === false) {
    342                         // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    343                         \error_log('VNSPO Security: Failed to write temp file - ' . $temp);
     339                        $this->log('VNSPO Security: Failed to write temp file - ' . $temp);
    344340                        return false;
    345341                }
    … …  
    354350                        // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
    355351                        \unlink($temp);
    356                         // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    357                         \error_log('VNSPO Security: Failed to rename temp file - ' . $temp);
     352                        $this->log('VNSPO Security: Failed to rename temp file - ' . $temp);
    358353                        return false;
    359354                }
  • vn-speed-optimizer/trunk/src/Services/Database/DatabaseCleanup.php

    r3810859 r3847091  
    1212 * Handles database optimization: revisions, auto-drafts, trashed posts,
    1313 * spam comments, trashed comments, transients, and table optimization.
    14  * Mirrors WP Rocket's Optimization class (inc/Engine/Admin/Database/Optimization.php).
    1514 *
    1615 * @since 1.3.0
  • vn-speed-optimizer/trunk/src/Services/Database/DatabaseCleanupProcess.php

    r3810859 r3847091  
    1212 * Background async processor for database cleanup tasks.
    1313 * Runs each cleanup type as a separate async batch to avoid timeout.
    14  * Mirrors WP Rocket's OptimizationProcess.
    1514 *
    1615 * @since 1.3.0
  • vn-speed-optimizer/trunk/src/Services/Database/ObjectCache.php

    r3810859 r3847091  
    4545
    4646        /**
    47          * Detect a working local Redis Unix socket (AZDIGI/cPanel) or TCP endpoint.
     47         * Detect a working local Redis Unix socket or TCP endpoint.
    4848         *
    4949         * @return array{host:string,port:int}|null
    … …  
    126126                }
    127127
    128                 $base_path = defined('VNSPEED_PATH') ? VNSPEED_PATH : dirname(__DIR__, 3) . '/';
     128                $base_path = defined('VNSPO_PATH') ? VNSPO_PATH : (defined('VNSPEED_PATH') ? VNSPEED_PATH : dirname(__DIR__, 3) . '/');
    129129                $source    = trailingslashit($base_path) . 'src/Templates/object-cache.php';
    130130                $dest      = WP_CONTENT_DIR . '/object-cache.php';
  • vn-speed-optimizer/trunk/src/Services/Edge/AdvancedPerformance.php

    r3810859 r3847091  
    1313
    1414namespace VNSPO\Services\Edge;
     15
     16if ( ! defined( 'ABSPATH' ) ) {
     17        exit;
     18}
    1519
    1620class AdvancedPerformance
    … …  
    334338        // Client Hints (modern browsers)
    335339        if (isset($_SERVER['HTTP_SEC_CH_UA_MOBILE'])) {
    336             return $_SERVER['HTTP_SEC_CH_UA_MOBILE'] === '?1';
     340            $ch_mobile = (string) (function_exists('wp_unslash') ? wp_unslash($_SERVER['HTTP_SEC_CH_UA_MOBILE']) : $_SERVER['HTTP_SEC_CH_UA_MOBILE']);
     341            if (function_exists('sanitize_text_field')) {
     342                $ch_mobile = sanitize_text_field($ch_mobile);
     343            }
     344            return $ch_mobile === '?1';
    337345        }
    338346
    … …  
    342350        }
    343351
    344         $user_agent = $_SERVER['HTTP_USER_AGENT'];
     352        $user_agent = (string) (function_exists('wp_unslash') ? wp_unslash($_SERVER['HTTP_USER_AGENT']) : $_SERVER['HTTP_USER_AGENT']);
     353        if (function_exists('sanitize_text_field')) {
     354            $user_agent = sanitize_text_field($user_agent);
     355        }
    345356        $mobile_regex = '/(android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i';
    346357
  • vn-speed-optimizer/trunk/src/Services/Edge/AjaxHandlers.php

    r3810859 r3847091  
    9898                }
    9999
    100                 $action = sanitize_text_field($_POST['todo'] ?? '');
     100                $raw_action = isset($_POST['db_action']) ? $_POST['db_action'] : '';
     101                $action     = \sanitize_key((string) \wp_unslash($raw_action));
    101102
    102103                // Use injected optimizer or fallback (for now, but we will inject it)
  • vn-speed-optimizer/trunk/src/Services/Media/AvatarAltText.php

    r3456323 r3847091  
    44 * AvatarAltText Service
    55 *
    6  * Auto-generates alt text for avatars when missing
    7  * Inspired by Rank Math Pro Image SEO (class-image-seo-pro.php:270-325)
     6 * Auto-generates alt text for avatars when missing.
    87 *
    98 * @package VNSPO
  • vn-speed-optimizer/trunk/src/Services/Media/ImageDimensionsFixer.php

    r3810859 r3847091  
    633633        private function getAttributePlaceholder()
    634634        {
    635                 return defined('VNSPEED_PLUGIN_URL')
    636                         ? VNSPEED_PLUGIN_URL . 'assets/img/placeholder.svg'
     635                $plugin_url = defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     636                return '' !== $plugin_url
     637                        ? $plugin_url . 'assets/img/placeholder.svg'
    637638                        : '';
    638639        }
  • vn-speed-optimizer/trunk/src/Services/Media/LQIPPlaceholderHelpers.php

    r3810859 r3847091  
    2121        private function getAttributePlaceholder()
    2222        {
    23                 return defined('VNSPEED_PLUGIN_URL')
    24                         ? VNSPEED_PLUGIN_URL . 'assets/img/placeholder.svg'
     23                $plugin_url = defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     24                return '' !== $plugin_url
     25                        ? $plugin_url . 'assets/img/placeholder.svg'
    2526                        : 'data:image/svg+xml;base64,' . base64_encode('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>');
    2627        }
  • vn-speed-optimizer/trunk/src/Services/Media/WebPConverterService.php

    r3810859 r3847091  
    8181                return true;
    8282            } catch (\Exception $e) {
    83                 error_log('[VNSPO] WebP conversion failed: ' . $e->getMessage());
     83                if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     84                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     85                    error_log('[VNSPO] WebP conversion failed: ' . $e->getMessage());
     86                }
    8487            }
    8588        }
    … …  
    100103                return true;
    101104            } catch (\Exception $e) {
    102                 error_log('[VNSPO] AVIF conversion failed: ' . $e->getMessage());
     105                if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     106                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     107                    error_log('[VNSPO] AVIF conversion failed: ' . $e->getMessage());
     108                }
    103109            }
    104110        }
  • vn-speed-optimizer/trunk/src/Services/Media/YouTubeLazyLoad.php

    r3810859 r3847091  
    9393
    9494                if (! empty($options['youtube_lazy'])) {
     95                        $plugin_url  = \defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (\defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     96                        $plugin_path = \defined('VNSPO_PATH') ? \VNSPO_PATH : (\defined('VNSPEED_PATH') ? \VNSPEED_PATH : dirname(__DIR__, 3) . '/');
     97                        $version     = \defined('VNSPO_VERSION') ? VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
    9598                        \wp_enqueue_style(
    9699                                'vnspo-youtube-lazy',
    97                                 VNSPEED_PLUGIN_URL . 'assets/css/youtube-lazy.css',
     100                                $plugin_url . 'assets/css/youtube-lazy.css',
    98101                                array(),
    99                                 VNSPEED_VERSION
     102                                $version
    100103                        );
    101104
    102105                        // Inline the JS if not already present from existing youtube-lazy.js
    103                         $script_path = \VNSPEED_PATH . 'assets/js/youtube-lazy.js';
     106                        $script_path = $plugin_path . 'assets/js/youtube-lazy.js';
    104107                        if (file_exists($script_path)) {
    105108                                \wp_enqueue_script(
    106109                                        'vnspo-youtube-lazy',
    107                                         VNSPEED_PLUGIN_URL . 'assets/js/youtube-lazy.js',
     110                                        $plugin_url . 'assets/js/youtube-lazy.js',
    108111                                        array(),
    109                                         VNSPEED_VERSION,
     112                                        $version,
    110113                                        true
    111114                                );
  • vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetCombiner.php

    r3810859 r3847091  
    348348                // Generate cache filename with version hash
    349349                $hash = substr(md5(implode(',', $hashes)), 0, 8);
    350                 $version = VNSPEED_VERSION ?? '1';
     350                $version = defined('VNSPO_VERSION') ? VNSPO_VERSION : (defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1');
    351351                $filename = "{$type}-{$hash}-v{$version}.{$type}";
    352352                $dir = $this->getCacheDir();
  • vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetLocalizer.php

    r3456323 r3847091  
    7878    {
    7979        $parsed = \wp_parse_url($url);
    80         if (!$parsed || !isset($parsed['host'])) {
     80        $scheme = isset($parsed['scheme']) ? strtolower((string) $parsed['scheme']) : '';
     81        if (! $parsed || ! in_array($scheme, array('http', 'https'), true) || empty($parsed['host'])) {
    8182            return false;
    8283        }
    8384
    84         // Block internal/private IP ranges (RFC1918, link-local, loopback)
    85         $ip = gethostbyname($parsed['host']);
    86         if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
    87             error_log('VNSPO Security: Blocked internal IP access attempt - ' . $url);
     85        $host = strtolower(rtrim((string) $parsed['host'], '.'));
     86        if ('' === $host) {
    8887            return false;
    8988        }
    9089
    91         // Whitelist allowed domains
     90        // Strict exact or subdomain match against whitelisted domains before any DNS resolution.
    9291        $allowed_domains = array(
    9392            'googletagmanager.com',
    … …  
    9695        );
    9796
     97        $domain_allowed = false;
    9898        foreach ($allowed_domains as $domain) {
    99             if (strpos($parsed['host'], $domain) !== false) {
    100                 return true;
     99            $suffix = '.' . $domain;
     100            if ($host === $domain || (strlen($host) > strlen($suffix) && substr($host, -strlen($suffix)) === $suffix)) {
     101                $domain_allowed = true;
     102                break;
    101103            }
    102104        }
    103105
    104         error_log('VNSPO Security: Domain not whitelisted - ' . $parsed['host']);
    105         return false;
     106        if (! $domain_allowed) {
     107            if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     108                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     109                error_log('VNSPO Security: Domain not whitelisted - ' . $host);
     110            }
     111            return false;
     112        }
     113
     114        // Block internal/private IP ranges across all resolved IPv4 addresses (RFC1918, link-local, loopback).
     115        $ips = filter_var($host, FILTER_VALIDATE_IP) ? array($host) : @gethostbynamel($host);
     116        if (empty($ips) || ! is_array($ips)) {
     117            if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     118                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     119                error_log('VNSPO Security: Failed to resolve host - ' . $host);
     120            }
     121            return false;
     122        }
     123
     124        foreach ($ips as $ip) {
     125            if (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
     126                if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     127                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     128                    error_log('VNSPO Security: Blocked internal IP access attempt - ' . $url);
     129                }
     130                return false;
     131            }
     132        }
     133
     134        return true;
    106135    }
    107136
  • vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetManager.php

    r3810859 r3847091  
    593593                        }
    594594                        // Both broken — return site_url as-is but flag the issue
    595                         error_log('[VNSPO AssetManager] Warning: site_url/home_url return invalid address. Please update WordPress Site URL settings.');
     595                        if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     596                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     597                                error_log('[VNSPO AssetManager] Warning: site_url/home_url return invalid address. Please update WordPress Site URL settings.');
     598                        }
    596599                }
    597600
  • vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetOptimizer.php

    r3810859 r3847091  
    152152                        if ($critical_css && $this->containsMaliciousContent($critical_css)) {
    153153                                $critical_css = ''; // Discard malicious content
    154                                 error_log('VNSPO Security: Blocked malicious Critical CSS injection');
     154                                if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     155                                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     156                                        error_log('VNSPO Security: Blocked malicious Critical CSS injection');
     157                                }
    155158                        }
    156159                }
    … …  
    171174                }
    172175
    173                 \wp_register_style('vnspo-critical', false);
     176                \wp_register_style('vnspo-critical', false, array(), defined('VNSPO_VERSION') ? VNSPO_VERSION : '1.2.2');
    174177                \wp_enqueue_style('vnspo-critical');
    175178
  • vn-speed-optimizer/trunk/src/Services/Optimization/Assets/DelayJsConfig.php

    r3810859 r3847091  
    1313class DelayJsConfig
    1414{
     15    /**
     16     * Get scripts automatically excluded by AutoHealService circuit breaker.
     17     *
     18     * @return array<int, string>
     19     */
     20    public static function get_auto_heal_exclusions(): array
     21    {
     22        $saved = \get_option('vnspo_auto_heal_exclusions', array());
     23        if (!is_array($saved)) {
     24            return array();
     25        }
     26        $clean = array();
     27        foreach ($saved as $item) {
     28            if (!is_string($item)) {
     29                continue;
     30            }
     31            $pattern = trim(\sanitize_text_field($item), " \t\n\r\0\x0B/");
     32            if ('' !== $pattern) {
     33                $clean[] = $pattern;
     34            }
     35        }
     36        return array_values(array_unique($clean));
     37    }
     38
    1539    public static function get_exclusions()
    1640    {
    … …  
    91115        ];
    92116
     117        $options = \get_option('vnspo_options', array());
     118        if (is_array($options) && !empty($options['delay_js_exclusions'])) {
     119            $manual = is_array($options['delay_js_exclusions'])
     120                ? $options['delay_js_exclusions']
     121                : preg_split('/[\r\n,]+/', (string) $options['delay_js_exclusions']);
     122            if (is_array($manual)) {
     123                foreach ($manual as $pattern) {
     124                    if (is_string($pattern)) {
     125                        $trimmed = trim(\sanitize_text_field($pattern), " \t\n\r\0\x0B/");
     126                        if ('' !== $trimmed) {
     127                            $exclusions[] = $trimmed;
     128                        }
     129                    }
     130                }
     131            }
     132        }
     133
     134        foreach (self::get_auto_heal_exclusions() as $healed) {
     135            $exclusions[] = $healed;
     136        }
     137
    93138        $policy = (new \VNSPO\Services\Cloud\PolicyStore())->getSection('delay_js_exclusions');
    94139        foreach ($policy as $pattern) {
    … …  
    104149    {
    105150        $exclusions = self::get_exclusions();
     151        $handle     = (string) $handle;
     152        $src        = (string) $src;
    106153
    107154        foreach ($exclusions as $pattern) {
    108             $pattern = trim($pattern, '/');
     155            $pattern = trim((string) $pattern, '/');
     156            if ('' === $pattern) {
     157                continue;
     158            }
    109159
    110160            if (stripos($handle, $pattern) !== false || stripos($src, $pattern) !== false) {
  • vn-speed-optimizer/trunk/src/Services/Optimization/Assets/EnhancedLazyLoadScript.php

    r3810859 r3847091  
    273273        private function getAttributePlaceholder()
    274274        {
    275                 return defined('VNSPEED_PLUGIN_URL')
    276                         ? VNSPEED_PLUGIN_URL . 'assets/img/placeholder.svg'
     275                $plugin_url = defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     276                return '' !== $plugin_url
     277                        ? $plugin_url . 'assets/img/placeholder.svg'
    277278                        : $this->getPlaceholder(array());
    278279        }
  • vn-speed-optimizer/trunk/src/Services/Optimization/Assets/InteractionDelay.php

    r3810859 r3847091  
    172172    private function get_loader_script()
    173173    {
     174        $options     = \get_option('vnspo_options', array());
     175        $timeout_sec = max(5, min(120, (int) ($options['delay_js_timeout'] ?? 10)));
     176        $timeout_ms  = $timeout_sec * 1000;
     177
    174178        return "
    175179        <script>
    … …  
    191195            }
    192196            events.forEach(function(e) { window.addEventListener(e, loadScripts, {passive: true, once: true}); });
     197            setTimeout(loadScripts, " . $timeout_ms . ");
    193198        })();
    194199        </script>";
  • vn-speed-optimizer/trunk/src/Services/Optimization/CLSOptimizer.php

    r3810859 r3847091  
    213213     */
    214214    public function handle_cls_report($request) {
     215        $nonce = is_object($request) && method_exists($request, 'get_header')
     216            ? \sanitize_text_field((string) $request->get_header('X-WP-Nonce'))
     217            : '';
     218        if ('' === $nonce || ! \wp_verify_nonce($nonce, 'wp_rest')) {
     219            return new \WP_REST_Response(['success' => false, 'error' => 'invalid_nonce'], 403);
     220        }
     221
    215222        $options = \get_option('vnspo_options', []);
    216223        if (empty($options['rum_enabled'])) {
  • vn-speed-optimizer/trunk/src/Services/Optimization/Cache/ConfigGenerator.php

    r3810859 r3847091  
    127127                // URL no-dots mode (shared hosting)
    128128                if (apply_filters('vnspo_url_no_dots', false)) {
    129                         $buffer .= "define( 'VNSPEED_URL_NO_DOTS', 1 );\n";
     129                        $buffer .= "define( 'VNSPO_URL_NO_DOTS', 1 );\n";
    130130                }
    131131
  • vn-speed-optimizer/trunk/src/Services/Optimization/Cache/DropInManager.php

    r3810859 r3847091  
    9494
    9595                $options = function_exists('get_option') ? (array) \get_option('vnspo_options', array()) : array();
     96                $excludeUris = array(
     97                        '/wp-admin',
     98                        '/wp-login.php',
     99                        '/wp-json',
     100                        '/xmlrpc.php',
     101                        '/wc-api',
     102                        '/cart',
     103                        '/checkout',
     104                        '/my-account',
     105                        '/gio-hang',
     106                        '/thanh-toan',
     107                        '/tai-khoan',
     108                        '/feed',
     109                );
     110                if (! empty($options['cache_exclude_urls']) && is_string($options['cache_exclude_urls'])) {
     111                        foreach (preg_split('/[\r\n,]+/', $options['cache_exclude_urls']) ?: array() as $customLine) {
     112                                $cleanUri = trim(\sanitize_text_field((string) $customLine));
     113                                if ('' !== $cleanUri && '/' !== $cleanUri) {
     114                                        $excludeUris[] = '/' . ltrim($cleanUri, '/');
     115                                }
     116                        }
     117                }
     118
    96119                $config  = array(
    97120                        'cache_dir'    => $cacheDir,
    … …  
    99122                        'cache_mobile' => ! empty($options['cache_mobile']),
    100123                        'cache_webp'   => ! empty($options['cache_webp']),
     124                        'exclude_uris' => array_values(array_unique($excludeUris)),
    101125                );
    102126
  • vn-speed-optimizer/trunk/src/Services/Optimization/Cache/MobileCacheManager.php

    r3810859 r3847091  
    1010 * MobileCacheManager
    1111 *
    12  * Manages separate cache versions for mobile and desktop.
    13  * Mirrors WP Rocket's mobile caching system with enhancements:
     12 * Manages separate cache versions for mobile and desktop:
    1413 * - Separate mobile cache directory
    1514 * - Tablet-aware caching (serve desktop to tablets by default)
  • vn-speed-optimizer/trunk/src/Services/Optimization/Cache/PageCacheCompatibility.php

    r3810859 r3847091  
    6363                }
    6464
    65                 $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? (string) $_SERVER['SERVER_SOFTWARE'] : '';
     65                $raw_server_software = isset($_SERVER['SERVER_SOFTWARE']) ? (string) $_SERVER['SERVER_SOFTWARE'] : '';
     66                if (function_exists('wp_unslash')) {
     67                        $raw_server_software = (string) \wp_unslash($raw_server_software);
     68                }
     69                $server_software = function_exists('sanitize_text_field')
     70                        ? \sanitize_text_field($raw_server_software)
     71                        : $raw_server_software;
    6672                return false !== stripos($server_software, 'litespeed');
    6773        }
  • vn-speed-optimizer/trunk/src/Services/Optimization/Cache/VarnishPurger.php

    r3810859 r3847091  
    1111 *
    1212 * Sends PURGE requests to Varnish cache servers.
    13  * Mirrors WP Rocket's Varnish addon (inc/Addon/Varnish/Varnish.php).
    1413 *
    1514 * Features:
  • vn-speed-optimizer/trunk/src/Services/Optimization/INPOptimizer.php

    r3810859 r3847091  
    133133     */
    134134    public function handle_inp_report($request) {
     135        $nonce = is_object($request) && method_exists($request, 'get_header')
     136            ? \sanitize_text_field((string) $request->get_header('X-WP-Nonce'))
     137            : '';
     138        if ('' === $nonce || ! \wp_verify_nonce($nonce, 'wp_rest')) {
     139            return new \WP_REST_Response(['success' => false, 'error' => 'invalid_nonce'], 403);
     140        }
     141
    135142        $options = \get_option('vnspo_options', []);
    136143        if (empty($options['rum_enabled'])) {
  • vn-speed-optimizer/trunk/src/Services/Optimization/Network/BrowserCache.php

    r3456323 r3847091  
    4949                }
    5050
    51                 // Use WordPress core function to safely inject rules
    52                 // If $rules is empty, it removes the block.
    53                 \insert_with_markers($htaccess_path, 'VN Speed Optimizer - Browser Cache', $rules);
     51                // Use WordPress core function to safely inject rules (load misc.php in REST/CLI contexts).
     52                if (! \function_exists('insert_with_markers') && \defined('ABSPATH')) {
     53                        $misc_file = ABSPATH . 'wp-admin/includes/misc.php';
     54                        if (\file_exists($misc_file)) {
     55                                require_once $misc_file;
     56                        }
     57                }
     58                if (\function_exists('insert_with_markers')) {
     59                        // If $rules is empty, it removes the block.
     60                        \insert_with_markers($htaccess_path, 'VN Speed Optimizer - Browser Cache', $rules);
     61                }
    5462        }
    5563
  • vn-speed-optimizer/trunk/src/Services/Optimization/Network/FastLlmsTxt.php

    r3810859 r3847091  
    4141        }
    4242
    43         $request_uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
     43        $request_uri = isset($_SERVER['REQUEST_URI']) ? \sanitize_text_field(\wp_unslash((string) $_SERVER['REQUEST_URI'])) : '';
    4444        $path = (string) \wp_parse_url($request_uri, PHP_URL_PATH);
    45 
    46         if (0 === strpos($path, '/api/v1/') && class_exists('\VNSPO\Services\Cloud\LocalHubResponder')) {
    47             if (\VNSPO\Services\Cloud\LocalHubResponder::maybeServeHubEndpoint($path)) {
    48                 return;
    49             }
    50         }
    5145
    5246        if ($path === '/robots.txt') {
  • vn-speed-optimizer/trunk/src/Services/Optimization/Network/SmartPrefetch.php

    r3810859 r3847091  
    1010 * Prefetches links likely to be clicked next, reducing perceived latency.
    1111 *
    12  * Mirrors: WP Rocket's/prefetch, LiteSpeed's prefetch,
    13  * SpeedyCache link prefetch, Chrome's Speculation Rules API.
     12 * Supports Speculation Rules API and prefetch fallbacks for browsers.
    1413 *
    1514 * Features:
    … …  
    7776                        \add_action('admin_menu', array($this, 'addAdminMenu'), 100);
    7877                        \add_action('wp_ajax_vnspo_prefetch_stats', array($this, 'ajaxPrefetchStats'));
     78                        \add_action('wp_ajax_nopriv_vnspo_prefetch_stats', array($this, 'ajaxPrefetchStats'));
    7979                        return;
    8080                }
    … …  
    111111                }
    112112
     113                $plugin_url = \defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (\defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     114                $version    = \defined('VNSPO_VERSION') ? VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
    113115                \wp_enqueue_script(
    114116                        'vnspo-smart-prefetch',
    115                         VNSPEED_PLUGIN_URL . 'assets/js/vn-spo-prefetch.js',
     117                        $plugin_url . 'assets/js/vn-spo-prefetch.js',
    116118                        array(),
    117                         VNSPEED_VERSION,
     119                        $version,
    118120                        true
    119121                );
    … …  
    318320        private function supportsSpeculationRules()
    319321        {
    320                 return isset($_SERVER['HTTP_USER_AGENT'])
    321                         && preg_match('/Chrome\/(10[1-9]\.|11[0-9]\.)/', $_SERVER['HTTP_USER_AGENT']);
     322                if (! isset($_SERVER['HTTP_USER_AGENT'])) {
     323                        return false;
     324                }
     325                $ua = (string) (function_exists('wp_unslash') ? \wp_unslash($_SERVER['HTTP_USER_AGENT']) : $_SERVER['HTTP_USER_AGENT']);
     326                if (function_exists('sanitize_text_field')) {
     327                        $ua = \sanitize_text_field($ua);
     328                }
     329                return (bool) (preg_match('/Chrome\/(\d+)\./', $ua, $matches) && (int) $matches[1] >= 109);
    322330        }
    323331
    … …  
    348356                \set_transient($rate_key, $current_rate + 1, MINUTE_IN_SECONDS);
    349357
    350                 $action    = sanitize_text_field($_POST['action_type'] ?? '');
    351                 $url       = esc_url_raw($_POST['url'] ?? '');
     358                $action    = isset($_POST['action_type']) ? \sanitize_text_field((string) \wp_unslash($_POST['action_type'])) : '';
     359                $url       = isset($_POST['url']) ? \esc_url_raw((string) \wp_unslash($_POST['url'])) : '';
    352360                $hit       = isset($_POST['hit']) ? (bool) $_POST['hit'] : false;
    353                 $page_type = sanitize_text_field($_POST['page_type'] ?? '');
     361                $page_type = isset($_POST['page_type']) ? \sanitize_text_field((string) \wp_unslash($_POST['page_type'])) : '';
    354362
    355363                if (empty($url)) {
  • vn-speed-optimizer/trunk/src/Services/Optimization/Network/SpeculationRules.php

    r3810859 r3847091  
    3535         */
    3636        public function inject_speculation_rules() {
    37                 // Only valid for frontend
    38                 if ( \is_admin() || \is_feed() || \defined( 'VNSPO_SPECULATION_INJECTED' ) ) {
     37                // Only valid for anonymous non-checkout frontend requests
     38                if ( \is_admin() || \is_feed() || \is_user_logged_in() || \defined( 'VNSPO_SPECULATION_INJECTED' ) ) {
     39                        return;
     40                }
     41                if ( \function_exists( 'is_cart' ) && ( \is_cart() || \is_checkout() || \is_account_page() ) ) {
    3942                        return;
    4043                }
    4144                \define( 'VNSPO_SPECULATION_INJECTED', true );
    4245
    43                 // JSON Config
    44                 // Prerender: moderate (hover > 200ms or pointer down)
    45                 // Target: Same origin links
    46                 //
    47                 // IMPORTANT: The Speculation Rules API requires at least one of
    48                 // 'prefetch' or 'prerender' rules with a valid 'source' field
    49                 // that the browser can parse. Both are included here for
    50                 // broader browser compatibility (prefetch for Firefox/Safari
    51                 // once supported, prerender for Chrome 108+).
     46                $exclusions = array(
     47                        array( 'href_matches' => '/*' ),
     48                        array( 'not' => array( 'href_matches' => '/wp-admin/*' ) ),
     49                        array( 'not' => array( 'href_matches' => '/wp-login.php' ) ),
     50                        array( 'not' => array( 'href_matches' => '/logout' ) ),
     51                        array( 'not' => array( 'href_matches' => '/cart*' ) ),
     52                        array( 'not' => array( 'href_matches' => '/checkout*' ) ),
     53                        array( 'not' => array( 'href_matches' => '/my-account*' ) ),
     54                        array( 'not' => array( 'href_matches' => '/gio-hang*' ) ),
     55                        array( 'not' => array( 'href_matches' => '/thanh-toan*' ) ),
     56                        array( 'not' => array( 'href_matches' => '/tai-khoan*' ) ),
     57                        array( 'not' => array( 'href_matches' => '/*\\?add-to-cart=*' ) ),
     58                        array( 'not' => array( 'href_matches' => '/*\\?remove_item=*' ) ),
     59                        array( 'not' => array( 'href_matches' => '/*\\?wc-ajax=*' ) ),
     60                        array( 'not' => array( 'selector_matches' => '.no-prerender, [rel~=nofollow]' ) ),
     61                );
     62
    5263                $rules = array(
    5364                        'prefetch' => array(
    5465                                array(
    5566                                        'source'    => 'document',
    56                                         'where'     => array(
    57                                                 'and' => array(
    58                                                         array( 'href_matches' => '/*' ),
    59                                                         array( 'not' => array( 'href_matches' => '/wp-admin/*' ) ),
    60                                                         array( 'not' => array( 'href_matches' => '/wp-login.php' ) ),
    61                                                         array( 'not' => array( 'href_matches' => '/logout' ) ),
    62                                                         array( 'not' => array( 'href_matches' => '/*\\?add-to-cart=*' ) ),
    63                                                 ),
    64                                         ),
     67                                        'where'     => array( 'and' => $exclusions ),
    6568                                        'eagerness' => 'moderate',
    6669                                ),
    … …  
    6972                                array(
    7073                                        'source'    => 'document',
    71                                         'where'     => array(
    72                                                 'and' => array(
    73                                                         array( 'href_matches' => '/*' ),
    74                                                         array( 'not' => array( 'href_matches' => '/wp-admin/*' ) ),
    75                                                         array( 'not' => array( 'href_matches' => '/wp-login.php' ) ),
    76                                                         array( 'not' => array( 'href_matches' => '/logout' ) ),
    77                                                         array( 'not' => array( 'href_matches' => '/*\\?add-to-cart=*' ) ),
    78                                                 ),
    79                                         ),
     74                                        'where'     => array( 'and' => $exclusions ),
    8075                                        'eagerness' => 'moderate',
    8176                                ),
  • vn-speed-optimizer/trunk/src/Services/Optimization/Preload/PreloadQueue.php

    r3810859 r3847091  
    7070         */
    7171        private function ensureQueueTable() {
     72                if (function_exists('get_option') && get_option('vnspo_preload_queue_table_created')) {
     73                        return;
     74                }
     75
    7276                global $wpdb;
    7377
    … …  
    125129                // Option changes that affect sitemap
    126130                add_action('update_option_vnspo_options', [$this, 'onOptionsChange'], 10, 2);
     131
     132                // Auto-prioritize hot/slow RUM paths into PreloadQueue
     133                add_action('vnspo_rum_path_recorded', [$this, 'onRumPathRecorded'], 10, 2);
     134        }
     135
     136        /**
     137         * Compute adaptive batch size based on 1-minute server load average.
     138         */
     139        public static function computeAdaptiveBatchSize($requested_batch, $load_1m = null) {
     140                $batch = max(1, (int) $requested_batch);
     141                if (null === $load_1m && function_exists('sys_getloadavg')) {
     142                        $loads = @sys_getloadavg();
     143                        $load_1m = (is_array($loads) && isset($loads[0])) ? (float) $loads[0] : 0.0;
     144                }
     145                $load = (float) ($load_1m ?? 0.0);
     146                if ($load > 4.0) {
     147                        return 1;
     148                }
     149                if ($load > 2.5) {
     150                        return min(2, $batch);
     151                }
     152                return $batch;
     153        }
     154
     155        /**
     156         * Decide whether the queue should back off after a slow or failed preload request.
     157         */
     158        public static function shouldBackoffAfterRequest($elapsed_sec, $succeeded) {
     159                return ! $succeeded || ((float) $elapsed_sec > 2.5);
     160        }
     161
     162        /**
     163         * Enqueue top recorded RUM hot paths at highest preload priority (1).
     164         */
     165        public function enqueueRumHotPaths($limit = 10) {
     166                $hot = get_option('vnspo_rum_hot_paths', []);
     167                if (!is_array($hot) || empty($hot)) {
     168                        return 0;
     169                }
     170                $paths = array_slice(array_keys($hot), 0, max(1, (int) $limit));
     171                $urls  = [];
     172                foreach ($paths as $path) {
     173                        if (is_string($path) && '' !== $path && '/' === $path[0]) {
     174                                $urls[] = home_url($path);
     175                        }
     176                }
     177                if (empty($urls)) {
     178                        return 0;
     179                }
     180                return $this->addUrls($urls, 1);
     181        }
     182
     183        /**
     184         * Auto-queue hot or slow RUM paths when preloader is enabled.
     185         */
     186        public function onRumPathRecorded($path, $sample = []) {
     187                $options = get_option('vnspo_options', []);
     188                if (empty($options['preloader_enabled'])) {
     189                        return 0;
     190                }
     191                $ttfb = (float) ($sample['ttfb'] ?? 0);
     192                if ($ttfb < 600) {
     193                        return 0;
     194                }
     195                if (!is_string($path) || '' === $path || '/' !== $path[0]) {
     196                        return 0;
     197                }
     198                return $this->addUrls([home_url($path)], 1);
    127199        }
    128200
    … …  
    358430                $table = $wpdb->prefix . 'vnspo_preload_queue';
    359431
    360                 // Get pending URLs (oldest first, respect priority)
    361                 $limit = absint($batch_size);
     432                // Get pending URLs (oldest first, respect priority) throttled by host load
     433                $limit = self::computeAdaptiveBatchSize($batch_size);
     434                $throttled = false;
    362435                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    363436                $rows = $wpdb->get_results(
    … …  
    400473
    401474                        // Perform the preload request
     475                        $t0 = microtime(true);
    402476                        $result = $this->preloadUrl($row['url'], $row['device']);
     477                        $elapsed = microtime(true) - $t0;
    403478
    404479                        if ($result === true) {
    … …  
    440515                                $stats['failed']++;
    441516                        }
    442                 }
    443 
    444                 // Schedule next batch if there are more items
     517
     518                        if (self::shouldBackoffAfterRequest($elapsed, true === $result)) {
     519                                $throttled = true;
     520                                break;
     521                        }
     522                }
     523
     524                // Schedule next batch if there are more items (with adaptive backoff when host is slow)
    445525                $remaining = $this->countPending();
    446526                if ($remaining > 0) {
    447                         $this->scheduleProcessing(60); // Process next batch in 60 seconds
     527                        $this->scheduleProcessing($throttled ? 180 : 60);
    448528                }
    449529
  • vn-speed-optimizer/trunk/src/Services/Optimization/System/HtaccessManager.php

    r3813133 r3847091  
    2323 * - Cache-Control headers for static assets
    2424 *
    25  * Mirrors WP Rocket's htaccess engine (inc/functions/htaccess.php)
    26  * with VNSPO-specific configuration.
     25 * VNSPO server-level .htaccess rule generator and block manager.
    2726 *
    2827 * @since 1.3.0
    … …  
    3130
    3231        /**
    33          * Marker comment for WP Rocket-style block preservation
     32         * Marker comment for VNSPO-managed .htaccess block preservation
    3433         */
    3534        const MARKER_START = '# BEGIN VNSPO';
    … …  
    6261         */
    6362        public function syncVersionedRules() {
    64                 $rules_version = 'server-cache-v1';
     63                $rules_version = 'server-cache-v4';
    6564                if (function_exists('get_option') && $rules_version === get_option('vnspo_htaccess_rules_version', '')) {
    6665                        return true;
    … …  
    8180
    8281                if (function_exists('update_option')) {
    83                         update_option('vnspo_htaccess_rules_version', 'server-cache-v1', false);
     82                        update_option('vnspo_htaccess_rules_version', 'server-cache-v4', false);
    8483                }
    8584
    … …  
    258257                }
    259258
    260                 $version = VNSPEED_VERSION;
     259                $version = defined('VNSPO_VERSION') ? VNSPO_VERSION : (defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
    261260
    262261                $rules  = "<IfModule mod_alias.c>\n";
    … …  
    382381                $rules .= "\t</IfModule>\n";
    383382                $rules .= "\t<IfModule mod_headers.c>\n";
    384                 $rules .= "\t\t Header append Vary: Accept-Encoding\n";
     383                $rules .= "\t\tHeader merge Vary Accept-Encoding\n";
    385384                $rules .= "\t</IfModule>\n";
    386385                $rules .= "</IfModule>\n";
    … …  
    437436                $rules .= "Header always set X-VNSPO-Cache \"HIT-SERVER\" env=VNSPO_CACHE_HIT\n";
    438437                $rules .= "Header always set X-VNSPO-Cache \"HIT-SERVER\" env=REDIRECT_VNSPO_CACHE_HIT\n";
     438                $rules .= "Header always set Cache-Control \"public, max-age=0, must-revalidate\" env=VNSPO_CACHE_HIT\n";
    439439                $rules .= "Header always set Cache-Control \"public, max-age=0, must-revalidate\" env=REDIRECT_VNSPO_CACHE_HIT\n";
    440440                $rules .= "</IfModule>\n\n";
    … …  
    444444                $rules .= "RewriteBase " . $home_root . "\n";
    445445
     446                // Environment-flag rules run first so their RewriteRule directives never consume bypass RewriteConds.
    446447                // SSL
    447448                $rules .= $this->generateSSLRewriteCond();
    … …  
    453454
    454455                $rules .= $gzip_rules;
    455                 $rules .= "RewriteCond %{REQUEST_METHOD} ^(GET|HEAD)$\n";
    456                 $rules .= "RewriteCond %{QUERY_STRING} ^$ [OR]\n";
    457                 $rules .= "RewriteCond %{QUERY_STRING} " . CacheQueryPolicy::trackingQueryPattern() . " [NC]\n";
    458                 $rules .= "RewriteCond %{REQUEST_URI} !%\n";
    459                 $rules .= "RewriteCond %{REQUEST_URI} !\\.(?:xml|json)(?:/|$) [NC]\n";
     456
     457                // Mobile env variant (when mobile cache is separated)
     458                if ($options['cache_mobile']) {
     459                        $rules .= "RewriteCond %{HTTP_USER_AGENT} (mobile|android|iphone|ipod|iemobile|windows\\ phone) [NC]\n";
     460                        $rules .= "RewriteRule .* - [E=VNSPO_MOBILE:-mobile]\n";
     461                }
     462
     463                // Shared bypass conditions repeated before every cache-serving RewriteRule
     464                // because mod_rewrite binds RewriteCond directives only to the next RewriteRule.
     465                $cache_conds  = "RewriteCond %{REQUEST_METHOD} ^(GET|HEAD)$\n";
     466                $cache_conds .= "RewriteCond %{QUERY_STRING} ^$ [OR]\n";
     467                $cache_conds .= "RewriteCond %{QUERY_STRING} " . CacheQueryPolicy::trackingQueryPattern() . " [NC]\n";
     468                $cache_conds .= "RewriteCond %{REQUEST_URI} !%\n";
     469                $cache_conds .= "RewriteCond %{REQUEST_URI} !\\.(?:xml|json)(?:/|$) [NC]\n";
    460470
    461471                // Rejected cookies
    462472                $cookies = $this->getRejectedCookies();
    463473                if ($cookies) {
    464                         $rules .= "RewriteCond %{HTTP:Cookie} !(" . $cookies . ") [NC]\n";
     474                        $cache_conds .= "RewriteCond %{HTTP:Cookie} !(" . $cookies . ") [NC]\n";
    465475                }
    466476
    … …  
    468478                $protected_paths = $this->getProtectedCachePaths();
    469479                if ($protected_paths) {
    470                         $rules .= "RewriteCond %{REQUEST_URI} !^(?:" . $protected_paths . ") [NC]\n";
     480                        $cache_conds .= "RewriteCond %{REQUEST_URI} !^(?:" . $protected_paths . ") [NC]\n";
    471481                }
    472482
    … …  
    474484                $uri = $this->getRejectedUri();
    475485                if ($uri) {
    476                         $rules .= "RewriteCond %{REQUEST_URI} !^(" . $uri . ")$ [NC]\n";
    477                 }
    478 
    479                 // Mobile
     486                        $cache_conds .= "RewriteCond %{REQUEST_URI} !^(" . $uri . ")$ [NC]\n";
     487                }
     488
     489                // Desktop-only UA exclusion when mobile cache is disabled
    480490                if (! $options['cache_mobile']) {
    481                         $rules .= $this->generateMobileRewriteCond();
    482                 } else {
    483                         $rules .= "RewriteCond %{HTTP_USER_AGENT} (mobile|android|iphone|ipod|iemobile|windows\\ phone) [NC]\n";
    484                         $rules .= "RewriteRule .* - [E=VNSPO_MOBILE:-mobile]\n";
     491                        $cache_conds .= $this->generateMobileRewriteCond();
    485492                }
    486493
    … …  
    488495                $ua = $this->getRejectedUa();
    489496                if ($ua) {
    490                         $rules .= "RewriteCond %{HTTP_USER_AGENT} !^(" . $ua . ").* [NC]\n";
    491                 }
     497                        $cache_conds .= "RewriteCond %{HTTP_USER_AGENT} !^(" . $ua . ").* [NC]\n";
     498                }
     499
     500                $cache_conds .= "RewriteCond %{HTTP_HOST} " . $host_pattern . "\n";
    492501
    493502                $index_file = 'index%{ENV:VNSPO_SSL}%{ENV:VNSPO_WEBP}%{ENV:VNSPO_MOBILE}.html' . $enc;
    494                 $rules .= "RewriteCond %{HTTP_HOST} " . $host_pattern . "\n";
     503                $rules .= $cache_conds;
    495504                $rules .= "RewriteCond %{REQUEST_URI} =/\n";
    496505                $rules .= 'RewriteCond "' . $cache_base_path . '/' . $index_file . '" -f' . "\n";
    497506                $rules .= 'RewriteRule ^$ "' . $cache_root . $http_host . '/' . $index_file . '" [E=VNSPO_CACHE_HIT:1,L]' . "\n";
    498                 $rules .= "RewriteCond %{HTTP_HOST} " . $host_pattern . "\n";
    499                 $rules .= "RewriteCond %{REQUEST_URI} /$\n";
     507                $rules .= $cache_conds;
     508                $rules .= "RewriteCond %{REQUEST_URI} ^/.+/$\n";
    500509                $rules .= 'RewriteCond "' . $cache_base_path . '%{REQUEST_URI}' . $index_file . '" -f' . "\n";
    501510                $rules .= 'RewriteRule .* "' . $cache_root . $http_host . '%{REQUEST_URI}' . $index_file . '" [E=VNSPO_CACHE_HIT:1,L]' . "\n";
    502                 $rules .= "RewriteCond %{HTTP_HOST} " . $host_pattern . "\n";
     511                $rules .= $cache_conds;
    503512                $rules .= "RewriteCond %{REQUEST_URI} !/$\n";
    504513                $rules .= 'RewriteCond "' . $cache_base_path . '%{REQUEST_URI}/' . $index_file . '" -f' . "\n";
    … …  
    590599                        'woocommerce_items_in_cart',
    591600                        'woocommerce_cart_hash',
     601                        'woocommerce_recently_viewed',
    592602                        'wp_woocommerce_session_',
     603                        'yith_wcwl_session_',
    593604                        'edd_items_in_cart',
    594605                );
    … …  
    655666                        return true;
    656667                }
    657                 $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? (string) $_SERVER['SERVER_SOFTWARE'] : '';
     668                $raw_server_software = isset($_SERVER['SERVER_SOFTWARE']) ? (string) $_SERVER['SERVER_SOFTWARE'] : '';
     669                if (function_exists('wp_unslash')) {
     670                        $raw_server_software = (string) \wp_unslash($raw_server_software);
     671                }
     672                $server_software = function_exists('sanitize_text_field')
     673                        ? \sanitize_text_field($raw_server_software)
     674                        : $raw_server_software;
    658675                return false !== stripos($server_software, 'litespeed');
    659676        }
    … …  
    680697                        '/checkout',
    681698                        '/my-account',
     699                        '/gio-hang',
     700                        '/thanh-toan',
     701                        '/tai-khoan',
    682702                );
    683703                $protected_urls = array(
  • vn-speed-optimizer/trunk/src/Services/Optimization/TBTOptimizer.php

    r3810859 r3847091  
    147147     */
    148148    public function handle_tbt_report($request) {
     149        $nonce = is_object($request) && method_exists($request, 'get_header')
     150            ? \sanitize_text_field((string) $request->get_header('X-WP-Nonce'))
     151            : '';
     152        if ('' === $nonce || ! \wp_verify_nonce($nonce, 'wp_rest')) {
     153            return new \WP_REST_Response(['success' => false, 'error' => 'invalid_nonce'], 403);
     154        }
     155
    149156        $options = \get_option('vnspo_options', []);
    150157        if (empty($options['rum_enabled'])) {
  • vn-speed-optimizer/trunk/src/Services/PageCache.php

    r3810859 r3847091  
    445445                // The default WooCommerce endpoints are known bypasses. Decide these
    446446                // before resolving all configured WooCommerce page permalinks below.
    447                 if (preg_match('#^/(?:cart|checkout|my-account)(?:/|$)#i', $path)) {
     447                if (preg_match('#^/(?:cart|checkout|my-account|gio-hang|thanh-toan|tai-khoan)(?:/|$)#i', $path)) {
    448448                        return false;
    449449                }
    … …  
    463463                $protected_paths = array(
    464464                        '/wp-admin', '/wp-login.php', '/wp-register.php', '/xmlrpc.php', '/wp-json',
    465                         '/cart', '/checkout', '/my-account',
     465                        '/wc-api', '/cart', '/checkout', '/my-account',
     466                        '/gio-hang', '/thanh-toan', '/tai-khoan',
    466467                );
    467468                $protected_urls = array(
    … …  
    499500                        'woocommerce_items_in_cart',
    500501                        'woocommerce_cart_hash',
     502                        'woocommerce_recently_viewed',
    501503                        'wp_woocommerce_session_',
     504                        'yith_wcwl_session_',
    502505                        'edd_items_in_cart',
    503506                );
  • vn-speed-optimizer/trunk/src/Services/SEO/AeoFrontend.php

    r3810859 r3847091  
    8282        \ob_start();
    8383        ?>
    84         <!-- VN-Nexus AEO Quick Summary -->
     84        <!-- VN Speed Optimizer AEO Quick Summary -->
    8585        <section id="vnspo-aeo-summary" aria-label="Quick Summary" data-nosnippet class="vnspo-aeo-box">
    8686            <div class="vnspo-aeo-header">
  • vn-speed-optimizer/trunk/src/Services/SEO/AeoMetabox.php

    r3810859 r3847091  
    11<?php
    22namespace VNSPO\Services\SEO;
     3
     4if ( ! defined( 'ABSPATH' ) ) {
     5    exit;
     6}
    37
    48class AeoMetabox {
    … …  
    2428        add_meta_box(
    2529            'vnspo_aeo_dashboard',
    26             'VN-Nexus AEO Check',
     30            esc_html__( 'VN Speed Optimizer AEO Check', 'vn-speed-optimizer' ),
    2731            array( $this, 'render_metabox_html' ),
    2832            array( 'post', 'page' ),
    … …  
    3741        }
    3842
     43        $plugin_url = defined('VNSPO_PLUGIN_URL') ? VNSPO_PLUGIN_URL : (defined('VNSPEED_PLUGIN_URL') ? VNSPEED_PLUGIN_URL : '');
     44        $version    = defined('VNSPO_VERSION') ? VNSPO_VERSION : (defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2');
     45
    3946        wp_enqueue_style(
    4047            'vnspo-aeo-css',
    41             VNSPEED_PLUGIN_URL . 'assets/aeo-dashboard.css',
     48            $plugin_url . 'assets/aeo-dashboard.css',
    4249            array(),
    43             VNSPEED_VERSION
     50            $version
    4451        );
    4552
    4653        wp_enqueue_script(
    4754            'vnspo-aeo-js',
    48             VNSPEED_PLUGIN_URL . 'assets/aeo-dashboard.js',
     55            $plugin_url . 'assets/aeo-dashboard.js',
    4956            array( 'jquery' ),
    50             VNSPEED_VERSION,
     57            $version,
    5158            true
    5259        );
    … …  
    108115        }
    109116
    110         $content = isset( $_POST['content'] ) ? wp_unslash( $_POST['content'] ) : '';
     117        $content = isset( $_POST['content'] ) ? wp_kses_post( wp_unslash( $_POST['content'] ) ) : '';
    111118       
    112119        $result = $this->perform_aeo_analysis( $content );
    … …  
    133140           
    134141            // Log success for audit (optional)
    135             error_log("VN-Nexus AEO: Auto-applied summary for post $post_id ($keyword)");
     142            if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
     143                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     144                error_log( "[VNSPO AEO] Auto-applied summary for post $post_id ($keyword)" );
     145            }
    136146        }
    137147    }
  • vn-speed-optimizer/trunk/src/Services/SEO/RedirectLogger.php

    r3456323 r3847091  
    44 * RedirectLogger Service
    55 *
    6  * Logs all redirects with hit count tracking
    7  * Inspired by Rank Math Pro redirect logging
     6 * Logs all redirects with hit count tracking.
    87 *
    98 * @package VNSPO
    … …  
    3635                add_filter('wp_redirect', array($this, 'log_redirect'), 10, 2);
    3736
    38                 // Create table on activation
    39                 add_action('init', array($this, 'maybe_create_table'), 1);
     37                // Create table in admin only when schema option is not yet recorded
     38                add_action('admin_init', array($this, 'maybe_create_table'));
    4039        }
    4140
    … …  
    4544        public function maybe_create_table()
    4645        {
     46                if (function_exists('get_option') && '1' === (string) get_option('vnspo_redirect_logs_db_ver', '')) {
     47                        return;
     48                }
     49
    4750                global $wpdb;
    4851
    … …  
    6467                require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    6568                dbDelta($sql);
     69
     70                if (function_exists('update_option')) {
     71                        update_option('vnspo_redirect_logs_db_ver', '1', false);
     72                }
    6673        }
    6774
    … …  
    7986                if (empty($options['log_redirects'])) {
    8087                        return $location;
     88                }
     89
     90                if (function_exists('get_option') && '1' !== (string) get_option('vnspo_redirect_logs_db_ver', '')) {
     91                        $this->maybe_create_table();
    8192                }
    8293
    … …  
    108119
    109120        /**
     121         * Guard CSV cell values against spreadsheet formula injection.
     122         *
     123         * @param mixed $value Raw cell value.
     124         * @return string Escaped CSV cell value.
     125         */
     126        public static function escape_csv_cell($value)
     127        {
     128                $str = (string) $value;
     129                if ('' !== $str && in_array($str[0], array('=', '+', '-', '@', "\t", "\r"), true)) {
     130                        return "'" . $str;
     131                }
     132
     133                return $str;
     134        }
     135
     136        /**
    110137         * Export redirect logs to CSV
    111138         */
    112139        public function export_csv()
    113140        {
     141                if (! function_exists('current_user_can') || ! current_user_can('manage_options')) {
     142                        return;
     143                }
     144
    114145                global $wpdb;
    115146
    … …  
    138169                // CSV rows
    139170                foreach ($results as $row) {
    140                         fputcsv($output, $row);
     171                        $safe_row = array_map(array(__CLASS__, 'escape_csv_cell'), (array) $row);
     172                        fputcsv($output, $safe_row);
    141173                }
    142174
  • vn-speed-optimizer/trunk/src/Services/SEO/SchemaStacker.php

    r3810859 r3847091  
    11<?php
    22namespace VNSPO\Services\SEO;
     3
     4if ( ! defined( 'ABSPATH' ) ) {
     5    exit;
     6}
    37
    48class SchemaStacker {
    … …  
    8791            );
    8892
    89             echo "\n<!-- VN-Nexus AEO Schema Stacking -->\n";
     93            echo "\n<!-- VN Speed Optimizer AEO Schema Stacking -->\n";
    9094            // The escape flags above guarantee no </script> breakout is possible.
    9195            echo '<script type="application/ld+json">' . $minified_schema . '</script>' . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
  • vn-speed-optimizer/trunk/src/Services/SEO/Seo404Monitor.php

    r3810859 r3847091  
    6363        global $wp;
    6464
    65         $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';
    66         $referrer = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field($_SERVER['HTTP_REFERER']) : '';
    67         $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '';
     65        $request_uri = isset($_SERVER['REQUEST_URI']) ? \esc_url_raw(\wp_unslash($_SERVER['REQUEST_URI'])) : '';
     66        $referrer = isset($_SERVER['HTTP_REFERER']) ? \esc_url_raw(\wp_unslash($_SERVER['HTTP_REFERER'])) : '';
     67        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? \sanitize_text_field(\wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
    6868
    6969        // Get suggestion if available
  • vn-speed-optimizer/trunk/src/Services/System/CompatibilityManager.php

    r3810859 r3847091  
    1111 *
    1212 * Comprehensive 3rd-party plugin and hosting compatibility layer.
    13  * Mirrors WP Rocket's 3rd-party compatibility system.
    1413 *
    1514 * Handles:
  • vn-speed-optimizer/trunk/src/Services/System/Security/ImmutableLog.php

    r3810859 r3847091  
    109109    private function ensure_table()
    110110    {
     111        if (function_exists('get_option') && get_option('vnspo_immutable_log_table_created')) {
     112            return;
     113        }
     114
    111115        global $wpdb;
    112116        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
    … …  
    127131            dbDelta($sql);
    128132        }
     133
     134        if (function_exists('update_option')) {
     135            update_option('vnspo_immutable_log_table_created', 1, false);
     136        }
    129137    }
    130138}
  • vn-speed-optimizer/trunk/src/Templates/advanced-cache.php

    r3810859 r3847091  
    1313if (! function_exists('vnspo_serve_advanced_cache')) {
    1414        function vnspo_serve_advanced_cache() {
    15                 $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper((string) $_SERVER['REQUEST_METHOD']) : 'GET';
    16                 if ('GET' !== $method) {
    17                         return;
    18                 }
     15                $vnspoStart = microtime(true);
     16                $method     = isset($_SERVER['REQUEST_METHOD']) ? strtoupper((string) $_SERVER['REQUEST_METHOD']) : 'GET';
     17                if ('GET' !== $method && 'HEAD' !== $method) {
     18                        return;
     19                }
     20                $isHead = ('HEAD' === $method);
    1921
    2022                $rawUri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '/';
    … …  
    6062                                        'woocommerce_items_in_cart' === $name ||
    6163                                        'woocommerce_cart_hash' === $name ||
    62                                         0 === strpos($name, 'wp_woocommerce_session_')
     64                                        'woocommerce_recently_viewed' === $name ||
     65                                        0 === strpos($name, 'wp_woocommerce_session_') ||
     66                                        0 === strpos($name, 'yith_wcwl_session_')
    6367                                ) {
    6468                                        return;
    … …  
    99103                );
    100104
    101                 $cacheDir = defined('WP_CONTENT_DIR') ? rtrim(WP_CONTENT_DIR, '/\\') . '/uploads/vnspo-cache/' : '';
    102                 $ttl      = 86400;
    103                 $useMobile = false;
    104                 $useWebp   = false;
     105                $cacheDir    = defined('WP_CONTENT_DIR') ? rtrim(WP_CONTENT_DIR, '/\\') . '/uploads/vnspo-cache/' : '';
     106                $ttl         = 86400;
     107                $useMobile   = false;
     108                $useWebp     = false;
     109                $excludeUris = array(
     110                        '/wp-admin',
     111                        '/wp-login.php',
     112                        '/wp-json',
     113                        '/xmlrpc.php',
     114                        '/wc-api',
     115                        '/cart',
     116                        '/checkout',
     117                        '/my-account',
     118                        '/gio-hang',
     119                        '/thanh-toan',
     120                        '/tai-khoan',
     121                        '/feed',
     122                );
    105123
    106124                $configFile = defined('WP_CONTENT_DIR') ? rtrim(WP_CONTENT_DIR, '/\\') . '/vnspo-config/advanced-cache-config.php' : '';
    … …  
    116134                                $useMobile = ! empty($cfg['cache_mobile']);
    117135                                $useWebp   = ! empty($cfg['cache_webp']);
     136                                if (! empty($cfg['exclude_uris']) && is_array($cfg['exclude_uris'])) {
     137                                        $excludeUris = array_values(array_unique(array_merge($excludeUris, $cfg['exclude_uris'])));
     138                                }
     139                        }
     140                }
     141
     142                $normalizedUriPath = '/' . ltrim(strtolower($uriPath), '/');
     143                foreach ($excludeUris as $exUri) {
     144                        if (! is_string($exUri)) {
     145                                continue;
     146                        }
     147                        $exPrefix = '/' . ltrim(strtolower(trim($exUri)), '/');
     148                        if ('/' === $exPrefix) {
     149                                continue;
     150                        }
     151                        if (0 === strpos($normalizedUriPath, $exPrefix)) {
     152                                return;
    118153                        }
    119154                }
    … …  
    142177                        return;
    143178                }
    144 
    145                 $etag = '"' . md5_file($realFile) . '"';
     179                if ((int) @filesize($realFile) < 64) {
     180                        return;
     181                }
     182
     183                $dropinMs = number_format((microtime(true) - $vnspoStart) * 1000, 2, '.', '');
     184                $etag     = '"' . md5_file($realFile) . '"';
    146185                if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim((string) $_SERVER['HTTP_IF_NONE_MATCH']) === $etag) {
    147186                        header('HTTP/1.1 304 Not Modified');
     187                        header('Cache-Control: public, max-age=0, must-revalidate');
    148188                        header('X-VNSPO-Cache: HIT-DROPIN');
     189                        header('X-VNSPO-Dropin-Ms: ' . $dropinMs);
    149190                        exit;
    150191                }
    151192
    152193                $acceptEncoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? strtolower((string) $_SERVER['HTTP_ACCEPT_ENCODING']) : '';
    153                 $gzFile = $realFile . '.gz';
    154                 if (false !== strpos($acceptEncoding, 'gzip') && is_file($gzFile) && is_readable($gzFile)) {
    155                         header('Content-Type: text/html; charset=UTF-8');
    156                         header('Content-Encoding: gzip');
    157                         header('Vary: Accept-Encoding');
    158                         header('ETag: ' . $etag);
    159                         header('X-VNSPO-Cache: HIT-DROPIN');
    160                         /* phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile */ readfile($gzFile);
    161                         exit;
    162                 }
     194                $brFile         = $realFile . '.br';
     195                $gzFile         = $realFile . '.gz';
    163196
    164197                header('Content-Type: text/html; charset=UTF-8');
     198                header('Cache-Control: public, max-age=0, must-revalidate');
     199                header('Vary: Accept-Encoding');
    165200                header('ETag: ' . $etag);
    166201                header('X-VNSPO-Cache: HIT-DROPIN');
     202                header('X-VNSPO-Dropin-Ms: ' . $dropinMs);
     203
     204                if ($isHead) {
     205                        exit;
     206                }
     207
     208                if (false !== strpos($acceptEncoding, 'br') && is_file($brFile) && is_readable($brFile)) {
     209                        header('Content-Encoding: br');
     210                        /* phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile */ readfile($brFile);
     211                        exit;
     212                }
     213                if (false !== strpos($acceptEncoding, 'gzip') && is_file($gzFile) && is_readable($gzFile)) {
     214                        header('Content-Encoding: gzip');
     215                        /* phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile */ readfile($gzFile);
     216                        exit;
     217                }
     218
    167219                /* phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile */ readfile($realFile);
    168220                exit;
  • vn-speed-optimizer/trunk/uninstall.php

    r3810859 r3847091  
    2424global $wpdb;
    2525
    26 // 1. Remove every option whose name starts with vnspo_ (site + transients).
     26// 1. Remove every option whose name starts with vnspo_ or legacy vnspeed_ (site + transients).
    2727$wpdb->query(
    2828        $wpdb->prepare(
    29                 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
    30                 $wpdb->esc_like( 'vnspo_' ) . '%'
     29                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
     30                $wpdb->esc_like( 'vnspo_' ) . '%',
     31                $wpdb->esc_like( 'vnspeed_' ) . '%'
    3132        )
    3233);
    3334$wpdb->query(
    3435        $wpdb->prepare(
    35                 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
     36                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s",
    3637                $wpdb->esc_like( '_transient_vnspo_' ) . '%',
    37                 $wpdb->esc_like( '_transient_timeout_vnspo_' ) . '%'
     38                $wpdb->esc_like( '_transient_timeout_vnspo_' ) . '%',
     39                $wpdb->esc_like( '_transient_vnspeed_' ) . '%',
     40                $wpdb->esc_like( '_transient_timeout_vnspeed_' ) . '%'
    3841        )
    3942);
    4043
    41 // 2. Multisite support — also clean sitemeta if present.
     44// 2. Multisite support — also clean sitemeta and site transients if present.
    4245if ( is_multisite() ) {
    4346        $wpdb->query(
    4447                $wpdb->prepare(
    45                         "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s",
    46                         $wpdb->esc_like( 'vnspo_' ) . '%'
     48                        "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s OR meta_key LIKE %s OR meta_key LIKE %s OR meta_key LIKE %s OR meta_key LIKE %s OR meta_key LIKE %s",
     49                        $wpdb->esc_like( 'vnspo_' ) . '%',
     50                        $wpdb->esc_like( 'vnspeed_' ) . '%',
     51                        $wpdb->esc_like( '_site_transient_vnspo_' ) . '%',
     52                        $wpdb->esc_like( '_site_transient_timeout_vnspo_' ) . '%',
     53                        $wpdb->esc_like( '_site_transient_vnspeed_' ) . '%',
     54                        $wpdb->esc_like( '_site_transient_timeout_vnspeed_' ) . '%'
    4755                )
    4856        );
    … …  
    5058
    5159// 3. Drop custom tables owned by the plugin.
    52 foreach ( array( 'vnspo_404_logs', 'vnspo_rum', 'vnspo_immutable_log' ) as $vnspo_table ) {
     60foreach ( array( 'vnspo_404_logs', 'vnspo_rum', 'vnspo_immutable_log', 'vnspo_preload_queue', 'vnspo_redirect_logs' ) as $vnspo_table ) {
    5361        $vnspo_table_name = esc_sql( $wpdb->prefix . $vnspo_table );
    5462        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
    … …  
    5664}
    5765
    58 // 4. Clean post meta.
     66// 4. Clean post meta and user meta.
    5967$wpdb->query(
    6068        $wpdb->prepare(
    … …  
    6371        )
    6472);
     73$wpdb->query(
     74        $wpdb->prepare(
     75                "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s",
     76                $wpdb->esc_like( 'vnspo_' ) . '%'
     77        )
     78);
    6579
    66 // 5. Clear scheduled hooks.
    67 foreach ( array( 'vnspo_daily_maintenance', 'vnspo_hourly_event', 'vnspo_hive_mind_daily_tune' ) as $vnspo_hook ) {
     80// 5. Clear scheduled hooks (current vnspo_* and legacy vnspeed_*).
     81$vnspo_cron_hooks = array(
     82        'vnspo_daily_maintenance',
     83        'vnspo_hourly_event',
     84        'vnspo_hive_mind_daily_tune',
     85        'vnspo_scheduled_database_backup',
     86        'vnspo_autopilot_analysis',
     87        'vnspeed_ai_review_verify',
     88        'vnspo_async_ai_caption_job',
     89        'vnspeed_retry_metrics_revocation',
     90        'vnspeed_upload_public_assets',
     91        'vnspo_performance_check',
     92        'vnspeed_send_aggregate_metrics',
     93        'vnspeed_refresh_edge_policy',
     94        'vnspo_cf_devmode_deactivate',
     95        'vnspo_database_cleanup',
     96        'vnspo_database_optimize_cron',
     97        'vnspo_update_external_assets',
     98        'vnspo_batch_media_sync',
     99        'vnspo_cache_warm_top_urls',
     100        'vnspo_single_warm',
     101        'vnspo_run_preloader',
     102        'vnspo_r2_verify_upload',
     103        'vnspo_async_push_snapshot',
     104        'vnspo_webp_batch_process',
     105        'vnspo_daily_pagespeed_check',
     106        'vnspo_daily_asset_update',
     107        'vnspo_refresh_local_gtag',
     108        'vnspo_preload_process',
     109        'vnspo_cpcss_cleanup',
     110        'vnspo_sync_threat_shield_event',
     111        'vnspo_send_telemetry',
     112        'vnspo_generate_post_critical_css',
     113);
     114foreach ( $vnspo_cron_hooks as $vnspo_hook ) {
    68115        wp_clear_scheduled_hook( $vnspo_hook );
    69116}
    70117
    71 // 6. Delete the current and legacy cache directories from disk.
     118// 6. Delete the current and legacy cache directories from disk without following symlinks.
     119if ( ! function_exists( 'vnspo_uninstall_remove_directory' ) ) {
     120        /**
     121         * Recursively remove a cache directory using lexical paths only.
     122         *
     123         * @param string                    $vnspo_dir           Target directory path.
     124         * @param WP_Filesystem_Base|null   $vnspo_wp_filesystem Optional filesystem instance.
     125         * @return void
     126         */
     127        function vnspo_uninstall_remove_directory( $vnspo_dir, $vnspo_wp_filesystem = null ) {
     128                if ( is_link( $vnspo_dir ) ) {
     129                        \wp_delete_file( $vnspo_dir );
     130                        return;
     131                }
     132                if ( ! is_dir( $vnspo_dir ) ) {
     133                        return;
     134                }
     135
     136                $vnspo_iterator = new RecursiveIteratorIterator(
     137                        new RecursiveDirectoryIterator( $vnspo_dir, FilesystemIterator::SKIP_DOTS ),
     138                        RecursiveIteratorIterator::CHILD_FIRST
     139                );
     140
     141                foreach ( $vnspo_iterator as $vnspo_fileinfo ) {
     142                        if ( $vnspo_fileinfo->isLink() ) {
     143                                \wp_delete_file( $vnspo_fileinfo->getPathname() );
     144                                continue;
     145                        }
     146                        if ( $vnspo_fileinfo->isDir() ) {
     147                                if ( $vnspo_wp_filesystem instanceof WP_Filesystem_Base ) {
     148                                        $vnspo_wp_filesystem->rmdir( $vnspo_fileinfo->getPathname(), false );
     149                                } else {
     150                                        @rmdir( $vnspo_fileinfo->getPathname() ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
     151                                }
     152                                continue;
     153                        }
     154                        \wp_delete_file( $vnspo_fileinfo->getPathname() );
     155                }
     156
     157                if ( $vnspo_wp_filesystem instanceof WP_Filesystem_Base ) {
     158                        $vnspo_wp_filesystem->rmdir( $vnspo_dir, false );
     159                } else {
     160                        @rmdir( $vnspo_dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
     161                }
     162        }
     163}
     164
    72165$vnspo_upload_dir = wp_upload_dir();
    73166if ( ! function_exists( 'WP_Filesystem' ) ) {
    … …  
    77170global $wp_filesystem;
    78171
     172$vnspo_base_upload_dir = trailingslashit( $vnspo_upload_dir['basedir'] );
    79173foreach ( array( 'vnspo-cache', 'vnspo-page-cache' ) as $vnspo_cache_directory ) {
    80         $vnspo_cache_dir = trailingslashit( $vnspo_upload_dir['basedir'] ) . $vnspo_cache_directory;
    81         if ( is_link( $vnspo_cache_dir ) ) {
    82                 @\wp_delete_file( $vnspo_cache_dir );
    83                 continue;
    84         }
    85         if ( is_dir( $vnspo_cache_dir ) && $wp_filesystem instanceof WP_Filesystem_Base ) {
    86                 $wp_filesystem->rmdir( $vnspo_cache_dir, true );
    87         }
     174        vnspo_uninstall_remove_directory( $vnspo_base_upload_dir . $vnspo_cache_directory, $wp_filesystem );
    88175}
     176foreach ( array( 'vnspo/min', 'vnspo' ) as $vnspo_extra_cache_directory ) {
     177        vnspo_uninstall_remove_directory( $vnspo_base_upload_dir . $vnspo_extra_cache_directory, $wp_filesystem );
     178}
  • vn-speed-optimizer/trunk/vn-speed-optimizer.php

    r3813133 r3847091  
    44 * Plugin URI: https://vn-nexus.com/vnspo-pro
    55 * Description: Local-first WordPress performance tools for page cache, asset optimization, lazy loading, and technical diagnostics.
    6  * Version: 1.2.1
     6 * Version: 1.2.2
    77 * Author: TranDuy258
    88 * Author URI: https://profiles.wordpress.org/tranduy258
    … …  
    2626
    2727    // Plugin version
    28     define('VNSPEED_VERSION', '1.2.1');
     28    if (! defined('VNSPO_VERSION')) {
     29        define('VNSPO_VERSION', '1.2.2');
     30    }
    2931
    3032    // Edge API URL (configurable)
    … …  
    3436
    3537    // Plugin paths
    36     define('VNSPEED_PLUGIN_FILE', __FILE__);
    37     define('VNSPEED_PATH', plugin_dir_path(__FILE__));
     38    if (! defined('VNSPO_PLUGIN_FILE')) {
     39        define('VNSPO_PLUGIN_FILE', __FILE__);
     40    }
     41    if (! defined('VNSPO_PATH')) {
     42        define('VNSPO_PATH', plugin_dir_path(__FILE__));
     43    }
    3844
    3945    // Plugin URL with fallback for 0.0.0.1 site_url
    … …  
    4551        }
    4652    }
    47     define('VNSPEED_PLUGIN_URL', $vnspo_purl);
     53    if (! defined('VNSPO_PLUGIN_URL')) {
     54        define('VNSPO_PLUGIN_URL', $vnspo_purl);
     55    }
    4856    unset($vnspo_purl);
    4957
    … …  
    6573     * Get plugin URL
    6674     */
    67     function VNSPEED_URL($path = '')
     75    function vnspo_url($path = '')
    6876    {
    6977        if (empty($path)) {
    70             return VNSPEED_PLUGIN_URL;
    71         }
    72         return rtrim(VNSPEED_PLUGIN_URL, '/') . '/' . ltrim($path, '/');
     78            return VNSPO_PLUGIN_URL;
     79        }
     80        return rtrim(VNSPO_PLUGIN_URL, '/') . '/' . ltrim($path, '/');
    7381    }
    7482}
    … …  
    8593    spl_autoload_register(function ($class) {
    8694        $prefix = 'VNSPO\\';
    87         $base_dir = VNSPEED_PATH . 'src/';
     95        $base_dir = VNSPO_PATH . 'src/';
    8896        $len = strlen($prefix);
    8997
    … …  
    129137        if (\is_admin() || $is_preview) {
    130138            (new \VNSPO\Services\Optimization\Assets\ScriptDependencyInventory())->boot();
     139        }
     140        if (class_exists(\VNSPO\Services\Optimization\AutoHealService::class)) {
     141            (new \VNSPO\Services\Optimization\AutoHealService())->vnspo_register();
     142        }
     143        if (class_exists(\VNSPO\Services\Optimization\PriorityElementsService::class)) {
     144            (new \VNSPO\Services\Optimization\PriorityElementsService())->vnspo_register();
    131145        }
    132146    }, 0);
    … …  
    178192        register_rest_route('vnspo/v1', '/activate-pagespeed', [
    179193            'methods' => 'POST',
     194            'permission_callback' => function () {
     195                return current_user_can('manage_options');
     196            },
    180197            'callback' => function (\WP_REST_Request $request) {
    181198                if (! current_user_can('manage_options')) {
    … …  
    183200                }
    184201
    185                 $feature = $request->get_param('feature');
     202                $feature = \sanitize_key((string) $request->get_param('feature'));
    186203                $options = get_option('vnspo_options', []);
    187204
    … …  
    236253                ], 200);
    237254            },
    238             'permission_callback' => function () {
    239                 return current_user_can('manage_options');
    240             },
    241255        ]);
    242256    });
    … …  
    262276            'redirection' => 0,
    263277            'sslverify' => true,
    264             'user-agent' => 'VN-Speed-Optimizer/' . VNSPEED_VERSION,
     278            'user-agent' => 'VN-Speed-Optimizer/' . VNSPO_VERSION,
    265279        ]);
    266280
    … …  
    628642
    629643        if (isset($lang_map[$forced_lang]) && '' !== $lang_map[$forced_lang]['mo']) {
    630             $forced_mo = VNSPEED_PATH . 'languages/' . $lang_map[$forced_lang]['mo'];
     644            $forced_mo = VNSPO_PATH . 'languages/' . $lang_map[$forced_lang]['mo'];
    631645            if (\is_file($forced_mo)) {
    632646                \unload_textdomain('vn-speed-optimizer');
    … …  
    643657            return;
    644658        }
    645         $mo_file = VNSPEED_PATH . 'languages/vn-speed-optimizer-' . \sanitize_file_name((string) $locale) . '.mo';
     659        $mo_file = VNSPO_PATH . 'languages/vn-speed-optimizer-' . \sanitize_file_name((string) $locale) . '.mo';
    646660        if (!\is_file($mo_file)) {
    647661            $short = substr((string) $locale, 0, 2);
    648662            if (isset($lang_map[$short]) && '' !== $lang_map[$short]['mo']) {
    649                 $mo_file = VNSPEED_PATH . 'languages/' . $lang_map[$short]['mo'];
     663                $mo_file = VNSPO_PATH . 'languages/' . $lang_map[$short]['mo'];
    650664            }
    651665        }
    … …  
    665679    add_action('admin_init', function () {
    666680        $cache_ver_key = 'vnspo_combined_cache_ver';
    667         if (\get_option($cache_ver_key) !== VNSPEED_VERSION) {
     681        if (\get_option($cache_ver_key) !== VNSPO_VERSION) {
    668682            $upload = \wp_upload_dir();
    669683            $dir = $upload['basedir'] . '/vnspo/min/';
    … …  
    678692                }
    679693            }
    680             \update_option($cache_ver_key, VNSPEED_VERSION, false);
     694            \update_option($cache_ver_key, VNSPO_VERSION, false);
    681695        }
    682696    });
Note: See TracChangeset for help on using the changeset viewer.