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, '') !== false && stripos($cached, '') !== false); if (!$hasClosingTags) { AI_Cache::delete($key); $cached = false; } } if ($cached !== false) { $processing = false; return $this->post_process_cached_content(self::refresh_cached_nonces(self::refresh_cached_stylesheets($cached, $html), $html)); } } // Implement cache locking to prevent race conditions from concurrent requests // When multiple spiders/crawlers hit the same uncached page simultaneously, // only the first request generates the translation while others wait $lockKey = 'ai_translate_lock_' . md5($key); $maxLockWait = 30; // Maximum seconds to wait for lock $lockAcquired = false; // Pages that will not be written to the shared cache (session-specific HTML // or DONOTCACHEPAGE) must not wait on the lock: nothing will appear. if (!$bypassUserCache && !$nocache && !$noCachePage && !$isNeverCachedRoute) { $lockStart = time(); // Wait while another process holds the lock while (!self::try_acquire_cache_lock($lockKey)) { if ((time() - $lockStart) > $maxLockWait) { // Another request is still generating this page; avoid duplicate API calls $processing = false; return $html; } usleep(200000); $cached = AI_Cache::get($key); if ($cached !== false) { $processing = false; return $this->post_process_cached_content(self::refresh_cached_nonces(self::refresh_cached_stylesheets($cached, $html), $html)); } } $lockAcquired = true; } $timeLimit = (int) ini_get('max_execution_time'); $elapsed = microtime(true) - (float) (isset($_SERVER['REQUEST_TIME_FLOAT']) ? sanitize_text_field(wp_unslash((string) $_SERVER['REQUEST_TIME_FLOAT'])) : microtime(true)); $remaining = $timeLimit > 0 ? ($timeLimit - $elapsed) : 120; if ($remaining < 20) { if ($lockAcquired) { self::release_cache_lock($lockKey); } $processing = false; return $html; } // Extend execution time for large pages (translation pipeline can exceed default 30s on big HTML). if ($timeLimit > 0 && $timeLimit < 120) { // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- required for large-page translation that exceeds default execution time @set_time_limit(120); } // Validate HTML before processing: must have minimum length and essential tags // This prevents caching incomplete/empty HTML from spiders or partial buffer flushes $htmlLen = strlen($html); $hasHtml = (stripos($html, ' $expiry_seconds; } } if (!$cache_exists || !$cache_is_expired) { // Cache doesn't exist or is not expired, block translation if ($lockAcquired) { self::release_cache_lock($lockKey); } $reason = $cache_exists ? 'cache_not_expired' : 'cache_not_exists'; // If cache doesn't exist, inject warning message for logged-in admins if (!$cache_exists && function_exists('current_user_can') && current_user_can('manage_options')) { $warning = ''; $html = str_replace('', $warning . '', $html); } $processing = false; return $html; // Return untranslated HTML (or cached if exists) } } $plan = AI_DOM::plan($html); // Meta texts (title, description, Twitter Cards, JSON-LD) are translated later in separate // sequential rounds; adding them here puts them in the same parallel API stage. AI_DOM::merge() // only reads the ids of $plan, so the extra segments do not affect the page. $apiPlan = $plan; $metaSegments = AI_SEO::prefetch_segments($html, $lang); if (!empty($metaSegments) && isset($apiPlan['segments']) && is_array($apiPlan['segments'])) { $apiPlan['segments'] = array_merge($apiPlan['segments'], $metaSegments); } $res = AI_Batch::translate_plan($apiPlan, AI_Lang::default(), $lang, $this->site_context()); $translations = is_array(($res['segments'] ?? null)) ? $res['segments'] : []; if (empty($translations)) { if ($lockAcquired) { self::release_cache_lock($lockKey); } $processing = false; return $html; } else { AI_SEO::mark_translated($translations, (string) $lang); $merged = AI_DOM::merge($plan, $translations, $lang); // Preserve original framing to avoid theme conflicts: replace only inner body $html2 = $merged; if (preg_match('/]*>([\s\S]*?)<\/body>/i', (string) $merged, $mNew) && preg_match('/]*>([\s\S]*?)<\/body>/i', (string) $html, $mOrig)) { $newInner = (string) $mNew[1]; // Use preg_replace_callback instead of preg_replace to prevent $n back-reference // interpretation in the replacement string. Content like bash code blocks may contain // $1, $2 etc. which preg_replace would interpret as capture group references, // injecting mid-content and truncating the page. $html2 = (string) preg_replace_callback( '/(]*>)[\s\S]*?(<\/body>)/i', function ($m) use ($newInner) { return $m[1] . $newInner . $m[2]; }, (string) $html, 1 ); } // Update HTML lang attribute (and dir for RTL target languages) in the // preserved original HTML to match target language $html2 = self::apply_html_lang_dir($html2, $lang); } // Ensure lang (and dir for RTL) attributes are correct before SEO injection if ($lang !== null && $lang !== '' && !empty($html2)) { $locale = self::getLangAttribute($lang); $langOk = (bool) preg_match('/]*\slang=["\']' . preg_quote($locale, '/') . '["\']/i', $html2); $dirOk = !AI_Lang::is_rtl($lang) || (bool) preg_match('/]*\sdir=["\']rtl["\']/i', $html2); if (!$langOk || !$dirOk) { $html2 = self::apply_html_lang_dir($html2, $lang); } } // Protect script/style tags from DOMDocument corruption in SEO/URL pass. // DOMDocument::saveHTML() can encode & as & inside