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); return $html; } /** * 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((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']) ? (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 = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '/'; // URL decode only if double-encoded (contains %25) if (strpos($url, '%25') !== false) { $url = urldecode($url); } // 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(); // 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 && !$hasDynamicQueryParams) { $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($cached); } } // 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; if (!$bypassUserCache && !$nocache) { $lockStart = time(); // Try to acquire lock, wait if another process is generating this page while (($lockTime = get_transient($lockKey)) !== false) { if ((time() - $lockStart) > $maxLockWait) { // Another request is still generating this page; avoid duplicate API calls // Serve the current HTML without starting a second translation pass $processing = false; return $html; } // Wait 200ms before checking again usleep(200000); // Check if cache became available while waiting $cached = AI_Cache::get($key); if ($cached !== false) { $processing = false; return $this->post_process_cached_content($cached); } } // Acquire lock for this page generation set_transient($lockKey, time(), 120); // Lock expires after 2 minutes as failsafe $lockAcquired = true; } $timeLimit = (int) ini_get('max_execution_time'); $elapsed = microtime(true) - ($_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true)); $remaining = $timeLimit > 0 ? ($timeLimit - $elapsed) : 120; if ($remaining < 20) { if ($lockAcquired) { delete_transient($lockKey); } $processing = false; return $html; } // Extend execution time for large pages if ($timeLimit > 0 && $timeLimit < 120) { @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) { delete_transient($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); $res = AI_Batch::translate_plan($plan, AI_Lang::default(), $lang, $this->site_context()); $translations = is_array(($res['segments'] ?? null)) ? $res['segments'] : []; if (empty($translations)) { if ($lockAcquired) { delete_transient($lockKey); } $processing = false; return $html; } else { $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 in the preserved original HTML to match target language if ($lang !== null && $lang !== '') { $locale = self::getLangAttribute($lang); // Replace existing lang attribute $html2 = preg_replace('/(]*\s)lang=["\'][^"\']*["\']/i', '$1lang="' . esc_attr($locale) . '"', $html2, 1); // If no lang attribute exists, add it to the html tag if (!preg_match('/]*\slang=/i', $html2)) { $html2 = preg_replace('/(]*)>/i', '$1$2 lang="' . esc_attr($locale) . '">', $html2, 1); } } } // Ensure lang attribute is set before SEO injection if ($lang !== null && $lang !== '' && !empty($html2)) { $locale = self::getLangAttribute($lang); // Double-check lang attribute is correct in final HTML if (!preg_match('/]*\slang=["\']' . preg_quote($locale, '/') . '["\']/i', $html2)) { $html2 = preg_replace('/(]*\s)lang=["\'][^"\']*["\']/i', '$1lang="' . esc_attr($locale) . '"', $html2, 1); if (!preg_match('/]*\slang=/i', $html2)) { $html2 = preg_replace('/(]*)>/i', '$1$2 lang="' . esc_attr($locale) . '">', $html2, 1); } } } // Protect script/style tags from DOMDocument corruption in SEO/URL pass. // DOMDocument::saveHTML() can encode & as & inside