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
// Remove admin bar robustly via DOM (regex breaks on nested toolbar markup).
$doc = new \DOMDocument();
$internalErrors = libxml_use_internal_errors(true);
$htmlToLoad = AI_DOM::ensureUtf8((string) $html);
$doc->loadHTML('' . $htmlToLoad, LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
libxml_use_internal_errors($internalErrors);
$xpath = new \DOMXPath($doc);
$adminNodes = $xpath->query('//*[@id="wpadminbar" or @id="wp-toolbar"]');
if ($adminNodes !== false) {
foreach ($adminNodes as $adminNode) {
if ($adminNode->parentNode) {
$adminNode->parentNode->removeChild($adminNode);
}
}
}
// Remove inline adminbar style blocks from old cached variants.
$styleNodes = $xpath->query('//style');
if ($styleNodes !== false) {
foreach ($styleNodes as $styleNode) {
$styleText = strtolower((string) $styleNode->textContent);
if (strpos($styleText, '#wpadminbar') !== false ||
strpos($styleText, 'body{margin-top:32px') !== false ||
strpos($styleText, 'body {margin-top:32px') !== false) {
if ($styleNode->parentNode) {
$styleNode->parentNode->removeChild($styleNode);
}
}
}
}
// Also remove body/html "admin-bar" class to avoid layout offsets.
$bodyNodes = $xpath->query('//body');
if ($bodyNodes !== false) {
foreach ($bodyNodes as $bodyNode) {
if ($bodyNode instanceof \DOMElement) {
$classAttr = trim((string) $bodyNode->getAttribute('class'));
if ($classAttr !== '') {
$classes = preg_split('/\s+/', $classAttr);
if (is_array($classes)) {
$classes = array_values(array_filter($classes, function ($className) {
return $className !== 'admin-bar';
}));
if (!empty($classes)) {
$bodyNode->setAttribute('class', implode(' ', $classes));
} else {
$bodyNode->removeAttribute('class');
}
}
}
}
}
}
$htmlNodes = $xpath->query('//html');
if ($htmlNodes !== false) {
foreach ($htmlNodes as $htmlNode) {
if ($htmlNode instanceof \DOMElement) {
$classAttr = trim((string) $htmlNode->getAttribute('class'));
if ($classAttr !== '') {
$classes = preg_split('/\s+/', $classAttr);
if (is_array($classes)) {
$classes = array_values(array_filter($classes, function ($className) {
return $className !== 'admin-bar';
}));
if (!empty($classes)) {
$htmlNode->setAttribute('class', implode(' ', $classes));
} else {
$htmlNode->removeAttribute('class');
}
}
}
}
}
}
$html = $doc->saveHTML();
$html = preg_replace('/<\?xml[^?]*\?>\s*/i', '', $html);
}
// Update internal permalinks to use current translated slugs
$html = $this->update_cached_permalinks($html);
return $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;
}
// Find all internal links: href="/xx/service/slug/" or href="/service/slug/"
// Pattern matches: /{lang}/service/{slug}/ or /service/{slug}/
$pattern = '#href="(/(?:' . preg_quote($lang, '#') . '/)?service/([^/"]+)/?)"#i';
$html = preg_replace_callback($pattern, function ($matches) use ($lang) {
$full_href = $matches[1];
$old_slug = $matches[2];
// Try to find the post by this slug (could be source or old translated slug)
$post_id = \AITranslate\AI_Slugs::resolve_translated_slug_to_post($old_slug, $lang);
if (!$post_id) {
// Try resolving as source slug
$post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $old_slug);
}
if ($post_id) {
// Only use existing slug (no translation): we are serving from page cache and must not trigger 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) {
// Replace with correct slug
$new_href = '/' . $lang . '/service/' . trim($correct_slug, '/') . '/';
return 'href="' . $new_href . '"';
}
}
// No change needed or couldn't resolve
return $matches[0];
}, $html);
return $html;
}
/**
* Get simple admin bar HTML for cached content.
*
* @return string Simple admin bar HTML
*/
private function get_simple_admin_bar_html()
{
return '';
}
/**
* 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)
$settings = get_option('ai_translate_settings', array());
$stopTranslations = isset($settings['stop_translations_except_cache_invalidation']) &&
$settings['stop_translations_except_cache_invalidation'];
// 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 testing
$nocache = isset($_GET['nocache']) || isset($_GET['no_cache']);
// 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;
}
}
if ($cached !== false) {
$processing = false;
return $this->post_process_cached_content($cached);
}
} else {
$bypassReason = $bypassUserCache ? 'logged_in_user' : ($nocache ? 'nocache_param' : 'unknown');
}
// 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 $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