get_simple_admin_bar_html(); $html = preg_replace('/(
]*>)/', '$1' . $admin_bar_html, $html, 1); } elseif (!$should_show_admin_bar && $has_admin_bar) { // Regular user should NOT see admin bar but it's in cached content – strip it. // Uses a depth-counting string traversal instead of DOMDocument to avoid a // third DOM parse (pipeline already uses exactly two DOMDocument passes). $html = self::strip_admin_bar($html); } // Update internal permalinks to use current translated slugs $html = $this->update_cached_permalinks($html); // Replace WordPress site_url host with current request host to prevent cross-origin AJAX issues $html = $this->fix_cached_domain($html); // Pages cached before dir="rtl" support lack the attribute; apply it on serve // so existing Arabic/Hebrew caches render right-to-left immediately instead of // only after cache expiry. Idempotent for pages already generated with the fix. $active_lang = AI_Lang::current(); if ($active_lang !== null && AI_Lang::is_rtl($active_lang)) { $html = self::apply_html_lang_dir($html, $active_lang); } return $html; } /** * Replace nonces baked into cached HTML (inline JSON such as chatbot_message_nonce or * restNonce) by the ones WordPress generated for the current request. A nonce expires * after 12-24 hours, so a cached translated page otherwise makes AJAX/REST calls fail * ("Security check failed"). Keys are matched by name; values are WordPress nonces * (10 hex characters). Cache files themselves stay unchanged. */ private static function refresh_cached_nonces(string $html, string $source_html): string { // Group 1 = context that identifies the nonce, group 2 = the nonce (10 hex characters). $patterns = [ // JSON / JS / URL: "x_nonce":"abc", nonce: 'abc', \"nonce\":\"abc\", ?_wpnonce=abc, &_wpnonce=abc '/([\w-]*nonce[\w-]*[\\\\"\']*\s*[:=]\s*[\\\\"\']*)([0-9a-f]{10})(?![0-9a-f])/i', // Form fields: and '/(]*\bname=["\'][^"\']*nonce[^"\']*["\'][^>]*?\bvalue=["\'])([0-9a-f]{10})(?![0-9a-f])/i', '/(]*\bvalue=["\'])([0-9a-f]{10})(?=["\'][^>]*\bname=["\'][^"\']*nonce)/i', ]; foreach ($patterns as $pattern) { if (!preg_match_all($pattern, $source_html, $m, PREG_SET_ORDER)) { continue; } $fresh = []; foreach ($m as $hit) { $fresh[$hit[1]][] = $hit[2]; } $seen = []; $html = preg_replace_callback($pattern, static function ($hit) use ($fresh, &$seen) { $key = $hit[1]; if (empty($fresh[$key])) { return $hit[0]; } // Same context repeats in the same order in source and cache: pair by position. $i = $seen[$key] ?? 0; $seen[$key] = $i + 1; return $key . ($fresh[$key][$i] ?? $fresh[$key][0]); }, $html); } return $html; } /** Refresh only enqueued stylesheet tags; leave translated markup untouched. */ private static function refresh_cached_stylesheets(string $html, string $source_html): string { $pattern = '/]*\brel=["\']stylesheet["\'])(?=[^>]*\bid=["\'][^"\']+-css["\'])[^>]*>/i'; if (!preg_match_all($pattern, $source_html, $styles) || stripos($html, '') === false) { return $html; } $replacement = implode('', $styles[0]); $inserted = false; $html = preg_replace_callback($pattern, static function () use (&$inserted, $replacement) { if ($inserted) { return ''; } $inserted = true; return $replacement; }, $html); return $inserted ? $html : preg_replace('/<\/head>/i', $replacement . "\n", $html, 1); } /** * Replace the WordPress site_url host with the current request host in cached HTML. * Prevents cross-origin AJAX failures when a site is accessed via an alias domain. * * @param string $html * @return string */ private function fix_cached_domain($html) { $request_host = isset($_SERVER['HTTP_HOST']) ? strtok(sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_HOST'])), ':') : ''; if ($request_host === '') { return $html; } // Extract the domain baked into cached HTML from WordPress URL patterns if (!preg_match('#https?://([a-z0-9.-]+)/wp-(?:content|admin|includes)/#i', $html, $m)) { return $html; } $cached_host = $m[1]; if (strcasecmp($cached_host, $request_host) === 0) { return $html; } return str_replace($cached_host, $request_host, $html); } /** * Update internal permalinks in cached HTML to use current translated slugs. * This ensures that even if slugs change after caching, links remain correct. * * @param string $html Cached HTML content * @return string HTML with updated permalinks */ private function update_cached_permalinks($html) { $lang = \AITranslate\AI_Lang::current(); $default = \AITranslate\AI_Lang::default(); if ($lang === null || $default === null || strtolower($lang) === strtolower($default)) { return $html; } // Match all internal links that already carry the language prefix: // href="/{lang}/slug/" or href="/{lang}/base/slug/" // Group 1 = full path (e.g. /de/diensten/pakket/) // Group 2 = everything after the language segment (e.g. diensten/pakket) $lang_re = preg_quote($lang, '#'); $pattern = '#href="(/' . $lang_re . '/([^"?\#\s]+)/?)"#i'; $html = preg_replace_callback($pattern, function ($matches) use ($lang) { $path = trim($matches[2], '/'); // e.g. "diensten/pakket" $parts = explode('/', $path); $old_slug = array_pop($parts); // last segment is the slug if ($old_slug === '') { return $matches[0]; } // Try to find the post by translated slug, then by source slug. $post_id = \AITranslate\AI_Slugs::resolve_translated_slug_to_post($old_slug, $lang); if (!$post_id) { $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $old_slug); } if ($post_id) { // No-generate: serving from cache must not trigger new segment-cache writes. $correct_slug = \AITranslate\AI_Slugs::get_or_generate($post_id, $lang, false); if ($correct_slug !== null && $correct_slug !== '' && $correct_slug !== $old_slug) { $parts[] = trim($correct_slug, '/'); $new_href = '/' . $lang . '/' . implode('/', $parts) . '/'; return 'href="' . $new_href . '"'; } } return $matches[0]; }, $html); return $html; } /** * Strip the WordPress admin bar from HTML without using DOMDocument. * * Uses a depth-counting character scan to find the matching for the * wpadminbar container, plus regex for the associated inline '; } /** * OB callback to translate and cache the page. * * @param string $html * @return string */ public function callback($html) { // Detect warm cache requests (bypass static processing check) $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_USER_AGENT'])) : ''; $is_warm_cache_request = (strpos($user_agent, 'AITranslateCacheWarmer') !== false); static $processing = false; // Allow warm cache requests to bypass static processing check (they need to generate cache) if ($processing && !$is_warm_cache_request) { return $html; } $processing = true; // PHASE 1: Basic environment checks if ($this->should_skip_basic_checks()) { $processing = false; return $html; } // PHASE 2: Content type validation if ($this->should_skip_content_type($html)) { $processing = false; return $html; } // PHASE 3: Page structure validation if ($this->should_skip_page_structure()) { $processing = false; return $html; } // PHASE 4: File type checks if ($this->should_skip_file_types($html)) { $processing = false; return $html; } // PHASE 5: Language and user validation if ($this->should_skip_language_or_user()) { $processing = false; return $html; } // Get validated language (already checked in PHASE 5) $lang = AI_Lang::current(); // For default language: inject SEO tags but no translation $needsTranslation = AI_Lang::should_translate($lang); if (!$needsTranslation) { $htmlWithSEO = AI_SEO::inject($html, $lang); $processing = false; return $htmlWithSEO; } // Get user cache bypass setting (already determined in PHASE 5) $stopTranslations = (bool) AI_Translate_Core::get_setting('stop_translations_except_cache_invalidation', false); // PERFORMANCE FIX: Disable cache bypass completely for all users // This ensures optimal performance for everyone, including admins $bypassUserCache = false; $route = $this->current_route_id(); $url = ai_translate_request_uri('/'); // Allow cache bypass via nocache parameter for authenticated admins only $nocache = (isset($_GET['nocache']) || isset($_GET['no_cache'])) && current_user_can('manage_options'); // Check for dynamic query parameters that indicate the page should be translated but not cached // Examples: WooCommerce add-to-cart, form submissions, AJAX actions, etc. $hasDynamicQueryParams = $this->has_dynamic_query_parameters(); // DONOTCACHEPAGE means "do not store this response". WooCommerce sets it on // cart/checkout/my-account (session HTML). Jetpack Subscriptions also sets it // for every manage_options user via is_user_auth() — those admins must still // be served the shared page cache (admin bar is injected afterwards). $noCachePage = defined('DONOTCACHEPAGE') && DONOTCACHEPAGE; $neverCachedPostIds = AI_Cache_Meta::get_never_cached_post_ids(); $routePostId = (strpos((string) $route, 'post:') === 0) ? (int) substr((string) $route, 5) : 0; $isNeverCachedRoute = ($routePostId > 0 && in_array($routePostId, $neverCachedPostIds, true)); $isPrivilegedAdmin = function_exists('current_user_can') && current_user_can('manage_options'); // Jetpack Subscriptions defines DONOTCACHEPAGE for every manage_options user. // Those admins still get the shared page cache; the admin bar is injected after. // Session-specific routes (cart, paywalls, dynamic query params) still skip the read. $skipCacheRead = $hasDynamicQueryParams || $isNeverCachedRoute || ((bool) $noCachePage && !$isPrivilegedAdmin); // Note: content_version removed from cache key for stability // route_id is already unique per page, making content_version unnecessary // Cache expiry (14+ days) ensures automatic refresh $key = AI_Cache::key($lang, $route, ''); // Check if route should be translated (but may not be cached) // This allows search pages and other dynamic content to be translated but not cached $shouldTranslate = $this->route_should_be_translated($route); if (!$shouldTranslate) { $processing = false; return $html; // Return untranslated HTML without processing } if (!$bypassUserCache && !$nocache && !$skipCacheRead) { $cached = AI_Cache::get($key); if ($cached !== false && !$this->content_matches_target_lang($cached, $lang)) { $retryKey = 'ai_tr_retry_' . md5($key); $retries = (int) get_transient($retryKey); if ($retries >= 3) { // Max retries reached — serve cached content as-is } else { AI_Cache::delete($key); $cached = false; } } // Reject truncated cache (from bot visits): missing closing tags breaks chat/greeting if ($cached !== false) { $hasClosingTags = (stripos($cached, '