Changeset 3847091
- Timestamp:
- 12/06/2026 03:19:29 AM (60 minutes ago)
- Location:
- vn-speed-optimizer/trunk
- Files:
-
- 4 added
- 39 deleted
- 70 edited
-
assets/admin.js (modified) (1 diff)
-
assets/aeo-dashboard.css (modified) (1 diff)
-
includes (deleted)
-
readme.txt (modified) (5 diffs)
-
src/Admin/AdminBarWidget.php (modified) (1 diff)
-
src/Admin/ConflictManager.php (modified) (1 diff)
-
src/Admin/Views (deleted)
-
src/Core/Application.php (modified) (1 diff)
-
src/Core/Container.php (modified) (1 diff)
-
src/Core/Facade.php (modified) (1 diff)
-
src/Core/ServiceProvider.php (modified) (1 diff)
-
src/Core/WhitepaperSpecs.php (deleted)
-
src/Facades/Speed.php (modified) (1 diff)
-
src/Providers/AIServiceProvider.php (modified) (3 diffs)
-
src/Providers/AdminServiceProvider.php (modified) (1 diff)
-
src/Providers/MainServiceProvider.php (modified) (5 diffs)
-
src/Providers/OptimizationServiceProvider.php (modified) (1 diff)
-
src/Providers/PageSpeedOptimizationProvider.php (modified) (4 diffs)
-
src/Services/AI/AdaptiveEngine.php (deleted)
-
src/Services/AI/NeuralMemoryBridge.php (deleted)
-
src/Services/AI/ReviewQueue.php (modified) (2 diffs)
-
src/Services/Admin/AdminPage.php (modified) (36 diffs)
-
src/Services/Admin/AdminPageTabsTrait.php (added)
-
src/Services/Admin/CloudflarePairingController.php (modified) (1 diff)
-
src/Services/Admin/PublicAssetSharing.php (modified) (1 diff)
-
src/Services/Admin/SafePreviewRollback.php (added)
-
src/Services/Admin/SearchConsoleController.php (deleted)
-
src/Services/Admin/SetupWizard.php (modified) (7 diffs)
-
src/Services/Admin/Views/Cards/AiCard.php (deleted)
-
src/Services/Admin/Views/Cards/AlertCard.php (deleted)
-
src/Services/Admin/Views/Cards/BotIntelligenceCard.php (deleted)
-
src/Services/Admin/Views/Cards/CLSOptimizerCard.php (deleted)
-
src/Services/Admin/Views/Cards/DatabaseToolsCard.php (deleted)
-
src/Services/Admin/Views/Cards/ExpertPerformanceCard.php (deleted)
-
src/Services/Admin/Views/Cards/FCPOptimizerCard.php (deleted)
-
src/Services/Admin/Views/Cards/LCPAssetsCard.php (deleted)
-
src/Services/Admin/Views/Cards/LCPOptimizerCard.php (deleted)
-
src/Services/Admin/Views/Cards/LicenseActivationCard.php (deleted)
-
src/Services/Admin/Views/Cards/PerformanceMonitorCard.php (deleted)
-
src/Services/Admin/Views/Cards/PowerBloatCard.php (deleted)
-
src/Services/Admin/Views/Cards/PreloadQueueStatusCard.php (deleted)
-
src/Services/Admin/Views/Cards/RUCSSCard.php (deleted)
-
src/Services/Admin/Views/Cards/SidebarStatusCard.php (deleted)
-
src/Services/Admin/Views/Cards/SmartMediaCard.php (deleted)
-
src/Services/Admin/Views/Cards/SmartSEOCard.php (deleted)
-
src/Services/Admin/Views/Cards/TBTOptimizerCard.php (deleted)
-
src/Services/Admin/Views/Cards/WhitepaperCard.php (deleted)
-
src/Services/Admin/Views/Cards/WooCommerceCard.php (deleted)
-
src/Services/Admin/Views/Components/AiControlPanel.php (deleted)
-
src/Services/Admin/Views/Components/BaseComponent.php (modified) (1 diff)
-
src/Services/Admin/Views/Components/Input.php (modified) (1 diff)
-
src/Services/Admin/Views/Components/Textarea.php (modified) (1 diff)
-
src/Services/Admin/Views/Components/Toggle.php (modified) (1 diff)
-
src/Services/Analytics/PerformanceMonitor.php (modified) (2 diffs)
-
src/Services/Cloud/AggregateMetricsSender.php (modified) (1 diff)
-
src/Services/Cloud/BrainClient.php (modified) (7 diffs)
-
src/Services/Cloud/LocalHubResponder.php (deleted)
-
src/Services/Core/BaseService.php (modified) (6 diffs)
-
src/Services/Database/DatabaseCleanup.php (modified) (1 diff)
-
src/Services/Database/DatabaseCleanupProcess.php (modified) (1 diff)
-
src/Services/Database/ObjectCache.php (modified) (2 diffs)
-
src/Services/Edge/AdvancedPerformance.php (modified) (3 diffs)
-
src/Services/Edge/AjaxHandlers.php (modified) (1 diff)
-
src/Services/Edge/SmartJSWhitelist.php (deleted)
-
src/Services/Media/AvatarAltText.php (modified) (1 diff)
-
src/Services/Media/ImageDimensionsFixer.php (modified) (1 diff)
-
src/Services/Media/LQIPPlaceholderHelpers.php (modified) (1 diff)
-
src/Services/Media/WebPConverterService.php (modified) (2 diffs)
-
src/Services/Media/YouTubeLazyLoad.php (modified) (1 diff)
-
src/Services/Optimization/AdaptiveEngine.php (deleted)
-
src/Services/Optimization/Assets/AssetCombiner.php (modified) (1 diff)
-
src/Services/Optimization/Assets/AssetLocalizer.php (modified) (2 diffs)
-
src/Services/Optimization/Assets/AssetManager.php (modified) (1 diff)
-
src/Services/Optimization/Assets/AssetOptimizer.php (modified) (2 diffs)
-
src/Services/Optimization/Assets/DelayJsConfig.php (modified) (3 diffs)
-
src/Services/Optimization/Assets/EnhancedLazyLoadScript.php (modified) (1 diff)
-
src/Services/Optimization/Assets/InteractionDelay.php (modified) (2 diffs)
-
src/Services/Optimization/AutoHealService.php (added)
-
src/Services/Optimization/CLSOptimizer.php (modified) (1 diff)
-
src/Services/Optimization/Cache/ConfigGenerator.php (modified) (1 diff)
-
src/Services/Optimization/Cache/DropInManager.php (modified) (2 diffs)
-
src/Services/Optimization/Cache/MobileCacheManager.php (modified) (1 diff)
-
src/Services/Optimization/Cache/PageCacheCompatibility.php (modified) (1 diff)
-
src/Services/Optimization/Cache/VarnishPurger.php (modified) (1 diff)
-
src/Services/Optimization/INPOptimizer.php (modified) (1 diff)
-
src/Services/Optimization/Network/BrowserCache.php (modified) (1 diff)
-
src/Services/Optimization/Network/FastLlmsTxt.php (modified) (1 diff)
-
src/Services/Optimization/Network/SmartPrefetch.php (modified) (5 diffs)
-
src/Services/Optimization/Network/SpeculationRules.php (modified) (2 diffs)
-
src/Services/Optimization/Preload/PreloadQueue.php (modified) (5 diffs)
-
src/Services/Optimization/PriorityElementsService.php (added)
-
src/Services/Optimization/System/HtaccessManager.php (modified) (15 diffs)
-
src/Services/Optimization/TBTOptimizer.php (modified) (1 diff)
-
src/Services/PageCache.php (modified) (3 diffs)
-
src/Services/SEO/AeoFrontend.php (modified) (1 diff)
-
src/Services/SEO/AeoMetabox.php (modified) (5 diffs)
-
src/Services/SEO/Calculators (deleted)
-
src/Services/SEO/ExpertAuthorSchema.php (deleted)
-
src/Services/SEO/FourOhFourMonitor.php (deleted)
-
src/Services/SEO/LocalFaqProvider.php (deleted)
-
src/Services/SEO/RedirectLogger.php (modified) (7 diffs)
-
src/Services/SEO/SchemaRulesEngine.php (deleted)
-
src/Services/SEO/SchemaStacker.php (modified) (2 diffs)
-
src/Services/SEO/Seo404Monitor.php (modified) (1 diff)
-
src/Services/SEO/SmartAccessibility.php (deleted)
-
src/Services/SEO/SmartSeo.php (deleted)
-
src/Services/System/CompatibilityManager.php (modified) (1 diff)
-
src/Services/System/Security/Firewall.php (deleted)
-
src/Services/System/Security/ImmutableLog.php (modified) (2 diffs)
-
src/Templates/advanced-cache.php (modified) (5 diffs)
-
src/js (deleted)
-
uninstall.php (modified) (5 diffs)
-
vn-speed-optimizer.php (modified) (15 diffs)
Legend:
- Unmodified
- Added
- Removed
-
vn-speed-optimizer/trunk/assets/admin.js
r3810859 r3847091 35 35 var cls = 36 36 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 || "")); 44 41 $(".vnspo-wrap").prepend($n); 45 42 setTimeout(function () { -
vn-speed-optimizer/trunk/assets/aeo-dashboard.css
r3810859 r3847091 1 /* VN -NexusAEO Dashboard CSS */1 /* VN Speed Optimizer AEO Dashboard CSS */ 2 2 #vnspo-aeo-container { 3 3 padding: 10px 0; -
vn-speed-optimizer/trunk/readme.txt
r3813133 r3847091 5 5 Tested up to: 7.1 6 6 Requires PHP: 8.0 7 Stable tag: 1.2. 17 Stable tag: 1.2.2 8 8 License: GPLv2 or later 9 9 License URI: https://www.gnu.org/licenses/gpl-2.0.html … … 31 31 Community 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. 32 32 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.33 Pro / 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. 34 34 35 35 = Compatibility and verification = … … 49 49 = Setup Wizard = 50 50 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 51 Choose an initial preset: **Safe**, **Balanced**, **Aggressive**, or **WooCommerce**. 56 52 57 53 == Frequently Asked Questions == … … 69 65 Yes. 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. 70 66 71 = Where can I get Pro ? =67 = Where can I get Pro or Agency? = 72 68 73 A separate Pro add-on is planned and is not available yet. See the [product page](https://vn-nexus.com/vnspo-pro). 69 A 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 73 1. Dashboard overview with Cache Hit Rate, server readiness, and Live TTFB Before/After Speed Proof. 74 2. Quick Speed Presets (Safe, Balanced, Aggressive, WooCommerce) and Simple/Advanced controls. 75 3. CSS, JavaScript optimization, media, font, and preload controls. 76 4. Site Diagnostics and Free vs Pro capability overview. 77 5. WooCommerce and dynamic-request bypass status. 78 6. Live LiteSpeed shared-hosting N=15 TTFB and tail-latency benchmark proof (2.81x median speedup, -64.42% TTFB). 79 7. WooCommerce & authenticated 4/4 dynamic bypass verification and WordPress.org Plugin Check (0 errors). 80 8. Closed-loop RUM to PreloadQueue architecture and Free 1.2.2 vs Pro 3.x capability overview. 74 81 75 82 == Changelog == 76 83 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`). 79 88 80 89 == Upgrade Notice == 81 90 82 = 1.2. 0=83 Local-first performance tools with optional, administrator-initiated remote services.91 = 1.2.2 = 92 Adds live site diagnostics, local RUM Auto-Priority Elements, opt-in Speed Radar, Safe-Preview rollback, and WordPress.org compliance hardening. 84 93 85 94 == External Services == … … 87 96 Local 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. 88 97 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 93 101 94 102 = 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/privacy103 * 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 96 104 97 105 = 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/privacy106 * Requested only when a visitor clicks play (video ID + connection metadata). Privacy: https://policies.google.com/privacy | Terms: https://www.youtube.com/t/terms 99 107 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. 103 110 104 111 = 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/privacy112 * Fonts/Analytics load only when enabled by the administrator. Privacy: https://policies.google.com/privacy | Terms: https://policies.google.com/terms 106 113 107 114 = 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/ 109 116 110 117 = 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.php118 * Public URL is sent only when an admin triggers a test. Privacy: https://www.webpagetest.org/privacy.php 112 119 113 120 = 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 116 122 117 123 = Privacy Controls = -
vn-speed-optimizer/trunk/src/Admin/AdminBarWidget.php
r3810859 r3847091 316 316 } 317 317 318 $url = \esc_url_raw($_POST['url'] ?? '');318 $url = isset($_POST['url']) ? \esc_url_raw(\wp_unslash((string) $_POST['url'])) : ''; 319 319 if (empty($url)) { 320 320 \wp_send_json_error(['message' => \__('Invalid URL', 'vn-speed-optimizer')]); -
vn-speed-optimizer/trunk/src/Admin/ConflictManager.php
r3810859 r3847091 68 68 { 69 69 // 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']); 71 74 72 75 // Show admin notice -
vn-speed-optimizer/trunk/src/Core/Application.php
r3810859 r3847091 1 1 <?php 2 2 namespace VNSPO\Core; 3 4 if ( ! defined( 'ABSPATH' ) ) { 5 exit; 6 } 3 7 4 8 /** -
vn-speed-optimizer/trunk/src/Core/Container.php
r3813133 r3847091 1 1 <?php 2 2 namespace VNSPO\Core; 3 4 if ( ! defined( 'ABSPATH' ) ) { 5 exit; 6 } 3 7 4 8 /** -
vn-speed-optimizer/trunk/src/Core/Facade.php
r3810859 r3847091 1 1 <?php 2 2 namespace VNSPO\Core; 3 4 if ( ! defined( 'ABSPATH' ) ) { 5 exit; 6 } 3 7 4 8 /** -
vn-speed-optimizer/trunk/src/Core/ServiceProvider.php
r3810859 r3847091 1 1 <?php 2 2 namespace VNSPO\Core; 3 4 if ( ! defined( 'ABSPATH' ) ) { 5 exit; 6 } 3 7 4 8 /** -
vn-speed-optimizer/trunk/src/Facades/Speed.php
r3456323 r3847091 2 2 3 3 namespace VNSPO\Facades; 4 5 if ( ! defined( 'ABSPATH' ) ) { 6 exit; 7 } 4 8 5 9 use VNSPO\Core\Facade; -
vn-speed-optimizer/trunk/src/Providers/AIServiceProvider.php
r3813133 r3847091 4 4 5 5 use VNSPO\Core\ServiceProvider; 6 use VNSPO\Services\AI\SmartEyes;7 use VNSPO\Services\AI\NeuralCore;8 6 use VNSPO\Services\SEO\AeoFrontend; 9 7 … … 13 11 14 12 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 28 13 $this->app->singleton( 'aeo.frontend', function () { 29 14 $aeo = new AeoFrontend(); … … 34 19 35 20 public function boot() { 36 37 21 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 }69 22 70 23 // AEO Frontend (answer engine markup). -
vn-speed-optimizer/trunk/src/Providers/AdminServiceProvider.php
r3813133 r3847091 2 2 3 3 namespace VNSPO\Providers; 4 5 if ( ! defined( 'ABSPATH' ) ) { 6 exit; 7 } 4 8 5 9 use VNSPO\Core\ServiceProvider; -
vn-speed-optimizer/trunk/src/Providers/MainServiceProvider.php
r3810859 r3847091 63 63 64 64 $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 } 65 71 return new \VNSPO\Services\Optimization\Tweaks\PreconnectHints(); 66 72 } ); … … 159 165 160 166 $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(); 162 171 } ); 163 172 … … 220 229 } 221 230 } 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 } 223 235 } 224 236 } ); … … 245 257 // ── AI + Image ──────────────────────────────────────────────────────── 246 258 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 () { 251 260 return null; 252 261 } ); 253 262 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 () { 258 264 return null; 259 265 } ); … … 418 424 $this->app->make( 'ObjectCache' ); 419 425 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 431 426 // Legacy R2 mirroring is intentionally not booted in the WordPress.org build. 432 427 // Public sharing runs through PublicAssetSharing after per-file selection and consent. -
vn-speed-optimizer/trunk/src/Providers/OptimizationServiceProvider.php
r3813133 r3847091 509 509 \add_action( 'wp_enqueue_scripts', function () { 510 510 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' ); 511 513 \wp_enqueue_script( 512 514 'vnspo-admin-tracker', 513 VNSPEED_PLUGIN_URL. 'assets/js/admin-tracker.js',515 $plugin_url . 'assets/js/admin-tracker.js', 514 516 array( 'jquery' ), 515 VNSPEED_VERSION,517 $version, 516 518 true 517 519 ); -
vn-speed-optimizer/trunk/src/Providers/PageSpeedOptimizationProvider.php
r3810859 r3847091 62 62 $this->try_singleton( 'speculation_optimizer', 'VNSPO\\Services\\Optimization\\SpeculationRulesOptimizer' ); 63 63 $this->try_singleton( 'edge_cache_optimizer', 'VNSPO\\Services\\Optimization\\EdgeCacheOptimizer' ); 64 $this->try_singleton( 'adaptive_engine', 'VNSPO\\Services\\Optimization\\AdaptiveEngine' );65 64 $this->try_singleton( 'semantic_cache', 'VNSPO\\Services\\Optimization\\SemanticCacheLayer' ); 66 65 $this->try_singleton( 'bot_intel', 'VNSPO\\Services\\Optimization\\BotIntelligence' ); … … 108 107 $this->safe_boot( 'speculation_optimizer', $on( 'speculation_enabled' ) ); 109 108 $this->safe_boot( 'edge_cache_optimizer', $on( 'edge_cache_enabled' ) ); 110 $this->safe_boot( 'adaptive_engine', $on( 'adaptive_engine_enabled' ) );111 109 $this->safe_boot( 'semantic_cache', $on( 'semantic_cache_enabled' ) ); 112 110 $this->safe_boot( 'bot_intel', $on( 'bot_intel_enabled' ) ); … … 141 139 } 142 140 } 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 } 144 145 } 145 146 } … … 166 167 } 167 168 } 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 } 169 173 } 170 174 } -
vn-speed-optimizer/trunk/src/Services/AI/ReviewQueue.php
r3810859 r3847091 117 117 { 118 118 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); 121 122 \wp_localize_script('vnspeed-safe-preview', 'vnspoSafePreview', [ 122 123 'ajaxUrl' => \admin_url('admin-ajax.php'), … … 564 565 { 565 566 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); 567 570 $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>'; 568 571 $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 14 14 class AdminPage 15 15 { 16 use AdminPageTabsTrait; 17 16 18 private $tabs = array( 17 19 'dashboard' => 'Dashboard', … … 34 36 /** 35 37 * Get all option keys from OptionsRegistry. 36 * This replaces the hardcoded$all_options array.38 * This replaces the static $all_options array. 37 39 * 38 40 * @return array … … 121 123 \add_action('wp_ajax_vnspo_rum_beacon', array($this, 'ajaxRumBeacon')); 122 124 \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')); 123 132 \add_action('wp_footer', array($this, 'renderFrontendRumBeacon'), 99); 124 133 \add_action('vnspo_ota_policy_cron', array($this, 'syncOtaPolicyFromEdge')); … … 131 140 public function addAdminMenu() 132 141 { 142 $menu_title = (string) \apply_filters('vnspo_menu_title', __('VN Speed Optimizer', 'vn-speed-optimizer')); 133 143 \add_menu_page( 134 __('VN Speed Optimizer', 'vn-speed-optimizer'),135 __('VN Speed Optimizer', 'vn-speed-optimizer'),144 $menu_title, 145 $menu_title, 136 146 'manage_options', 137 147 'vn-speed-optimizer', … … 244 254 // string — select, text, textarea 245 255 $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])) 247 257 : (isset($def['default']) ? $def['default'] : ''); 248 258 } … … 373 383 374 384 $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 } 375 388 376 389 // Handle special options & keep community opt-in state mirrored cleanly … … 382 395 383 396 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 }389 397 \delete_transient('vnspo_community_mesh_status_v3'); 390 398 } … … 979 987 980 988 /** 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 /** 981 999 * Measure real multi-page TTFB: Origin (nocache) vs Warm Cache (2nd hit). 982 1000 */ … … 993 1011 $sum_origin = 0; 994 1012 $sum_cached = 0; 1013 $last_cache_header = ''; 1014 $last_vary_header = ''; 1015 $sum_origin_bytes = 0; 1016 $sum_cached_bytes = 0; 995 1017 996 1018 foreach ($targets as $target) { … … 1009 1031 continue; 1010 1032 } 1033 $origin_bytes = strlen((string) \wp_remote_retrieve_body($res_origin)); 1011 1034 1012 1035 // Warm once then measure cached hit … … 1018 1041 continue; 1019 1042 } 1043 $cached_bytes = strlen((string) \wp_remote_retrieve_body($res_cached)); 1020 1044 1021 1045 $vnspo_hdr = (string) \wp_remote_retrieve_header($res_cached, 'x-vnspo-cache'); 1022 1046 $ls_hdr = (string) \wp_remote_retrieve_header($res_cached, 'x-litespeed-cache'); 1023 1047 $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 } 1027 1057 1028 1058 $saved = max(0, $origin_ms - $cached_ms); … … 1034 1064 'origin_ms' => $origin_ms, 1035 1065 'cached_ms' => $cached_ms, 1066 'origin_bytes' => $origin_bytes, 1067 'cached_bytes' => $cached_bytes, 1036 1068 'improvement_pct' => $pct, 1037 1069 'cache_hit' => $cache_hit, 1038 'cache_header' => $ vnspo_hdr ?: ($ls_hdr ?: $cf_hdr),1070 'cache_header' => $resolved_hdr, 1039 1071 ); 1040 1072 $sum_origin += $origin_ms; 1041 1073 $sum_cached += $cached_ms; 1074 $sum_origin_bytes += $origin_bytes; 1075 $sum_cached_bytes += $cached_bytes; 1042 1076 } 1043 1077 … … 1051 1085 $saved_ms = max(0, $avg_origin_ms - $avg_cached_ms); 1052 1086 $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; 1053 1088 1054 1089 $options = \get_option('vnspo_options', array()); … … 1062 1097 'saved_ms' => $saved_ms, 1063 1098 '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), 1064 1104 'pages_count' => $count, 1065 1105 'pages' => $pages, … … 1113 1153 if ('toplevel_page_vn-speed-optimizer' !== $hook) return; 1114 1154 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'); 1118 1160 1119 1161 \wp_enqueue_style( 1120 1162 'vnspo-admin-css', 1121 VNSPEED_PLUGIN_URL. 'assets/admin.css',1163 $plugin_url . 'assets/admin.css', 1122 1164 array(), 1123 1165 $css_ver … … 1126 1168 \wp_enqueue_script( 1127 1169 'vnspo-admin-js', 1128 VNSPEED_PLUGIN_URL. 'assets/admin.js',1170 $plugin_url . 'assets/admin.js', 1129 1171 array('jquery'), 1130 1172 $js_ver, … … 1191 1233 $db_size = $this->getDatabaseSizeMb(); 1192 1234 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'); 1194 1238 $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') 1196 1240 : 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'; 1198 1242 $supported_langs = array('en', 'vi', 'de', 'fr', 'es', 'ja'); 1199 1243 $forced_lang = (\function_exists('get_current_user_id') && \get_current_user_id() > 0) … … 1241 1285 </svg> 1242 1286 </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 ?> 1243 1296 <div> 1244 1297 <h1 class="vnspo-title" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;"> 1245 VN Speed Optimizer1298 <?php echo esc_html($brand_name); ?> 1246 1299 <?php if ($pro_licensed) : ?> 1247 1300 <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> … … 1251 1304 </h1> 1252 1305 <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); ?> 1256 1307 </p> 1257 1308 </div> 1258 1309 </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 ?> 1259 1316 <div class="vnspo-header-actions"> 1260 1317 <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> 1261 1323 <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'); ?>"> 1262 1324 <?php foreach ($supported_langs as $lang_slug) : … … 1276 1338 <?php echo esc_html__('Recommended Setup', 'vn-speed-optimizer'); ?> 1277 1339 </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; ?> 1278 1383 </div> 1279 1384 </div> … … 1300 1405 break; 1301 1406 } 1407 } 1408 if ('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 ); 1302 1417 } 1303 1418 ?> … … 1389 1504 echo $this->renderProComparisonAndPlans('VI' === $language_code); ?> 1390 1505 <?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> 1391 1620 <?php endif; ?> 1392 1621 <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Rendered with internal escaping. … … 1396 1625 <!-- FOOTER --> 1397 1626 <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> 1399 1628 <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>·</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>·</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; ?> 1403 1636 </div> 1404 1637 </div> … … 1446 1679 }).always(function() { 1447 1680 $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); 1448 1733 }); 1449 1734 }); … … 1623 1908 }); 1624 1909 html += '</tbody></table></div>'; 1910 <?php if (! $hide_vendor_links) : ?> 1625 1911 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);">' + 1626 1912 '<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 & 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>' + 1628 1914 '</div>'; 1915 <?php endif; ?> 1629 1916 $out.html(html); 1630 1917 }).fail(function() { … … 1852 2139 function showNotice(msg, type) { 1853 2140 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 || '')); 1855 2142 $('.vnspo-wrap').prepend($n); 1856 2143 setTimeout(function() { $n.fadeOut(300, function() { $(this).remove(); }); }, 3000); … … 1861 2148 $(this).next('.vnspo-card-body').slideToggle(200); 1862 2149 $(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 }); 1863 2236 }); 1864 2237 })(jQuery); … … 1931 2304 private function renderProComparisonAndPlans($is_vi) 1932 2305 { 2306 if ((bool) \apply_filters('vnspo_hide_vendor_links', false)) { 2307 return ''; 2308 } 2309 1933 2310 $is_pro_active = (bool) \apply_filters('vnspo_is_pro_active', false); 1934 2311 if ($is_pro_active) { … … 1938 2315 : 'Your Pro license is active on this website. Extended modules (Bulk AVIF, RUCSS, Smart Delay JS, SEO & Ads Booster) are enabled.'; 1939 2316 } 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'; 1941 2318 $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'; 1946 2372 1947 2373 ob_start(); … … 1950 2376 <h2 id="vnspo-plans-title"><?php echo esc_html($title); ?></h2> 1951 2377 <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> 1953 2432 </section> 1954 2433 <?php … … 1971 2450 return '<div class="vnspo-row">' . 1972 2451 '<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>' . 1974 2453 '<span class="vnspo-row-desc">' . esc_html($this->tr($desc)) . '</span>' . 1975 2454 '</div>' . 1976 2455 '<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 . '>' . 1978 2457 '<span class="vnspo-slider"></span>' . 1979 2458 '</label>' . … … 1987 2466 return '<div class="vnspo-row">' . 1988 2467 '<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>' . 1990 2469 '<span class="vnspo-row-desc">' . esc_html($this->tr($desc)) . '</span>' . 1991 2470 '</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) . '" ' . 1994 2473 'class="vnspo-number-input" style="width:80px;padding:4px 8px;border:1px solid var(--v-border);border-radius:6px;">' . 1995 2474 '</div>'; … … 2003 2482 return '<div class="vnspo-row">' . 2004 2483 '<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>' . 2006 2485 '<span class="vnspo-row-desc">' . esc_html($this->tr($desc)) . '</span>' . 2007 2486 '</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) . '" ' . 2009 2488 'value="' . esc_attr($value) . '" placeholder="' . esc_attr($placeholder) . '" ' . 2010 2489 'class="vnspo-input" style="min-width:260px;max-width:360px;padding:6px 10px;border:1px solid var(--v-border);border-radius:6px;">' . … … 2029 2508 } 2030 2509 2031 private function tabDashboard($options)2032 {2033 // Use new Dashboard V22034 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_licensed2202 ? __('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 class2282 $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_active2384 ? __('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 list2557 $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 !== null2572 && 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' !== $code2591 ? $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 <?php2630 $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_vi2633 ? '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_vi2637 ? 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 <?php2714 echo $has_live_nodes2715 ? 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 <?php2724 $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 <?php2731 $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_active2739 ? ($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 <?php2764 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_ttfb2898 ? ((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_active2903 ? __('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 <?php2944 /* 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 <?php2952 // 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 <?php2983 return ob_get_clean();2984 }2985 2986 /**2987 * Dashboard V2 - Premium SaaS-grade layout2988 */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 <?php3060 /* 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 <?php3093 $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 <?php3111 $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_ttfb3147 ? 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_active3177 ? 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_active3182 ? 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 <?php3289 return ob_get_clean();3290 }3291 3292 /**3293 * Get score grade letter3294 */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 class3306 */3307 private function getScoreGradeClass($grade)3308 {3309 return 'vnspo-grade-' . strtolower($grade);3310 }3311 3312 /**3313 * Get score ring SVG color3314 */3315 private function getScoreRingColor($score)3316 {3317 if ($score >= 70) return '#2563eb'; // Blue3318 return '#dc2626'; // Red3319 }3320 3321 /**3322 * Generate metric card HTML3323 */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 HTML3352 */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 HTML3374 */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 3401 2510 /** 3402 2511 * AJAX: Manually sync OTA JSON exclusions/policy from VN-Nexus Edge. … … 3432 2541 'timeout' => 4, 3433 2542 'sslverify' => true, 3434 'user-agent' => 'VN-Speed-Optimizer/' . (\defined('VNSP EED_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')), 3435 2544 )); 3436 2545 … … 3506 2615 \update_option('vnspo_rum_lcp_ms', $next, false); 3507 2616 \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)); 3509 2863 } 3510 2864 } -
vn-speed-optimizer/trunk/src/Services/Admin/CloudflarePairingController.php
r3810859 r3847091 131 131 $metricsConsent = $this->client->getMetricsConsent(); 132 132 $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'); 134 135 135 136 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); 137 138 } 138 139 -
vn-speed-optimizer/trunk/src/Services/Admin/PublicAssetSharing.php
r3810859 r3847091 51 51 if ('vn-speed-optimizer_page_vnspo-public-assets' !== $hook) return; 52 52 \wp_enqueue_media(); 53 $version = \defined('VNSP EED_VERSION') ? VNSPEED_VERSION : '1.0.0';54 $baseUrl = \defined('VNSP EED_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 : ''); 55 55 \wp_enqueue_script( 56 56 'vnspo-public-assets', -
vn-speed-optimizer/trunk/src/Services/Admin/SetupWizard.php
r3810859 r3847091 39 39 'heartbeat_control' => 'limit', 40 40 ], 41 'expected_lcp' => ' -15%',42 'expected_tti' => ' -10%',41 'expected_lcp' => 'Measure live', 42 'expected_tti' => 'Safe scope', 43 43 ], 44 44 'balanced' => [ … … 56 56 'auto_meta_desc' => 1, 57 57 ], 58 'expected_lcp' => ' -40%',59 'expected_tti' => ' -35%',58 'expected_lcp' => 'Measure live', 59 'expected_tti' => 'Balanced scope', 60 60 ], 61 61 'aggressive' => [ … … 77 77 'preload_lcp' => 1, 78 78 ], 79 'expected_lcp' => ' -60%',80 'expected_tti' => ' -50%',79 'expected_lcp' => 'Measure live', 80 'expected_tti' => 'Full scope', 81 81 ], 82 82 ]; … … 122 122 // Output a standalone HTML page with all required assets inline. 123 123 // 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' ); 128 129 $wizard_data = [ 129 130 'ajaxUrl' => $ajax_url, … … 329 330 <div class="vnspo-preset" data-preset="<?php echo esc_attr($key); ?>"> 330 331 <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> 332 333 <p><?php echo esc_html($preset['desc']); ?></p> 333 334 </div> … … 420 421 </div> 421 422 <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;"> 423 424 <?php echo esc_html__('Explore Pro Early Access', 'vn-speed-optimizer'); ?> 424 425 </a> … … 450 451 </div> 451 452 <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">—</span> 454 <span class="label"><?php echo esc_html__('Run real Speed Proof on Dashboard', 'vn-speed-optimizer'); ?></span> 454 455 </div> 455 456 </div> 456 457 457 458 <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"> 459 460 📊 View Dashboard 460 461 </a> -
vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/BaseComponent.php
r3810859 r3847091 1 1 <?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 */ 2 2 namespace VNSPO\Services\Admin\Views\Components; 3 if ( ! defined( 'ABSPATH' ) ) { exit; } 3 4 abstract class BaseComponent { 4 5 /** * Plugin options array * * @var array */ -
vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/Input.php
r3810859 r3847091 1 1 <?php /** * Input Component * * Renders a text input field with label and description. * * @package VNSPO\Services\Admin\Views\Components * @since 1.1.0 */ 2 2 namespace VNSPO\Services\Admin\Views\Components; 3 if ( ! defined( 'ABSPATH' ) ) { exit; } 3 4 class Input extends BaseComponent { 4 5 /** * Component configuration * * @var array */ -
vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/Textarea.php
r3810859 r3847091 1 1 <?php /** * Textarea Component * * Renders a textarea input with label and description. * * @package VNSPO\Services\Admin\Views\Components * @since 1.1.0 */ 2 2 namespace VNSPO\Services\Admin\Views\Components; 3 if ( ! defined( 'ABSPATH' ) ) { exit; } 3 4 class Textarea extends BaseComponent { 4 5 /** * Component configuration * * @var array */ -
vn-speed-optimizer/trunk/src/Services/Admin/Views/Components/Toggle.php
r3810859 r3847091 1 1 <?php /** * Toggle Component * * Renders a checkbox toggle with label and description. * * @package VNSPO\Services\Admin\Views\Components * @since 1.1.0 */ 2 2 namespace VNSPO\Services\Admin\Views\Components; 3 if ( ! defined( 'ABSPATH' ) ) { exit; } 3 4 class Toggle extends BaseComponent { 4 5 /** * Component configuration * * @var array */ -
vn-speed-optimizer/trunk/src/Services/Analytics/PerformanceMonitor.php
r3810859 r3847091 296 296 297 297 /** 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 /** 298 320 * Record real browser CWV beacon into local performance history. 299 321 */ … … 343 365 } 344 366 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 345 399 $history = get_option(self::HISTORY_OPTION, []); 346 400 if (!is_array($history)) { -
vn-speed-optimizer/trunk/src/Services/Cloud/AggregateMetricsSender.php
r3810859 r3847091 91 91 $aggregate = [ 92 92 'period_start' => (int) (\floor(\time() / 86400) * 86400), 93 'plugin_version' => \defined('VNSP EED_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'), 94 94 // This is one smoothed site-level LCP summary, not an individual visit record. 95 95 'lcp_ms' => $lcpMs, -
vn-speed-optimizer/trunk/src/Services/Cloud/BrainClient.php
r3810859 r3847091 6 6 7 7 /** 8 * Server-to-server client for the private VN-Nexus Qwenrecommendation API.8 * Server-to-server client for the optional VN-Nexus Edge recommendation API. 9 9 * Credentials stay in WordPress options and are never exposed to browser code. 10 10 */ … … 157 157 if ('disconnect' === $operation) return ['contract_version' => 1, 'status' => 'disconnected', 'google_grant_revoked' => false]; 158 158 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')); 160 160 $drafts = []; 161 161 foreach (\array_slice($data['drafts'], 0, 5) as $draft) { … … 581 581 'pairing_code' => $pairingCode, 582 582 'site_ref' => $siteRef, 583 'plugin_version' => \defined('VNSP EED_VERSION') ? VNSPEED_VERSION : '0.0.0',583 'plugin_version' => \defined('VNSPO_VERSION') ? VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '0.0.0'), 584 584 ]), 585 585 ]); … … 744 744 745 745 /** 746 * Backward-compatible method used by NeuralCore and other existingcallers.746 * Backward-compatible method used by legacy review callers. 747 747 */ 748 748 public function evaluate(array $payload, string $reason = 'background'): array … … 765 765 } 766 766 767 // NeuralCore treats ai_rules as an informational snapshot and storesit767 // Legacy callers treat ai_rules as an informational snapshot and store it 768 768 // for the administrator; it does not apply arbitrary remote settings. 769 769 $policy['ai_rules'] = $policy['recommendations'] ?? []; … … 779 779 } 780 780 781 // Bridge only recommendations with exact, pre-existing AIAutoPilot-safe values.781 // Bridge only recommendations with exact, pre-existing safe local keys. 782 782 $safeFixes = [ 783 783 'critical_css' => ['fix' => 'critical_css_enabled', 'value' => true], … … 803 803 private function remotePost(string $url, array $args) 804 804 { 805 $version = \defined('VNSP EED_VERSION') ? (string) VNSPEED_VERSION : '1.2.0';805 $version = \defined('VNSPO_VERSION') ? (string) VNSPO_VERSION : (\defined('VNSPEED_VERSION') ? (string) VNSPEED_VERSION : '1.2.2'); 806 806 $args['user-agent'] = 'VN-Speed-Optimizer/' . $version; 807 807 return \wp_remote_post($url, $args); -
vn-speed-optimizer/trunk/src/Services/Core/BaseService.php
r3810859 r3847091 121 121 protected function log($message, $context = array()) 122 122 { 123 if (! WP_DEBUG|| ! WP_DEBUG_LOG) {123 if (! defined('WP_DEBUG') || ! WP_DEBUG || ! defined('WP_DEBUG_LOG') || ! WP_DEBUG_LOG) { 124 124 return; 125 125 } … … 297 297 $real_allowed = \realpath($allowed_dir); 298 298 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); 301 300 return false; 302 301 } … … 311 310 // Directory doesn't exist - try to create it 312 311 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); 315 313 return false; 316 314 } … … 318 316 } 319 317 320 if (\strpos($real_dir, $real_allowed) !== 0) {321 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log322 \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; 327 325 328 326 // ✅ 3. Check for symlink attacks 329 327 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); 332 329 return false; 333 330 } … … 340 337 $bytes = \file_put_contents($temp, $content, LOCK_EX); 341 338 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); 344 340 return false; 345 341 } … … 354 350 // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink 355 351 \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); 358 353 return false; 359 354 } -
vn-speed-optimizer/trunk/src/Services/Database/DatabaseCleanup.php
r3810859 r3847091 12 12 * Handles database optimization: revisions, auto-drafts, trashed posts, 13 13 * spam comments, trashed comments, transients, and table optimization. 14 * Mirrors WP Rocket's Optimization class (inc/Engine/Admin/Database/Optimization.php).15 14 * 16 15 * @since 1.3.0 -
vn-speed-optimizer/trunk/src/Services/Database/DatabaseCleanupProcess.php
r3810859 r3847091 12 12 * Background async processor for database cleanup tasks. 13 13 * Runs each cleanup type as a separate async batch to avoid timeout. 14 * Mirrors WP Rocket's OptimizationProcess.15 14 * 16 15 * @since 1.3.0 -
vn-speed-optimizer/trunk/src/Services/Database/ObjectCache.php
r3810859 r3847091 45 45 46 46 /** 47 * Detect a working local Redis Unix socket (AZDIGI/cPanel)or TCP endpoint.47 * Detect a working local Redis Unix socket or TCP endpoint. 48 48 * 49 49 * @return array{host:string,port:int}|null … … 126 126 } 127 127 128 $base_path = defined('VNSP EED_PATH') ? VNSPEED_PATH : dirname(__DIR__, 3) . '/';128 $base_path = defined('VNSPO_PATH') ? VNSPO_PATH : (defined('VNSPEED_PATH') ? VNSPEED_PATH : dirname(__DIR__, 3) . '/'); 129 129 $source = trailingslashit($base_path) . 'src/Templates/object-cache.php'; 130 130 $dest = WP_CONTENT_DIR . '/object-cache.php'; -
vn-speed-optimizer/trunk/src/Services/Edge/AdvancedPerformance.php
r3810859 r3847091 13 13 14 14 namespace VNSPO\Services\Edge; 15 16 if ( ! defined( 'ABSPATH' ) ) { 17 exit; 18 } 15 19 16 20 class AdvancedPerformance … … 334 338 // Client Hints (modern browsers) 335 339 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'; 337 345 } 338 346 … … 342 350 } 343 351 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 } 345 356 $mobile_regex = '/(android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i'; 346 357 -
vn-speed-optimizer/trunk/src/Services/Edge/AjaxHandlers.php
r3810859 r3847091 98 98 } 99 99 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)); 101 102 102 103 // Use injected optimizer or fallback (for now, but we will inject it) -
vn-speed-optimizer/trunk/src/Services/Media/AvatarAltText.php
r3456323 r3847091 4 4 * AvatarAltText Service 5 5 * 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. 8 7 * 9 8 * @package VNSPO -
vn-speed-optimizer/trunk/src/Services/Media/ImageDimensionsFixer.php
r3810859 r3847091 633 633 private function getAttributePlaceholder() 634 634 { 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' 637 638 : ''; 638 639 } -
vn-speed-optimizer/trunk/src/Services/Media/LQIPPlaceholderHelpers.php
r3810859 r3847091 21 21 private function getAttributePlaceholder() 22 22 { 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' 25 26 : 'data:image/svg+xml;base64,' . base64_encode('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>'); 26 27 } -
vn-speed-optimizer/trunk/src/Services/Media/WebPConverterService.php
r3810859 r3847091 81 81 return true; 82 82 } 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 } 84 87 } 85 88 } … … 100 103 return true; 101 104 } 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 } 103 109 } 104 110 } -
vn-speed-optimizer/trunk/src/Services/Media/YouTubeLazyLoad.php
r3810859 r3847091 93 93 94 94 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'); 95 98 \wp_enqueue_style( 96 99 'vnspo-youtube-lazy', 97 VNSPEED_PLUGIN_URL. 'assets/css/youtube-lazy.css',100 $plugin_url . 'assets/css/youtube-lazy.css', 98 101 array(), 99 VNSPEED_VERSION102 $version 100 103 ); 101 104 102 105 // 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'; 104 107 if (file_exists($script_path)) { 105 108 \wp_enqueue_script( 106 109 'vnspo-youtube-lazy', 107 VNSPEED_PLUGIN_URL. 'assets/js/youtube-lazy.js',110 $plugin_url . 'assets/js/youtube-lazy.js', 108 111 array(), 109 VNSPEED_VERSION,112 $version, 110 113 true 111 114 ); -
vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetCombiner.php
r3810859 r3847091 348 348 // Generate cache filename with version hash 349 349 $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'); 351 351 $filename = "{$type}-{$hash}-v{$version}.{$type}"; 352 352 $dir = $this->getCacheDir(); -
vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetLocalizer.php
r3456323 r3847091 78 78 { 79 79 $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'])) { 81 82 return false; 82 83 } 83 84 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) { 88 87 return false; 89 88 } 90 89 91 // Whitelist allowed domains90 // Strict exact or subdomain match against whitelisted domains before any DNS resolution. 92 91 $allowed_domains = array( 93 92 'googletagmanager.com', … … 96 95 ); 97 96 97 $domain_allowed = false; 98 98 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; 101 103 } 102 104 } 103 105 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; 106 135 } 107 136 -
vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetManager.php
r3810859 r3847091 593 593 } 594 594 // 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 } 596 599 } 597 600 -
vn-speed-optimizer/trunk/src/Services/Optimization/Assets/AssetOptimizer.php
r3810859 r3847091 152 152 if ($critical_css && $this->containsMaliciousContent($critical_css)) { 153 153 $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 } 155 158 } 156 159 } … … 171 174 } 172 175 173 \wp_register_style('vnspo-critical', false );176 \wp_register_style('vnspo-critical', false, array(), defined('VNSPO_VERSION') ? VNSPO_VERSION : '1.2.2'); 174 177 \wp_enqueue_style('vnspo-critical'); 175 178 -
vn-speed-optimizer/trunk/src/Services/Optimization/Assets/DelayJsConfig.php
r3810859 r3847091 13 13 class DelayJsConfig 14 14 { 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 15 39 public static function get_exclusions() 16 40 { … … 91 115 ]; 92 116 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 93 138 $policy = (new \VNSPO\Services\Cloud\PolicyStore())->getSection('delay_js_exclusions'); 94 139 foreach ($policy as $pattern) { … … 104 149 { 105 150 $exclusions = self::get_exclusions(); 151 $handle = (string) $handle; 152 $src = (string) $src; 106 153 107 154 foreach ($exclusions as $pattern) { 108 $pattern = trim($pattern, '/'); 155 $pattern = trim((string) $pattern, '/'); 156 if ('' === $pattern) { 157 continue; 158 } 109 159 110 160 if (stripos($handle, $pattern) !== false || stripos($src, $pattern) !== false) { -
vn-speed-optimizer/trunk/src/Services/Optimization/Assets/EnhancedLazyLoadScript.php
r3810859 r3847091 273 273 private function getAttributePlaceholder() 274 274 { 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' 277 278 : $this->getPlaceholder(array()); 278 279 } -
vn-speed-optimizer/trunk/src/Services/Optimization/Assets/InteractionDelay.php
r3810859 r3847091 172 172 private function get_loader_script() 173 173 { 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 174 178 return " 175 179 <script> … … 191 195 } 192 196 events.forEach(function(e) { window.addEventListener(e, loadScripts, {passive: true, once: true}); }); 197 setTimeout(loadScripts, " . $timeout_ms . "); 193 198 })(); 194 199 </script>"; -
vn-speed-optimizer/trunk/src/Services/Optimization/CLSOptimizer.php
r3810859 r3847091 213 213 */ 214 214 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 215 222 $options = \get_option('vnspo_options', []); 216 223 if (empty($options['rum_enabled'])) { -
vn-speed-optimizer/trunk/src/Services/Optimization/Cache/ConfigGenerator.php
r3810859 r3847091 127 127 // URL no-dots mode (shared hosting) 128 128 if (apply_filters('vnspo_url_no_dots', false)) { 129 $buffer .= "define( 'VNSP EED_URL_NO_DOTS', 1 );\n";129 $buffer .= "define( 'VNSPO_URL_NO_DOTS', 1 );\n"; 130 130 } 131 131 -
vn-speed-optimizer/trunk/src/Services/Optimization/Cache/DropInManager.php
r3810859 r3847091 94 94 95 95 $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 96 119 $config = array( 97 120 'cache_dir' => $cacheDir, … … 99 122 'cache_mobile' => ! empty($options['cache_mobile']), 100 123 'cache_webp' => ! empty($options['cache_webp']), 124 'exclude_uris' => array_values(array_unique($excludeUris)), 101 125 ); 102 126 -
vn-speed-optimizer/trunk/src/Services/Optimization/Cache/MobileCacheManager.php
r3810859 r3847091 10 10 * MobileCacheManager 11 11 * 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: 14 13 * - Separate mobile cache directory 15 14 * - Tablet-aware caching (serve desktop to tablets by default) -
vn-speed-optimizer/trunk/src/Services/Optimization/Cache/PageCacheCompatibility.php
r3810859 r3847091 63 63 } 64 64 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; 66 72 return false !== stripos($server_software, 'litespeed'); 67 73 } -
vn-speed-optimizer/trunk/src/Services/Optimization/Cache/VarnishPurger.php
r3810859 r3847091 11 11 * 12 12 * Sends PURGE requests to Varnish cache servers. 13 * Mirrors WP Rocket's Varnish addon (inc/Addon/Varnish/Varnish.php).14 13 * 15 14 * Features: -
vn-speed-optimizer/trunk/src/Services/Optimization/INPOptimizer.php
r3810859 r3847091 133 133 */ 134 134 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 135 142 $options = \get_option('vnspo_options', []); 136 143 if (empty($options['rum_enabled'])) { -
vn-speed-optimizer/trunk/src/Services/Optimization/Network/BrowserCache.php
r3456323 r3847091 49 49 } 50 50 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 } 54 62 } 55 63 -
vn-speed-optimizer/trunk/src/Services/Optimization/Network/FastLlmsTxt.php
r3810859 r3847091 41 41 } 42 42 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'])) : ''; 44 44 $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 }51 45 52 46 if ($path === '/robots.txt') { -
vn-speed-optimizer/trunk/src/Services/Optimization/Network/SmartPrefetch.php
r3810859 r3847091 10 10 * Prefetches links likely to be clicked next, reducing perceived latency. 11 11 * 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. 14 13 * 15 14 * Features: … … 77 76 \add_action('admin_menu', array($this, 'addAdminMenu'), 100); 78 77 \add_action('wp_ajax_vnspo_prefetch_stats', array($this, 'ajaxPrefetchStats')); 78 \add_action('wp_ajax_nopriv_vnspo_prefetch_stats', array($this, 'ajaxPrefetchStats')); 79 79 return; 80 80 } … … 111 111 } 112 112 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'); 113 115 \wp_enqueue_script( 114 116 'vnspo-smart-prefetch', 115 VNSPEED_PLUGIN_URL. 'assets/js/vn-spo-prefetch.js',117 $plugin_url . 'assets/js/vn-spo-prefetch.js', 116 118 array(), 117 VNSPEED_VERSION,119 $version, 118 120 true 119 121 ); … … 318 320 private function supportsSpeculationRules() 319 321 { 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); 322 330 } 323 331 … … 348 356 \set_transient($rate_key, $current_rate + 1, MINUTE_IN_SECONDS); 349 357 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'])) : ''; 352 360 $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'])) : ''; 354 362 355 363 if (empty($url)) { -
vn-speed-optimizer/trunk/src/Services/Optimization/Network/SpeculationRules.php
r3810859 r3847091 35 35 */ 36 36 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() ) ) { 39 42 return; 40 43 } 41 44 \define( 'VNSPO_SPECULATION_INJECTED', true ); 42 45 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 52 63 $rules = array( 53 64 'prefetch' => array( 54 65 array( 55 66 '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 ), 65 68 'eagerness' => 'moderate', 66 69 ), … … 69 72 array( 70 73 '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 ), 80 75 'eagerness' => 'moderate', 81 76 ), -
vn-speed-optimizer/trunk/src/Services/Optimization/Preload/PreloadQueue.php
r3810859 r3847091 70 70 */ 71 71 private function ensureQueueTable() { 72 if (function_exists('get_option') && get_option('vnspo_preload_queue_table_created')) { 73 return; 74 } 75 72 76 global $wpdb; 73 77 … … 125 129 // Option changes that affect sitemap 126 130 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); 127 199 } 128 200 … … 358 430 $table = $wpdb->prefix . 'vnspo_preload_queue'; 359 431 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; 362 435 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared 363 436 $rows = $wpdb->get_results( … … 400 473 401 474 // Perform the preload request 475 $t0 = microtime(true); 402 476 $result = $this->preloadUrl($row['url'], $row['device']); 477 $elapsed = microtime(true) - $t0; 403 478 404 479 if ($result === true) { … … 440 515 $stats['failed']++; 441 516 } 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) 445 525 $remaining = $this->countPending(); 446 526 if ($remaining > 0) { 447 $this->scheduleProcessing( 60); // Process next batch in 60 seconds527 $this->scheduleProcessing($throttled ? 180 : 60); 448 528 } 449 529 -
vn-speed-optimizer/trunk/src/Services/Optimization/System/HtaccessManager.php
r3813133 r3847091 23 23 * - Cache-Control headers for static assets 24 24 * 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. 27 26 * 28 27 * @since 1.3.0 … … 31 30 32 31 /** 33 * Marker comment for WP Rocket-styleblock preservation32 * Marker comment for VNSPO-managed .htaccess block preservation 34 33 */ 35 34 const MARKER_START = '# BEGIN VNSPO'; … … 62 61 */ 63 62 public function syncVersionedRules() { 64 $rules_version = 'server-cache-v 1';63 $rules_version = 'server-cache-v4'; 65 64 if (function_exists('get_option') && $rules_version === get_option('vnspo_htaccess_rules_version', '')) { 66 65 return true; … … 81 80 82 81 if (function_exists('update_option')) { 83 update_option('vnspo_htaccess_rules_version', 'server-cache-v 1', false);82 update_option('vnspo_htaccess_rules_version', 'server-cache-v4', false); 84 83 } 85 84 … … 258 257 } 259 258 260 $version = VNSPEED_VERSION;259 $version = defined('VNSPO_VERSION') ? VNSPO_VERSION : (defined('VNSPEED_VERSION') ? VNSPEED_VERSION : '1.2.2'); 261 260 262 261 $rules = "<IfModule mod_alias.c>\n"; … … 382 381 $rules .= "\t</IfModule>\n"; 383 382 $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"; 385 384 $rules .= "\t</IfModule>\n"; 386 385 $rules .= "</IfModule>\n"; … … 437 436 $rules .= "Header always set X-VNSPO-Cache \"HIT-SERVER\" env=VNSPO_CACHE_HIT\n"; 438 437 $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"; 439 439 $rules .= "Header always set Cache-Control \"public, max-age=0, must-revalidate\" env=REDIRECT_VNSPO_CACHE_HIT\n"; 440 440 $rules .= "</IfModule>\n\n"; … … 444 444 $rules .= "RewriteBase " . $home_root . "\n"; 445 445 446 // Environment-flag rules run first so their RewriteRule directives never consume bypass RewriteConds. 446 447 // SSL 447 448 $rules .= $this->generateSSLRewriteCond(); … … 453 454 454 455 $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"; 460 470 461 471 // Rejected cookies 462 472 $cookies = $this->getRejectedCookies(); 463 473 if ($cookies) { 464 $ rules .= "RewriteCond %{HTTP:Cookie} !(" . $cookies . ") [NC]\n";474 $cache_conds .= "RewriteCond %{HTTP:Cookie} !(" . $cookies . ") [NC]\n"; 465 475 } 466 476 … … 468 478 $protected_paths = $this->getProtectedCachePaths(); 469 479 if ($protected_paths) { 470 $ rules .= "RewriteCond %{REQUEST_URI} !^(?:" . $protected_paths . ") [NC]\n";480 $cache_conds .= "RewriteCond %{REQUEST_URI} !^(?:" . $protected_paths . ") [NC]\n"; 471 481 } 472 482 … … 474 484 $uri = $this->getRejectedUri(); 475 485 if ($uri) { 476 $ rules .= "RewriteCond %{REQUEST_URI} !^(" . $uri . ")$ [NC]\n";477 } 478 479 // Mobile486 $cache_conds .= "RewriteCond %{REQUEST_URI} !^(" . $uri . ")$ [NC]\n"; 487 } 488 489 // Desktop-only UA exclusion when mobile cache is disabled 480 490 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(); 485 492 } 486 493 … … 488 495 $ua = $this->getRejectedUa(); 489 496 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"; 492 501 493 502 $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; 495 504 $rules .= "RewriteCond %{REQUEST_URI} =/\n"; 496 505 $rules .= 'RewriteCond "' . $cache_base_path . '/' . $index_file . '" -f' . "\n"; 497 506 $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"; 500 509 $rules .= 'RewriteCond "' . $cache_base_path . '%{REQUEST_URI}' . $index_file . '" -f' . "\n"; 501 510 $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; 503 512 $rules .= "RewriteCond %{REQUEST_URI} !/$\n"; 504 513 $rules .= 'RewriteCond "' . $cache_base_path . '%{REQUEST_URI}/' . $index_file . '" -f' . "\n"; … … 590 599 'woocommerce_items_in_cart', 591 600 'woocommerce_cart_hash', 601 'woocommerce_recently_viewed', 592 602 'wp_woocommerce_session_', 603 'yith_wcwl_session_', 593 604 'edd_items_in_cart', 594 605 ); … … 655 666 return true; 656 667 } 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; 658 675 return false !== stripos($server_software, 'litespeed'); 659 676 } … … 680 697 '/checkout', 681 698 '/my-account', 699 '/gio-hang', 700 '/thanh-toan', 701 '/tai-khoan', 682 702 ); 683 703 $protected_urls = array( -
vn-speed-optimizer/trunk/src/Services/Optimization/TBTOptimizer.php
r3810859 r3847091 147 147 */ 148 148 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 149 156 $options = \get_option('vnspo_options', []); 150 157 if (empty($options['rum_enabled'])) { -
vn-speed-optimizer/trunk/src/Services/PageCache.php
r3810859 r3847091 445 445 // The default WooCommerce endpoints are known bypasses. Decide these 446 446 // 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)) { 448 448 return false; 449 449 } … … 463 463 $protected_paths = array( 464 464 '/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', 466 467 ); 467 468 $protected_urls = array( … … 499 500 'woocommerce_items_in_cart', 500 501 'woocommerce_cart_hash', 502 'woocommerce_recently_viewed', 501 503 'wp_woocommerce_session_', 504 'yith_wcwl_session_', 502 505 'edd_items_in_cart', 503 506 ); -
vn-speed-optimizer/trunk/src/Services/SEO/AeoFrontend.php
r3810859 r3847091 82 82 \ob_start(); 83 83 ?> 84 <!-- VN -NexusAEO Quick Summary -->84 <!-- VN Speed Optimizer AEO Quick Summary --> 85 85 <section id="vnspo-aeo-summary" aria-label="Quick Summary" data-nosnippet class="vnspo-aeo-box"> 86 86 <div class="vnspo-aeo-header"> -
vn-speed-optimizer/trunk/src/Services/SEO/AeoMetabox.php
r3810859 r3847091 1 1 <?php 2 2 namespace VNSPO\Services\SEO; 3 4 if ( ! defined( 'ABSPATH' ) ) { 5 exit; 6 } 3 7 4 8 class AeoMetabox { … … 24 28 add_meta_box( 25 29 'vnspo_aeo_dashboard', 26 'VN-Nexus AEO Check',30 esc_html__( 'VN Speed Optimizer AEO Check', 'vn-speed-optimizer' ), 27 31 array( $this, 'render_metabox_html' ), 28 32 array( 'post', 'page' ), … … 37 41 } 38 42 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 39 46 wp_enqueue_style( 40 47 'vnspo-aeo-css', 41 VNSPEED_PLUGIN_URL. 'assets/aeo-dashboard.css',48 $plugin_url . 'assets/aeo-dashboard.css', 42 49 array(), 43 VNSPEED_VERSION50 $version 44 51 ); 45 52 46 53 wp_enqueue_script( 47 54 'vnspo-aeo-js', 48 VNSPEED_PLUGIN_URL. 'assets/aeo-dashboard.js',55 $plugin_url . 'assets/aeo-dashboard.js', 49 56 array( 'jquery' ), 50 VNSPEED_VERSION,57 $version, 51 58 true 52 59 ); … … 108 115 } 109 116 110 $content = isset( $_POST['content'] ) ? wp_ unslash( $_POST['content']) : '';117 $content = isset( $_POST['content'] ) ? wp_kses_post( wp_unslash( $_POST['content'] ) ) : ''; 111 118 112 119 $result = $this->perform_aeo_analysis( $content ); … … 133 140 134 141 // 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 } 136 146 } 137 147 } -
vn-speed-optimizer/trunk/src/Services/SEO/RedirectLogger.php
r3456323 r3847091 4 4 * RedirectLogger Service 5 5 * 6 * Logs all redirects with hit count tracking 7 * Inspired by Rank Math Pro redirect logging 6 * Logs all redirects with hit count tracking. 8 7 * 9 8 * @package VNSPO … … 36 35 add_filter('wp_redirect', array($this, 'log_redirect'), 10, 2); 37 36 38 // Create table on activation39 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')); 40 39 } 41 40 … … 45 44 public function maybe_create_table() 46 45 { 46 if (function_exists('get_option') && '1' === (string) get_option('vnspo_redirect_logs_db_ver', '')) { 47 return; 48 } 49 47 50 global $wpdb; 48 51 … … 64 67 require_once ABSPATH . 'wp-admin/includes/upgrade.php'; 65 68 dbDelta($sql); 69 70 if (function_exists('update_option')) { 71 update_option('vnspo_redirect_logs_db_ver', '1', false); 72 } 66 73 } 67 74 … … 79 86 if (empty($options['log_redirects'])) { 80 87 return $location; 88 } 89 90 if (function_exists('get_option') && '1' !== (string) get_option('vnspo_redirect_logs_db_ver', '')) { 91 $this->maybe_create_table(); 81 92 } 82 93 … … 108 119 109 120 /** 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 /** 110 137 * Export redirect logs to CSV 111 138 */ 112 139 public function export_csv() 113 140 { 141 if (! function_exists('current_user_can') || ! current_user_can('manage_options')) { 142 return; 143 } 144 114 145 global $wpdb; 115 146 … … 138 169 // CSV rows 139 170 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); 141 173 } 142 174 -
vn-speed-optimizer/trunk/src/Services/SEO/SchemaStacker.php
r3810859 r3847091 1 1 <?php 2 2 namespace VNSPO\Services\SEO; 3 4 if ( ! defined( 'ABSPATH' ) ) { 5 exit; 6 } 3 7 4 8 class SchemaStacker { … … 87 91 ); 88 92 89 echo "\n<!-- VN -NexusAEO Schema Stacking -->\n";93 echo "\n<!-- VN Speed Optimizer AEO Schema Stacking -->\n"; 90 94 // The escape flags above guarantee no </script> breakout is possible. 91 95 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 63 63 global $wp; 64 64 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'])) : ''; 68 68 69 69 // Get suggestion if available -
vn-speed-optimizer/trunk/src/Services/System/CompatibilityManager.php
r3810859 r3847091 11 11 * 12 12 * Comprehensive 3rd-party plugin and hosting compatibility layer. 13 * Mirrors WP Rocket's 3rd-party compatibility system.14 13 * 15 14 * Handles: -
vn-speed-optimizer/trunk/src/Services/System/Security/ImmutableLog.php
r3810859 r3847091 109 109 private function ensure_table() 110 110 { 111 if (function_exists('get_option') && get_option('vnspo_immutable_log_table_created')) { 112 return; 113 } 114 111 115 global $wpdb; 112 116 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching … … 127 131 dbDelta($sql); 128 132 } 133 134 if (function_exists('update_option')) { 135 update_option('vnspo_immutable_log_table_created', 1, false); 136 } 129 137 } 130 138 } -
vn-speed-optimizer/trunk/src/Templates/advanced-cache.php
r3810859 r3847091 13 13 if (! function_exists('vnspo_serve_advanced_cache')) { 14 14 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); 19 21 20 22 $rawUri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '/'; … … 60 62 'woocommerce_items_in_cart' === $name || 61 63 '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_') 63 67 ) { 64 68 return; … … 99 103 ); 100 104 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 ); 105 123 106 124 $configFile = defined('WP_CONTENT_DIR') ? rtrim(WP_CONTENT_DIR, '/\\') . '/vnspo-config/advanced-cache-config.php' : ''; … … 116 134 $useMobile = ! empty($cfg['cache_mobile']); 117 135 $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; 118 153 } 119 154 } … … 142 177 return; 143 178 } 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) . '"'; 146 185 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim((string) $_SERVER['HTTP_IF_NONE_MATCH']) === $etag) { 147 186 header('HTTP/1.1 304 Not Modified'); 187 header('Cache-Control: public, max-age=0, must-revalidate'); 148 188 header('X-VNSPO-Cache: HIT-DROPIN'); 189 header('X-VNSPO-Dropin-Ms: ' . $dropinMs); 149 190 exit; 150 191 } 151 192 152 193 $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'; 163 196 164 197 header('Content-Type: text/html; charset=UTF-8'); 198 header('Cache-Control: public, max-age=0, must-revalidate'); 199 header('Vary: Accept-Encoding'); 165 200 header('ETag: ' . $etag); 166 201 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 167 219 /* phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile */ readfile($realFile); 168 220 exit; -
vn-speed-optimizer/trunk/uninstall.php
r3810859 r3847091 24 24 global $wpdb; 25 25 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). 27 27 $wpdb->query( 28 28 $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_' ) . '%' 31 32 ) 32 33 ); 33 34 $wpdb->query( 34 35 $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", 36 37 $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_' ) . '%' 38 41 ) 39 42 ); 40 43 41 // 2. Multisite support — also clean sitemeta if present.44 // 2. Multisite support — also clean sitemeta and site transients if present. 42 45 if ( is_multisite() ) { 43 46 $wpdb->query( 44 47 $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_' ) . '%' 47 55 ) 48 56 ); … … 50 58 51 59 // 3. Drop custom tables owned by the plugin. 52 foreach ( array( 'vnspo_404_logs', 'vnspo_rum', 'vnspo_immutable_log' ) as $vnspo_table ) {60 foreach ( array( 'vnspo_404_logs', 'vnspo_rum', 'vnspo_immutable_log', 'vnspo_preload_queue', 'vnspo_redirect_logs' ) as $vnspo_table ) { 53 61 $vnspo_table_name = esc_sql( $wpdb->prefix . $vnspo_table ); 54 62 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange … … 56 64 } 57 65 58 // 4. Clean post meta .66 // 4. Clean post meta and user meta. 59 67 $wpdb->query( 60 68 $wpdb->prepare( … … 63 71 ) 64 72 ); 73 $wpdb->query( 74 $wpdb->prepare( 75 "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s", 76 $wpdb->esc_like( 'vnspo_' ) . '%' 77 ) 78 ); 65 79 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 ); 114 foreach ( $vnspo_cron_hooks as $vnspo_hook ) { 68 115 wp_clear_scheduled_hook( $vnspo_hook ); 69 116 } 70 117 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. 119 if ( ! 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 72 165 $vnspo_upload_dir = wp_upload_dir(); 73 166 if ( ! function_exists( 'WP_Filesystem' ) ) { … … 77 170 global $wp_filesystem; 78 171 172 $vnspo_base_upload_dir = trailingslashit( $vnspo_upload_dir['basedir'] ); 79 173 foreach ( 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 ); 88 175 } 176 foreach ( 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 4 4 * Plugin URI: https://vn-nexus.com/vnspo-pro 5 5 * Description: Local-first WordPress performance tools for page cache, asset optimization, lazy loading, and technical diagnostics. 6 * Version: 1.2. 16 * Version: 1.2.2 7 7 * Author: TranDuy258 8 8 * Author URI: https://profiles.wordpress.org/tranduy258 … … 26 26 27 27 // Plugin version 28 define('VNSPEED_VERSION', '1.2.1'); 28 if (! defined('VNSPO_VERSION')) { 29 define('VNSPO_VERSION', '1.2.2'); 30 } 29 31 30 32 // Edge API URL (configurable) … … 34 36 35 37 // 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 } 38 44 39 45 // Plugin URL with fallback for 0.0.0.1 site_url … … 45 51 } 46 52 } 47 define('VNSPEED_PLUGIN_URL', $vnspo_purl); 53 if (! defined('VNSPO_PLUGIN_URL')) { 54 define('VNSPO_PLUGIN_URL', $vnspo_purl); 55 } 48 56 unset($vnspo_purl); 49 57 … … 65 73 * Get plugin URL 66 74 */ 67 function VNSPEED_URL($path = '')75 function vnspo_url($path = '') 68 76 { 69 77 if (empty($path)) { 70 return VNSP EED_PLUGIN_URL;71 } 72 return rtrim(VNSP EED_PLUGIN_URL, '/') . '/' . ltrim($path, '/');78 return VNSPO_PLUGIN_URL; 79 } 80 return rtrim(VNSPO_PLUGIN_URL, '/') . '/' . ltrim($path, '/'); 73 81 } 74 82 } … … 85 93 spl_autoload_register(function ($class) { 86 94 $prefix = 'VNSPO\\'; 87 $base_dir = VNSP EED_PATH . 'src/';95 $base_dir = VNSPO_PATH . 'src/'; 88 96 $len = strlen($prefix); 89 97 … … 129 137 if (\is_admin() || $is_preview) { 130 138 (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(); 131 145 } 132 146 }, 0); … … 178 192 register_rest_route('vnspo/v1', '/activate-pagespeed', [ 179 193 'methods' => 'POST', 194 'permission_callback' => function () { 195 return current_user_can('manage_options'); 196 }, 180 197 'callback' => function (\WP_REST_Request $request) { 181 198 if (! current_user_can('manage_options')) { … … 183 200 } 184 201 185 $feature = $request->get_param('feature');202 $feature = \sanitize_key((string) $request->get_param('feature')); 186 203 $options = get_option('vnspo_options', []); 187 204 … … 236 253 ], 200); 237 254 }, 238 'permission_callback' => function () {239 return current_user_can('manage_options');240 },241 255 ]); 242 256 }); … … 262 276 'redirection' => 0, 263 277 'sslverify' => true, 264 'user-agent' => 'VN-Speed-Optimizer/' . VNSP EED_VERSION,278 'user-agent' => 'VN-Speed-Optimizer/' . VNSPO_VERSION, 265 279 ]); 266 280 … … 628 642 629 643 if (isset($lang_map[$forced_lang]) && '' !== $lang_map[$forced_lang]['mo']) { 630 $forced_mo = VNSP EED_PATH . 'languages/' . $lang_map[$forced_lang]['mo'];644 $forced_mo = VNSPO_PATH . 'languages/' . $lang_map[$forced_lang]['mo']; 631 645 if (\is_file($forced_mo)) { 632 646 \unload_textdomain('vn-speed-optimizer'); … … 643 657 return; 644 658 } 645 $mo_file = VNSP EED_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'; 646 660 if (!\is_file($mo_file)) { 647 661 $short = substr((string) $locale, 0, 2); 648 662 if (isset($lang_map[$short]) && '' !== $lang_map[$short]['mo']) { 649 $mo_file = VNSP EED_PATH . 'languages/' . $lang_map[$short]['mo'];663 $mo_file = VNSPO_PATH . 'languages/' . $lang_map[$short]['mo']; 650 664 } 651 665 } … … 665 679 add_action('admin_init', function () { 666 680 $cache_ver_key = 'vnspo_combined_cache_ver'; 667 if (\get_option($cache_ver_key) !== VNSP EED_VERSION) {681 if (\get_option($cache_ver_key) !== VNSPO_VERSION) { 668 682 $upload = \wp_upload_dir(); 669 683 $dir = $upload['basedir'] . '/vnspo/min/'; … … 678 692 } 679 693 } 680 \update_option($cache_ver_key, VNSP EED_VERSION, false);694 \update_option($cache_ver_key, VNSPO_VERSION, false); 681 695 } 682 696 });
Note:
See TracChangeset
for help on using the changeset viewer.