base -> language code $fallback_locales = array($locale); // If locale has underscores, extract base locale (e.g., nl_NL_formal -> nl_NL) if (strpos($locale, '_') !== false) { $parts = explode('_', $locale); if (count($parts) >= 2) { $base_locale = $parts[0] . '_' . $parts[1]; if (!in_array($base_locale, $fallback_locales, true)) { $fallback_locales[] = $base_locale; } } // Also try language code only (e.g., nl_NL -> nl) if (count($parts) >= 1) { $lang_only = $parts[0]; if (!in_array($lang_only, $fallback_locales, true)) { $fallback_locales[] = $lang_only; } } } // Try each locale in fallback chain foreach ($fallback_locales as $try_locale) { $mofile = $lang_dir . 'ai-translate-' . $try_locale . '.mo'; if (file_exists($mofile)) { // Unload existing textdomain first if reloading if ($force_user_locale && is_textdomain_loaded('ai-translate')) { unload_textdomain('ai-translate'); } load_textdomain('ai-translate', $mofile); if (is_textdomain_loaded('ai-translate')) { return; } } } // Final fallback to standard load_plugin_textdomain. Plugin ships its own .mo files in // /languages/, so we cannot rely solely on WordPress 4.6+ automatic translation loading // (which only picks up /wp-content/languages/plugins/ai-translate-*.mo files). // phpcs:ignore PluginCheck.CodeAnalysis.DiscouragedFunctions.load_plugin_textdomainFound -- needed for bundled translations load_plugin_textdomain( 'ai-translate', false, dirname(plugin_basename(__FILE__)) . '/languages/' ); } // Load textdomain for frontend with site locale add_action('plugins_loaded', function() { ai_translate_load_textdomain(); // Load with site locale for frontend }, 1); // For admin pages, load textdomain with user locale (this overrides the frontend load) add_action('admin_init', function() { if (is_user_logged_in()) { $user_locale = get_user_locale(); $site_locale = get_locale(); // Always load user locale for admin, even if same as site locale ai_translate_load_textdomain(true); // Force load with user locale } }, 1); // High priority to override any other loads // Include core/admin and runtime classes. require_once __DIR__ . '/includes/class-ai-translate-core.php'; require_once __DIR__ . '/includes/admin-page.php'; require_once __DIR__ . '/includes/class-ai-lang.php'; require_once __DIR__ . '/includes/class-ai-cache.php'; require_once __DIR__ . '/includes/class-ai-cache-meta.php'; require_once __DIR__ . '/includes/class-ai-dom.php'; require_once __DIR__ . '/includes/class-ai-batch.php'; require_once __DIR__ . '/includes/class-ai-seo.php'; require_once __DIR__ . '/includes/class-ai-url.php'; require_once __DIR__ . '/includes/class-ai-ob.php'; require_once __DIR__ . '/includes/class-ai-slugs.php'; require_once __DIR__ . '/includes/class-ai-404-recovery.php'; require_once __DIR__ . '/includes/class-ai-sitemap.php'; // Initialize sitemap integration \AITranslate\AI_Sitemap::init(); /** * Get transient with database fallback for ai_tr_attr_ keys. * First tries memcached (via get_transient), then falls back to database. * * @param string $key Transient key * @return mixed|false Transient value or false if not found */ function ai_translate_get_attr_transient($key) { // First try memcached (via standard WordPress transient API) $value = get_transient($key); if ($value !== false) { return $value; } // Fallback to database: check if transient exists in wp_options global $wpdb; $transient_key = '_transient_' . $key; $timeout_key = '_transient_timeout_' . $key; // Check if transient exists and hasn't expired $timeout = $wpdb->get_var($wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $timeout_key )); if ($timeout !== null) { // Check if expired if ((int) $timeout > time()) { // Not expired, get value from database $value = $wpdb->get_var($wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $transient_key )); if ($value !== null) { // Restore to memcached for faster access next time $expiry = (int) $timeout - time(); if ($expiry > 0) { set_transient($key, maybe_unserialize($value), $expiry); } return maybe_unserialize($value); } } else { // Expired, clean up $wpdb->delete($wpdb->options, ['option_name' => $transient_key], ['%s']); $wpdb->delete($wpdb->options, ['option_name' => $timeout_key], ['%s']); } } return false; } /** * Set transient with dual-write to both memcached and database for ai_tr_attr_ keys. * Writes to both memcached (via set_transient) and database (direct) for persistence. * * @param string $key Transient key * @param mixed $value Transient value * @param int $expiration Expiration time in seconds * @return bool True on success, false on failure */ function ai_translate_set_attr_transient($key, $value, $expiration) { // Write to memcached (via standard WordPress transient API) $memcached_result = set_transient($key, $value, $expiration); // Also write to database for persistence (survives memcached restart) global $wpdb; $transient_key = '_transient_' . $key; $timeout_key = '_transient_timeout_' . $key; $timeout = time() + $expiration; // Use WordPress functions to ensure proper serialization $value_serialized = maybe_serialize($value); // Insert or update transient value $wpdb->replace( $wpdb->options, [ 'option_name' => $transient_key, 'option_value' => $value_serialized, 'autoload' => 'no' ], ['%s', '%s', '%s'] ); // Insert or update timeout $wpdb->replace( $wpdb->options, [ 'option_name' => $timeout_key, 'option_value' => (string) $timeout, 'autoload' => 'no' ], ['%s', '%s', '%s'] ); return $memcached_result; } /** * Delete transient from both memcached and database for ai_tr_attr_ keys. * * @param string $key Transient key * @return bool True on success, false on failure */ function ai_translate_delete_attr_transient($key) { // Delete from memcached $memcached_result = delete_transient($key); // Also delete from database global $wpdb; $transient_key = '_transient_' . $key; $timeout_key = '_transient_timeout_' . $key; $wpdb->delete($wpdb->options, ['option_name' => $transient_key], ['%s']); $wpdb->delete($wpdb->options, ['option_name' => $timeout_key], ['%s']); return $memcached_result; } /** * Cache key for client-side / attribute translations (dual-write transient). * * @param string $lang Language code. * @param string $normalized_text Normalized source text. * @return string */ function ai_translate_attr_cache_key($lang, $normalized_text) { return 'ai_tr_attr_' . sanitize_key((string) $lang) . '_' . md5((string) $normalized_text); } /** * Segment-cache fallback key for attribute texts (ai_tr_seg_*). * * @param string $lang Language code. * @param string $normalized_text Normalized source text. * @return string */ function ai_translate_seg_attr_cache_key($lang, $normalized_text) { $lang = sanitize_key((string) $lang); return 'ai_tr_seg_' . $lang . '_' . md5('attr|' . md5((string) $normalized_text)); } /** * Register language-prefixed rewrite rules so WordPress can resolve translated URLs via the 'lang' query var. * Runs at priority 999 to ensure custom post types are registered first. * * @return void */ function ai_translate_register_rewrite_rules() { $enabled = \AITranslate\AI_Translate_Core::enabled_languages(); $detectable = \AITranslate\AI_Translate_Core::detectable_languages(); $default = \AITranslate\AI_Translate_Core::default_language(); $langs = array_values(array_unique(array_merge($enabled, $detectable))); if ($default !== '') { $langs = array_diff($langs, array($default)); } $langs = array_filter(array_map('sanitize_key', $langs)); if (empty($langs)) { return; } $regex = '(' . implode('|', array_map(function ($l) { return preg_quote($l, '/'); }, $langs)) . ')'; add_rewrite_rule('^' . $regex . '/?$', 'index.php?lang=$matches[1]', 'top'); $public_post_types = get_post_types(array('public' => true, '_builtin' => false), 'objects'); foreach ($public_post_types as $post_type) { if (!empty($post_type->rewrite) && isset($post_type->rewrite['slug'])) { $slug = $post_type->rewrite['slug']; $type_name = $post_type->name; add_rewrite_rule( '^' . $regex . '/(?!wp-admin|wp-login\.php)(' . preg_quote($slug, '/') . ')/([^/]+)/?$', 'index.php?lang=$matches[1]&post_type=' . $type_name . '&name=$matches[3]', 'top' ); } } add_rewrite_rule('^' . $regex . '/(?!wp-admin|wp-login\.php)(.+)$', 'index.php?ai_translate_path=$matches[2]&lang=$matches[1]', 'top'); add_rewrite_rule('^' . $regex . '/page/([0-9]+)/?$', 'index.php?lang=$matches[1]&paged=$matches[2]', 'top'); } add_action('init', 'ai_translate_register_rewrite_rules', 999); // Priority 999: runs AFTER custom post types are registered (default priority 10) // Ensure slug map and history tables exist — only run dbDelta when schema version changes add_action('init', function () { $current_version = '2.2.6'; $stored_version = get_option('ai_translate_slugs_schema_version', ''); if ($stored_version !== $current_version) { \AITranslate\AI_Slugs::install_table(); update_option('ai_translate_slugs_schema_version', $current_version); } }, 1); // Schedule cache metadata sync cron job add_action('ai_translate_sync_cache_metadata', function () { \AITranslate\AI_Cache_Meta::sync_from_filesystem(); }); if (!wp_next_scheduled('ai_translate_sync_cache_metadata')) { wp_schedule_event(time(), 'hourly', 'ai_translate_sync_cache_metadata'); } add_filter('query_vars', function ($vars) { if (!in_array('lang', $vars, true)) { $vars[] = 'lang'; } if (!in_array('ai_translate_path', $vars, true)) { $vars[] = 'ai_translate_path'; } return $vars; }); // Intentionally no early /{default}/ cookie mutation here. // The default language switch must be handled deterministically via server-side redirects // (especially for incognito), inside the switch handler and template_redirect rules. /** * Handle language switch via switcher early in init (before template_redirect) */ add_action('init', function () { // Skip admin/AJAX/REST if (is_admin() || wp_doing_ajax() || wp_is_json_request()) { return; } // Only handle switch_lang parameter - nothing else $switchLang = isset($_GET['switch_lang']) ? strtolower(sanitize_key((string) $_GET['switch_lang'])) : ''; if ($switchLang === '') { return; } // Set cookie using centralized function \AITranslate\AI_Lang::set_cookie($switchLang); // Redirect to clean URL (remove switch_lang parameter). // For default language: go straight to '/' to avoid /nl/ race conditions in incognito. $defaultLang = \AITranslate\AI_Lang::default(); $targetUrl = ($defaultLang && strtolower($switchLang) === strtolower((string) $defaultLang)) ? '/' : '/' . $switchLang . '/'; // Prevent intermediaries from caching the 302, so switch_lang stays effective. nocache_headers(); wp_safe_redirect(esc_url_raw($targetUrl), 302); exit; }, 2); /** * Block redirects for /{default}/ URLs when cookie doesn't match * This runs BEFORE redirect_canonical to prevent redirect before cookie is set */ add_filter('do_redirect_guess_404_permalink', function ($do_redirect) { $reqPathRaw = esc_url_raw(wp_unslash((string) ($_SERVER['REQUEST_URI'] ?? ''))); // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqPathRaw, '%25') !== false) { $reqPathRaw = urldecode($reqPathRaw); } $reqPath = ai_translate_strip_site_path((string) wp_parse_url($reqPathRaw, PHP_URL_PATH)); $defaultLang = \AITranslate\AI_Lang::default(); if ($reqPath !== '' && preg_match('#^/([a-z]{2})(?:/|$)#i', $reqPath, $m)) { $langFromUrl = strtolower(sanitize_key($m[1])); if ($defaultLang && strtolower($langFromUrl) === strtolower((string) $defaultLang)) { $cookieLang = isset($_COOKIE['ai_translate_lang']) ? strtolower(sanitize_key((string) $_COOKIE['ai_translate_lang'])) : ''; // If cookie doesn't match, block redirect so page can render and set cookie if ($cookieLang !== '' && strtolower($cookieLang) !== strtolower((string) $defaultLang)) { return false; // Block redirect } } } return $do_redirect; }, 1); /** * Prevent WordPress from redirecting language-prefixed URLs to the canonical root. * CRITICAL: This must run VERY early (priority 1) to prevent redirects before template_redirect */ add_filter('redirect_canonical', function ($redirect_url, $requested_url) { // Preserve switch_lang and _lang_switch parameters if (isset($_GET['switch_lang']) || isset($_GET['_lang_switch'])) { return false; } $req = (string) $requested_url; $path = ai_translate_strip_site_path((string) wp_parse_url($req, PHP_URL_PATH)); if ($path !== '' && preg_match('#^/([a-z]{2})(?:/|$)#i', $path, $m)) { $langFromUrl = strtolower(sanitize_key($m[1])); $defaultLang = \AITranslate\AI_Lang::default(); // If this is the default language, ALWAYS block redirect to allow page to render // This ensures the flag cookie is set and page can render before redirect if ($defaultLang && strtolower($langFromUrl) === strtolower((string) $defaultLang)) { // ALWAYS block redirect for /nl/ to allow page to render and set cookies return false; // Block redirect - render page first so cookies are set } // ALWAYS block redirect for language-prefixed URLs // This allows template_redirect to handle the redirect logic return false; } return $redirect_url; }, 0, 2); // Priority 0 to run BEFORE all other filters /** * Add a 5-star rating link to the plugin row on the Plugins screen. * * This renders a golden 5-star link that points to the plugin's WordPress.org page, * similar to popular plugins. Only affects the AI Translate row. * * @param string[] $links Existing meta links for the row. * @param string $file Plugin basename for the current row. * @return string[] */ add_filter('plugin_row_meta', function (array $links, $file) { if ($file !== plugin_basename(__FILE__)) { return $links; } $url = 'https://wordpress.org/plugins/ai-translate/'; $label = __('Rate on WordPress.org', 'ai-translate'); $stars = '★★★★★'; $links[] = sprintf( '%3$s', esc_url($url), esc_attr($label), esc_html($stars) ); return $links; }, 10, 2); /** * Plugin activation: flush rewrite rules and create database tables. */ register_activation_hook(__FILE__, function () { // Ensure rules are registered before flushing ai_translate_register_rewrite_rules(); // Automatically set permalinks to 'post-name' if they're currently 'plain' // since the plugin requires rewrite rules to function $permalink_structure = get_option('permalink_structure'); if ($permalink_structure === '' || $permalink_structure === null) { // Set to 'post-name' structure which is /%postname%/ update_option('permalink_structure', '/%postname%/'); } flush_rewrite_rules(); // Create cache metadata table \AITranslate\AI_Cache_Meta::create_table(); }); /** * Map ai_path to WordPress internal query vars. */ add_filter('request', function ($vars) { // Hard skip for admin paths $req = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : ''; if ($req !== '' && (strpos($req, '/wp-admin/') !== false || strpos($req, 'wp-login.php') !== false)) { return $vars; } // Fallback: if rewrite did not set ai_translate_path (e.g. URL with %), extract path from REQUEST_URI if (empty($vars['ai_translate_path']) && !empty($req) && preg_match('#^/([a-z]{2})/([^?]+)#i', $req, $m)) { $path_from_uri = ai_translate_strip_site_path((string) wp_parse_url($req, PHP_URL_PATH)); if ($path_from_uri !== '' && preg_match('#^/([a-z]{2})(?:/(.*))?$#i', $path_from_uri, $path_m)) { $vars['lang'] = strtolower($path_m[1]); $vars['ai_translate_path'] = isset($path_m[2]) ? trim($path_m[2], '/') : ''; } } // ai_translate_path: the generic rewrite rule sets ai_translate_path for /{lang}/{path}/. // Resolve to post before the main query so the correct page_id or p+post_type is included. if (!empty($vars['ai_translate_path']) && !empty($vars['lang'])) { $path = trim((string) $vars['ai_translate_path'], '/'); $lang = (string) $vars['lang']; // Split off a rewrite-endpoint or /page/N suffix (e.g. 'my-account/orders', // 'shop/page/2') so the base path can be resolved via the slug map. $suffix_info = ai_translate_split_endpoint_suffix($path); $resolve_path = ($suffix_info['suffix'] !== '' && $suffix_info['base'] !== '') ? $suffix_info['base'] : $path; $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $resolve_path); if (!$post_id && strpos($resolve_path, '/') !== false) { $base = basename($resolve_path); $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $base); if (!$post_id) { // Generic fallback: try to find post by translated slug (prefers non-attachments) $post_id = \AITranslate\AI_Slugs::resolve_translated_slug_to_post($base, $lang); } } if ($post_id) { $post = get_post($post_id); if ($post && $post->post_status === 'publish') { if ($post->post_type === 'page') { $vars['page_id'] = (int) $post->ID; } else { $vars['p'] = (int) $post->ID; $vars['post_type'] = $post->post_type; } if ($suffix_info['endpoint'] !== null) { $vars[$suffix_info['endpoint']] = $suffix_info['value']; } elseif ($suffix_info['paged'] > 1) { $vars['paged'] = $suffix_info['paged']; } } unset($vars['ai_translate_path']); } else { // Path did not resolve to a post; try taxonomy (category, tag, custom tax). $resolved_term = ai_translate_resolve_term_from_path($path); if ($resolved_term) { $vars = ai_translate_apply_resolved_term_to_vars($vars, $resolved_term); unset($vars['ai_translate_path']); } } } // Handle 'lang' query var: map translated slug back to source for both pages and singles if (isset($vars['lang'])) { // pagename can be hierarchical: map EACH segment back to its source slug if (!empty($vars['pagename'])) { $pg = (string) $vars['pagename']; $segments = array_values(array_filter(explode('/', trim($pg, '/')))); if (!empty($segments)) { foreach ($segments as $i => $seg) { $src = \AITranslate\AI_Slugs::resolve_any_to_source_slug((string) $seg); if ($src) { $segments[$i] = $src; } } $vars['pagename'] = implode('/', $segments); } } if (!empty($vars['name'])) { $nm = (string) $vars['name']; // If post_type is specified, use it to resolve slug conflicts $expected_post_type = !empty($vars['post_type']) ? $vars['post_type'] : null; $src = \AITranslate\AI_Slugs::resolve_any_to_source_slug($nm, $expected_post_type); if (!$src && !empty($vars['lang'])) { // Generic fallback: find post by translated slug with post_type filter if ($expected_post_type) { $post_id = \AITranslate\AI_Slugs::resolve_translated_slug_to_post_by_type($nm, (string) $vars['lang'], $expected_post_type); } else { $post_id = \AITranslate\AI_Slugs::resolve_translated_slug_to_post($nm, (string) $vars['lang']); } if ($post_id) { $post = get_post($post_id); if ($post && $post->post_status === 'publish') { $src = $post->post_name; } } } if ($src) { $vars['name'] = $src; } } } return $vars; }); /** * Detect page-builder editor / preview context (Elementor, Divi, Beaver, WPBakery, Oxygen, * Bricks, Breakdance, Brizy, Thrive) and WordPress core post preview. * * Editor previews are loaded inside an iframe by a logged-in admin and depend on the * original (untranslated) URL plus query parameters. The plugin must NOT redirect or * translate these requests, otherwise the editor loses preview parameters and the * builder reports a session error. * * @return bool True when the current request is a builder/preview context. */ function ai_translate_is_editor_context() { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only detection only. static $is_editor = null; if ($is_editor !== null) { return $is_editor; } // Known, builder-specific query parameters (verified in each builder's source). $builder_params = array( 'elementor-preview', // Elementor editor preview iframe 'elementor_library', // Elementor library preview 'et_fb', // Divi Visual Builder 'et_pb_preview', // Divi preview 'fl_builder', // Beaver Builder 'vc_editable', // WPBakery / Visual Composer 'vc_action', // WPBakery / Visual Composer 'tve', // Thrive Architect 'ct_builder', // Oxygen Builder 'oxygen', // Oxygen Builder loader URL 'bricks', // Bricks Builder 'breakdance', // Breakdance Builder loader URL (?breakdance=builder) 'breakdance_iframe', // Breakdance Builder iframe 'breakdance_open_document', // Breakdance render document '_breakdance_doing_ajax', // Breakdance frontend AJAX (POST /?page_id=X&_breakdance_doing_ajax=yes) 'brizy-edit', // Brizy Builder 'brizy-edit-iframe', // Brizy Builder iframe 'uxb_iframe', // Flatsome UX Builder iframe (?post_id=X&uxb_iframe=1) 'td_action', // Newspaper tagDiv Composer edit mode (?td_action=tdc) 'tdc_action', // Newspaper tagDiv Composer iframe (?tdc_action=iframe) 'fb-edit', // Avada Live frontend builder (?fb-edit=1) ); foreach ($builder_params as $param) { if (isset($_GET[$param])) { $is_editor = true; return true; } } // WordPress core post preview (preview=true and/or preview_id) — only for users // that can actually edit, to avoid abuse via crafted query strings on public URLs. $has_preview_param = ( (isset($_GET['preview']) && (string) $_GET['preview'] !== 'false') || isset($_GET['preview_id']) || isset($_GET['preview_nonce']) ); if ($has_preview_param && is_user_logged_in()) { $is_editor = true; return true; } // Generic fallback: any iframe loaded from /wp-admin/ by a user with edit capability. // Sec-Fetch-Dest is sent by all modern browsers (Chrome 80+, Firefox 90+, Safari 16.4+). // Combination of iframe destination + wp-admin Referer + edit capability uniquely // identifies a builder preview iframe, so unknown/future builders are also covered // without us needing to learn each builder's specific query parameter. if (is_user_logged_in() && function_exists('current_user_can') && current_user_can('edit_posts')) { $sec_fetch_dest = isset($_SERVER['HTTP_SEC_FETCH_DEST']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_SEC_FETCH_DEST'])) : ''; if ($sec_fetch_dest === 'iframe' || $sec_fetch_dest === 'frame') { $referer = wp_get_referer(); if ($referer && strpos((string) $referer, '/wp-admin/') !== false) { $is_editor = true; return true; } } } $is_editor = false; return false; // phpcs:enable WordPress.Security.NonceVerification.Recommended } /** * Check if current request is an XML file (sitemap, robots.txt, etc.). * * @return bool */ function ai_translate_is_xml_request() { $reqPathRaw = esc_url_raw(wp_unslash((string) ($_SERVER['REQUEST_URI'] ?? ''))); // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqPathRaw, '%25') !== false) { $reqPathRaw = urldecode($reqPathRaw); } $reqPath = ai_translate_strip_site_path((string) wp_parse_url($reqPathRaw, PHP_URL_PATH)); // Check if path ends with .xml if (preg_match('/\.xml$/i', $reqPath)) { return true; } // Check for WordPress sitemap query vars if (isset($_GET['sitemap']) || isset($_GET['sitemap-index'])) { return true; } // Check for sitemap in path (e.g., /wp-sitemap.xml, /sitemap.xml) if (preg_match('/sitemap/i', $reqPath)) { return true; } return false; } /** * Check if the current request's User-Agent is a known search engine crawler. * Used to keep bots on the default language instead of following browser-language * auto-detection (crawlers rarely send a meaningful Accept-Language header, and * should never trigger/see a language redirect for SEO consistency). * * @return bool */ function ai_translate_is_known_bot_ua() { $ua = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_USER_AGENT'])) : ''; return $ua !== '' && (bool) preg_match('/googlebot|googleother|bingbot|yandexbot|baiduspider|duckduckbot|slurp|facebot|ia_archiver/i', $ua); } /** * Whether a URL (Referer/Origin) belongs to this site. * Compares host (and subdirectory path when applicable). Rejects prefix tricks * like https://example.com.attacker.tld/ that pass a naive strpos(home_url()) check. * * @param string $url Absolute URL or Origin header value. * @return bool */ function ai_translate_is_same_site_url($url) { $url = esc_url_raw(trim((string) $url)); if ($url === '') { return false; } $home_parts = wp_parse_url(home_url('/')); $url_parts = wp_parse_url($url); if (!is_array($home_parts) || !is_array($url_parts)) { return false; } $home_host = isset($home_parts['host']) ? strtolower((string) $home_parts['host']) : ''; $url_host = isset($url_parts['host']) ? strtolower((string) $url_parts['host']) : ''; if ($home_host === '' || $url_host === '' || $home_host !== $url_host) { return false; } $home_scheme = isset($home_parts['scheme']) ? strtolower((string) $home_parts['scheme']) : 'http'; $url_scheme = isset($url_parts['scheme']) ? strtolower((string) $url_parts['scheme']) : ''; // Origin headers always include a scheme; Referer should too. Only http/https allowed. if ($url_scheme === '' || !in_array($url_scheme, ['http', 'https'], true) || !in_array($home_scheme, ['http', 'https'], true)) { return false; } $home_port = isset($home_parts['port']) ? (int) $home_parts['port'] : null; $url_port = isset($url_parts['port']) ? (int) $url_parts['port'] : null; if ($home_port !== $url_port) { return false; } // Subdirectory installs: URL path must stay under the site path. $home_path = isset($home_parts['path']) ? untrailingslashit((string) $home_parts['path']) : ''; if ($home_path !== '' && $home_path !== '/') { $url_path = isset($url_parts['path']) ? (string) $url_parts['path'] : '/'; if ($url_path !== $home_path && strpos($url_path, $home_path . '/') !== 0) { return false; } } return true; } /** * Add Accept-Language/Cookie to the Vary header on language-detection-based redirects. * * These redirects (browser-language auto-detect, cookie-based root/path redirects) decide * their target based on request headers, not just the URL. A shared cache (CDN/reverse proxy) * that does not honor Cache-Control but does honor Vary will otherwise reuse one visitor's * redirect for every other visitor of the same URL. This is defense-in-depth alongside the * existing nocache_headers() call, not a replacement for it. * * @return void */ function ai_translate_add_vary_headers() { if (headers_sent()) { return; } $existing = []; foreach (headers_list() as $h) { if (stripos($h, 'Vary:') === 0) { $existing = array_map('trim', explode(',', substr($h, strlen('Vary:')))); break; } } $merged = array_values(array_unique(array_filter(array_merge($existing, ['Accept-Language', 'Cookie'])))); header('Vary: ' . implode(', ', $merged)); } /** * Start output buffering for front-end (skip admin, AJAX, REST, feeds and XML files). * Handles language detection and redirection according to the 4 language switcher rules. */ // Check for _wp_old_slug redirects before other plugin logic (priority 1). // Request path is checked first: if it matches an old slug in DB, redirect. Do not rely on is_404 // because themes/plugins may serve the homepage instead of 404 for unknown slugs. add_action('template_redirect', function () { if (!isset($_SERVER['REQUEST_URI'])) { return; } $request_uri = esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])); $request_path = ai_translate_strip_site_path((string) wp_parse_url($request_uri, PHP_URL_PATH)); if (!is_string($request_path) || $request_path === '' || $request_path === '/') { return; } // Skip if URL has language prefix (let AI Translate handle those) if (preg_match('#^/([a-z]{2})(?:/|$)#i', $request_path)) { return; } // Single-segment path (e.g. /programmeren-met-een-ai-agen/) – might be an old slug $path_parts = array_filter(explode('/', trim($request_path, '/'))); if (empty($path_parts)) { return; } $slug = end($path_parts); global $wpdb; $post_id = $wpdb->get_var($wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_old_slug' AND meta_value = %s LIMIT 1", $slug )); if (!$post_id) { return; } $post = get_post($post_id); if (!$post || $post->post_status !== 'publish') { return; } $permalink = get_permalink($post); if ($permalink) { wp_safe_redirect($permalink, 301); exit; } }, 1); /** * Conservative 404 recovery: when a request would otherwise serve a 404, look * up the basename in the slug map (any language) and redirect to the canonical * translated URL when there is exactly one safe match. Only acts on * /{lang}/... paths and never triggers a new translation. See * docs/404-herstelplan-op-basis-van-url.md (Fase 1). * * Runs at priority 999 so it executes after all other template_redirect * callbacks have had a chance to resolve or fix the request. */ add_action('template_redirect', function () { if (!is_404()) { return; } if (is_admin() || wp_doing_ajax() || wp_is_json_request() || is_feed() || ai_translate_is_xml_request()) { return; } if (!isset($_SERVER['REQUEST_URI'])) { return; } $reqUriRaw = esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])); if (strpos($reqUriRaw, '%25') !== false) { $reqUriRaw = urldecode($reqUriRaw); } $request_path = ai_translate_strip_site_path((string) (wp_parse_url($reqUriRaw, PHP_URL_PATH) ?: '/')); $target_url = \AITranslate\AI_404_Recovery::resolve($request_path); if (!is_string($target_url) || $target_url === '') { return; } nocache_headers(); wp_safe_redirect(esc_url_raw($target_url), 301); exit; }, 999); add_action('template_redirect', function () { // Handle ai_translate_path query var for custom URL resolution if (isset($_GET['ai_translate_path'])) { $path = sanitize_text_field(wp_unslash($_GET['ai_translate_path'])); // Remove the query var so WordPress doesn't see it unset($_GET['ai_translate_path']); // Try to resolve the path without language prefix $resolved_post = \AITranslate\AI_Slugs::resolve_path_to_post('', $path); if ($resolved_post) { // Set the resolved post ID so WordPress loads the correct content global $wp_query; $wp_query->set('p', $resolved_post); $wp_query->set('post_type', 'any'); // Make sure WordPress knows this is a singular post $wp_query->is_singular = true; $wp_query->is_single = true; $wp_query->is_archive = false; $wp_query->is_page = false; } } // Skip admin/AJAX/REST/feeds/XML files if (is_admin() || wp_doing_ajax() || wp_is_json_request() || is_feed() || ai_translate_is_xml_request()) { return; } // Skip page-builder editor/preview iframes (Elementor, Divi, Beaver, ...) and WP post preview. // These are loaded by a logged-in admin and rely on the original URL + query parameters. // Redirecting them to /{lang}/ would drop the preview parameters and break the editor // ("Session expired" in Elementor). The frontend is rendered as-is in the default language. if (ai_translate_is_editor_context()) { return; } $reqPathRaw = esc_url_raw(wp_unslash((string) ($_SERVER['REQUEST_URI'] ?? ''))); // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqPathRaw, '%25') !== false) { $reqPathRaw = urldecode($reqPathRaw); } $reqPath = ai_translate_strip_site_path((string) wp_parse_url($reqPathRaw, PHP_URL_PATH)); $defaultLang = \AITranslate\AI_Lang::default(); // CRITICAL: If we're on /{default}/ and cookie doesn't match, render page FIRST // This prevents redirect before cookie is set if ($reqPath !== '' && preg_match('#^/([a-z]{2})(?:/|$)#i', $reqPath, $m)) { $langFromUrl = strtolower(sanitize_key($m[1])); if ($defaultLang && strtolower($langFromUrl) === strtolower((string) $defaultLang)) { $cookieLang = isset($_COOKIE['ai_translate_lang']) ? strtolower(sanitize_key((string) $_COOKIE['ai_translate_lang'])) : ''; // If cookie doesn't match, set language and render page (don't redirect yet) if ($cookieLang !== '' && strtolower($cookieLang) !== strtolower((string) $defaultLang)) { \AITranslate\AI_Lang::set_cookie((string) $defaultLang); \AITranslate\AI_Lang::set_current((string) $defaultLang); // Add JavaScript redirect to site root after page renders add_action('wp_footer', function() { echo ''; }, 999); // Continue to render page - Rule 3 below will be skipped // Set final language and start OB $finalLang = (string) $defaultLang; \AITranslate\AI_Lang::set_current($finalLang); add_filter('locale', function ($locale) use ($finalLang) { return strtolower($finalLang) . '_' . strtoupper($finalLang); }); \AITranslate\AI_OB::instance()->start(); return; // Stop here - don't execute Rule 3 redirect } } } // Check if we just switched languages - switcher has HIGHEST priority! // Extract language from URL $langFromUrl = null; if ($reqPath !== '' && preg_match('#^/([a-z]{2})(?:/|$)#i', $reqPath, $m)) { $langFromUrl = strtolower(sanitize_key($m[1])); // SECURITY: Prevent unauthorized translation by blocking non-enabled/non-detectable languages // If language is in URL but not enabled or detectable, return 404 to prevent API costs if ($langFromUrl !== null && $defaultLang && strtolower($langFromUrl) !== strtolower((string) $defaultLang)) { $enabled = \AITranslate\AI_Lang::enabled(); $detectable = \AITranslate\AI_Lang::detectable(); $langLower = strtolower($langFromUrl); $isEnabled = in_array($langLower, array_map('strtolower', $enabled), true); $isDetectable = in_array($langLower, array_map('strtolower', $detectable), true); // If language is not enabled and not detectable, return 404 to prevent unauthorized translation if (!$isEnabled && !$isDetectable) { global $wp_query; $wp_query->set_404(); status_header(404); nocache_headers(); return; } // SECURITY: Prevent DOS attack by blocking language/slug mismatches. // Only flag real non-Latin *scripts* (Cyrillic/Greek/Arabic/Hebrew/CJK/…), // never Latin Extended (Maltese ħ, French é, etc.). The old // [\x{0080}-\x{FFFF}] + incomplete accent-lang whitelist falsely 404'd // /mt/…ħ…/ → AI_404_Recovery self-redirect loop (curl: max redirects). $pathWithoutLang = preg_replace('#^/([a-z]{2})/#i', '/', $reqPath); if ($pathWithoutLang !== $reqPath) { $decodedPath = rawurldecode((string) $pathWithoutLang); // Scripts matching AI_Lang::non_latin_codes(): el, Cyrillic family, // he, ar, hi, th, ka, ja kana, CJK, ko Hangul. $hasNonLatinScript = (bool) preg_match( '/[\x{0370}-\x{03FF}\x{0400}-\x{052F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0900}-\x{097F}\x{0E00}-\x{0E7F}\x{10A0}-\x{10FF}\x{3040}-\x{30FF}\x{4E00}-\x{9FFF}\x{AC00}-\x{D7AF}]/u', $decodedPath ); if ($hasNonLatinScript && !\AITranslate\AI_Lang::is_non_latin($langLower)) { global $wp_query; $wp_query->set_404(); status_header(404); nocache_headers(); return; } } } } // RULE 0: Strip explicit ?lang= query parameter from URL → redirect to clean path-based URL // The ?lang= parameter is only used internally by rewrite rules, never in actual visitor URLs. // Examples: /es?lang=fr → /es/ | /?lang=es → /es/ | /?lang={default} → / if (isset($_GET['lang']) && trim(sanitize_text_field(wp_unslash((string) $_GET['lang']))) !== '') { $cleanParams = array_map(static function ($v) { return is_string($v) ? sanitize_text_field(wp_unslash($v)) : $v; }, $_GET); unset($cleanParams['lang']); $targetPath = $reqPath; if ($langFromUrl === null) { // No language in path yet — use the GET parameter to build the correct path $getLang = strtolower(sanitize_key((string) $_GET['lang'])); if ($getLang !== '' && $defaultLang && strtolower($getLang) !== strtolower((string) $defaultLang)) { $targetPath = '/' . $getLang . '/'; } } // Ensure trailing slash (except bare root) if ($targetPath !== '/' && substr($targetPath, -1) !== '/') { $targetPath .= '/'; } $targetUrl = home_url($targetPath); if (!empty($cleanParams)) { $targetUrl = add_query_arg($cleanParams, $targetUrl); } nocache_headers(); wp_safe_redirect(esc_url_raw($targetUrl), 301); exit; } $cookieLang = isset($_COOKIE['ai_translate_lang']) ? strtolower(sanitize_key((string) $_COOKIE['ai_translate_lang'])) : ''; // Ensure search requests have language-prefixed URL (before RULE 4 to prevent early return) // Check for search parameter 's' in query string $hasSearchParam = isset($_GET['s']) && trim(sanitize_text_field(wp_unslash((string) $_GET['s']))) !== ''; if ($hasSearchParam) { // Use cookie language if available, otherwise use URL language, otherwise default $searchLang = $cookieLang !== '' ? $cookieLang : ($langFromUrl !== null ? $langFromUrl : (string) $defaultLang); if ($searchLang !== '' && $defaultLang && strtolower($searchLang) !== strtolower((string) $defaultLang)) { $reqUriRaw = esc_url_raw(wp_unslash((string) ($_SERVER['REQUEST_URI'] ?? ''))); // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqUriRaw, '%25') !== false) { $reqUriRaw = urldecode($reqUriRaw); } $pathNow = ai_translate_strip_site_path((string) wp_parse_url($reqUriRaw, PHP_URL_PATH)); if ($pathNow === '' || $pathNow === '/' || !preg_match('#^/([a-z]{2})(?:/|$)#i', $pathNow)) { $base = home_url('/' . $searchLang . '/'); $target = add_query_arg($_GET, $base); nocache_headers(); wp_safe_redirect($target, 302); exit; } } } // RULE 3: Canonicalize default language - strip /{default}/ prefix, keep the rest. // /{default}/ → / and /{default}/product/x/ → /product/x/ // (Previously always redirected to /, which broke deep default-language URLs // and could bounce against WooCommerce/CPT canonical redirects.) if ($langFromUrl !== null && $defaultLang && strtolower($langFromUrl) === strtolower((string) $defaultLang)) { if ($reqPath !== '/') { \AITranslate\AI_Lang::set_cookie((string) $defaultLang); \AITranslate\AI_Lang::set_current((string) $defaultLang); $stripped = preg_replace('#^/' . preg_quote($langFromUrl, '#') . '(?=/|$)#i', '', $reqPath); if (!is_string($stripped) || $stripped === '') { $stripped = '/'; } if ($stripped !== '/' && substr($stripped, -1) !== '/') { $stripped .= '/'; } nocache_headers(); wp_safe_redirect(home_url($stripped), 302); exit; } } // RULE 4: If cookie exists and on root, redirect to cookie language or serve default if ($reqPath === '/' && $cookieLang !== '' && !$hasSearchParam) { if ($defaultLang && strtolower($cookieLang) !== strtolower((string) $defaultLang)) { // Returning visitor with non-default language preference - redirect to their preferred URL nocache_headers(); ai_translate_add_vary_headers(); wp_safe_redirect(home_url('/' . $cookieLang . '/'), 302); exit; } // Cookie is set to default language - serve default language page $finalLang = (string) $defaultLang; \AITranslate\AI_Lang::set_current($finalLang); add_filter('locale', function ($locale) { $currentLang = \AITranslate\AI_Lang::current(); if ($currentLang) { return strtolower($currentLang) . '_' . strtoupper($currentLang); } return $locale; }); \AITranslate\AI_OB::instance()->start(); return; } // RULE 5: Non-root pages without language prefix - redirect to cookie language URL // If visitor has a non-default language preference and visits a page without a language // prefix, redirect them to the language-prefixed version so they see it in their language. if ($langFromUrl === null && $reqPath !== '/' && $cookieLang !== '' && $defaultLang && strtolower($cookieLang) !== strtolower((string) $defaultLang) && !$hasSearchParam) { nocache_headers(); ai_translate_add_vary_headers(); wp_safe_redirect(home_url('/' . $cookieLang . $reqPath), 302); exit; } $resolvedLang = null; // RULE 1: First visit (no cookie) - detect browser language and redirect if ($cookieLang === '' && $langFromUrl === null && !$hasSearchParam) { // Crawlers must never follow a browser-language redirect: their Accept-Language // header is often generic/absent, and they should consistently see the default // language for SEO/indexing consistency. if (ai_translate_is_known_bot_ua()) { $resolvedLang = (string) $defaultLang; } else { \AITranslate\AI_Lang::reset(); \AITranslate\AI_Lang::detect(); $detected = \AITranslate\AI_Lang::current(); if (!$detected) { $detected = (string) $defaultLang; } $resolvedLang = $detected; // Set cookie (central helper handles domains/headers) \AITranslate\AI_Lang::set_cookie($detected); // Redirect to language URL if not default // IMPORTANT: prevent browsers/proxies from caching this 302 (incognito can get "stuck"). // Vary is defense-in-depth: a shared cache that ignores Cache-Control but honors Vary // will still not reuse this visitor's redirect for a visitor with a different // Accept-Language/cookie state. if ($detected && strtolower($detected) !== strtolower((string) $defaultLang)) { nocache_headers(); ai_translate_add_vary_headers(); // For root: redirect to /{lang}/; for non-root: redirect to /{lang}{path} $targetPath = ($reqPath === '/') ? '/' . $detected . '/' : '/' . $detected . $reqPath; wp_safe_redirect(home_url($targetPath), 302); exit; } // If detected == default, no redirect needed, just set language below } } elseif ($reqPath === '/' && $cookieLang !== '') { // Returning visitor on root: respect stored preference $resolvedLang = $cookieLang; if ($defaultLang && strtolower($cookieLang) !== strtolower((string) $defaultLang)) { nocache_headers(); ai_translate_add_vary_headers(); wp_safe_redirect(home_url('/' . $cookieLang . '/'), 302); exit; } } // Sync cookie if URL has language prefix if ($langFromUrl !== null && ($cookieLang === '' || $cookieLang !== $langFromUrl)) { \AITranslate\AI_Lang::set_cookie($langFromUrl); } // Set language for content // IMPORTANT: If URL has a language code, use it. Otherwise, use default language. // Cookie should ONLY influence behavior on root /, not on other pages! $finalLang = $resolvedLang; if ($finalLang === null) { // If URL has language code, use it. Otherwise, use default. // Do NOT use cookie for pages without language code in URL! if ($langFromUrl !== null) { $finalLang = $langFromUrl; } else { $finalLang = (string) $defaultLang; } } if ($finalLang === '') { $finalLang = (string) $defaultLang; } $finalLang = strtolower(sanitize_key((string) $finalLang)); if ($finalLang !== $cookieLang && $finalLang !== '') { \AITranslate\AI_Lang::set_cookie($finalLang); } \AITranslate\AI_Lang::set_current($finalLang); // Set WordPress locale $localeSetter = function ($locale) use ($finalLang) { if ($finalLang) { return strtolower($finalLang) . '_' . strtoupper($finalLang); } return $locale; }; add_filter('locale', $localeSetter); // Handle full_reset parameter for testing if (isset($_GET['full_reset']) && $_GET['full_reset'] === '1') { \AITranslate\AI_Lang::set_cookie((string) $defaultLang); wp_safe_redirect(home_url('/'), 302); exit; } // Ensure search requests have language-prefixed URL (fallback for is_search() check) if (function_exists('is_search') && is_search()) { $cur = \AITranslate\AI_Lang::current(); $def = \AITranslate\AI_Lang::default(); $pathNow = ai_translate_strip_site_path((string) wp_parse_url(esc_url_raw(wp_unslash((string) ($_SERVER['REQUEST_URI'] ?? ''))), PHP_URL_PATH)); if ($cur && $def && strtolower($cur) !== strtolower($def)) { if ($pathNow === '' || $pathNow === '/' || !preg_match('#^/([a-z]{2})(?:/|$)#i', $pathNow)) { $base = home_url('/' . $cur . '/'); $target = add_query_arg($_GET, $base); wp_safe_redirect($target, 302); exit; } } } \AITranslate\AI_OB::instance()->start(); }, 5); // Priority 5 to run AFTER preloader plugins (e.g. Safelayout Cute Preloader at 2). // Preloader must ob_start first so it injects into AI-Translate output, not vice versa. /** * Client-side cookie-based language redirect fallback. * * When a full-page cache (Kinsta, CDN, Varnish) serves a cached HTML page, PHP * never runs and server-side redirect rules (RULE 4/5 in template_redirect) cannot * fire. This inline script detects a non-default ai_translate_lang cookie on * a URL without a language prefix and performs a client-side redirect — bypassing * the cache layer entirely and restoring expected behavior for returning visitors. */ add_action('wp_head', function () { $default = \AITranslate\AI_Lang::default(); if ($default === '') { return; } $default = strtolower(sanitize_key($default)); ?> ID)) { if ($obj->post_type === 'page') { // get_page_uri builds parent/child slug path without any permalink filter $uri = get_page_uri($obj->ID); if ($uri) { $path = '/' . trim($uri, '/') . '/'; } } else { // Raw post slug + CPT rewrite prefix (e.g. product/ → urun/) so the // language switcher keeps WooCommerce/CPT URLs routable. $slug = get_post_field('post_name', $obj->ID); if ($slug) { $prefix = function_exists('ai_translate_cpt_path_prefix') ? ai_translate_cpt_path_prefix((string) $obj->post_type) : ''; $path = '/' . $prefix . trim((string) $slug, '/') . '/'; } } } elseif ($obj instanceof WP_Term && isset($obj->term_id)) { // ai-translate has no term_link filter, safe to use $p = get_term_link($obj); if ($p && !is_wp_error($p)) { $tp = (string) wp_parse_url($p, PHP_URL_PATH); if ($tp && $tp !== '/') { $path = trailingslashit($tp); } } } elseif ($obj instanceof WP_Post_Type && isset($obj->name)) { $p = get_post_type_archive_link($obj->name); if ($p) { $tp = (string) wp_parse_url($p, PHP_URL_PATH); if ($tp && $tp !== '/') { $path = trailingslashit($tp); } } } return $path ?? $fallback; } /** * Render the floating language switcher with the shared frontend renderer. */ add_action('wp_footer', function () { if (is_admin()) { return; } $position = \AITranslate\AI_Translate_Core::switcher_position(); $valid_positions = array('bottom-left', 'bottom-right', 'top-left', 'top-right', 'none'); if (!in_array($position, $valid_positions, true)) { $position = 'bottom-left'; } if ($position !== 'none') { echo ai_translate_generate_switcher_html( 'dropdown', true, true, 'ai-language-switcher-floating ai-language-switcher-pos-' . $position ); } }); /** * Translate dynamically rendered frontend strings on every frontend request. */ add_action('wp_footer', function () { if (is_admin()) { return; } $restUrl = esc_url_raw(rest_url('ai-translate/v1/batch-strings')); $nonce = wp_create_nonce('ai_translate_front_nonce'); echo ''; }); /** * Check whether a string is a known source string (msgid) in the translation * catalog (.pot) shipped by an active plugin. Used to validate client-side * rendered UI strings (e.g. WooCommerce block cart/checkout) that are absent * from the server-rendered HTML, without opening the batch-strings endpoint * up as a free-form translation proxy. * * @param string $text Normalized source string. * @return bool */ /** * Discover .pot catalogs shipped by active plugins (shared by the catalog validators). * * @return string[] Readable .pot file paths. */ function ai_translate_get_catalog_files() { static $catalogs = null; if ($catalogs === null) { $catalogs = []; $active = (array) get_option('active_plugins', []); foreach ($active as $plugin_file) { $plugin_dir = dirname((string) $plugin_file); if ($plugin_dir === '.' || $plugin_dir === '') { continue; // single-file plugin, ships no catalog } $dir = WP_PLUGIN_DIR . '/' . $plugin_dir; foreach (['/languages', '/i18n/languages'] as $sub) { foreach ((array) glob($dir . $sub . '/*.pot') as $pot) { if (is_string($pot) && is_readable($pot)) { $catalogs[] = $pot; } } } } } return $catalogs; } /** * Collect catalog template strings used to validate client-side rendered UI text: * single-line msgids from active plugins' .pot catalogs (English source strings) * plus translations from installed language packs (.mo) for the site locale, so * runtime strings rendered in the site's own locale are recognized as well. * * @return string[] */ function ai_translate_get_catalog_templates() { static $templates = null; if ($templates !== null) { return $templates; } $templates = []; foreach (ai_translate_get_catalog_files() as $pot) { $contents = (string) file_get_contents($pot); if ($contents === '') { continue; } if (preg_match_all('/^msgid(?:_plural)? "((?:[^"\\\\]|\\\\.)*)"$/m', $contents, $m)) { foreach ($m[1] as $raw) { $templates[] = stripcslashes($raw); } } } // Language packs: runtime strings (WC notices, block UI) are rendered in the site // locale when a pack is installed, so the English msgids alone are not enough. $locale = function_exists('get_locale') ? get_locale() : ''; if ($locale !== '' && !function_exists('get_file_data')) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } if ($locale !== '' && !class_exists('MO')) { require_once ABSPATH . WPINC . '/pomo/mo.php'; } if ($locale !== '') { foreach ((array) get_option('active_plugins', []) as $plugin_file) { $data = get_file_data(WP_PLUGIN_DIR . '/' . $plugin_file, ['TextDomain' => 'Text Domain']); $domain = isset($data['TextDomain']) ? trim((string) $data['TextDomain']) : ''; if ($domain === '') { continue; } $candidates = [ WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.mo', WP_PLUGIN_DIR . '/' . dirname((string) $plugin_file) . '/languages/' . $domain . '-' . $locale . '.mo', ]; foreach ($candidates as $mo_file) { if (!is_readable($mo_file)) { continue; } $mo = new \MO(); if (!$mo->import_from_file($mo_file)) { continue; } foreach ($mo->entries as $entry) { // Include every plural form; translations[0] alone misses rendered plurals. foreach ((array) $entry->translations as $msgstr) { $msgstr = (string) $msgstr; if ($msgstr !== '') { $templates[] = $msgstr; } } } break; // first readable pack for this plugin is enough } } } return $templates; } function ai_translate_is_known_catalog_string($text) { $text = (string) $text; if ($text === '' || mb_strlen($text) > 150) { return false; } static $set = null; if ($set === null) { $set = array_flip(ai_translate_get_catalog_templates()); } return isset($set[$text]); } /** * Whether a string matches a catalog template with placeholders filled in, e.g. a * WooCommerce notice like '"Bike" has been added to your cart.' rendered from the * template '"%s" has been added to your cart.'. Such runtime strings are absent from * both the server HTML and the exact-template catalog check. Matching is anchored and * only accepts templates that actually contain placeholders, so the batch-strings * endpoint stays closed for arbitrary free-form text. * * @param string $text Normalized source string. * @return bool */ function ai_translate_matches_catalog_pattern($text) { $text = (string) $text; if ($text === '' || mb_strlen($text) > 150) { return false; } static $patterns = null; if ($patterns === null) { $patterns = []; foreach (ai_translate_get_catalog_templates() as $template) { // Skip pure-literal templates; only placeholder templates become patterns. if (!preg_match('/%(?:\d+\$)?[sd]/', $template)) { continue; } // Require at least 3 literal letters besides the placeholders: a template // like "%s" alone would compile to ^.+?$ and match any arbitrary string, // reopening the endpoint as a free translation proxy. $literal = preg_replace('/%(?:\d+\$)?[sd%]/', '', $template); if (!preg_match('/\p{L}{3}/u', $literal)) { continue; } $tmp = preg_replace('/%%/', "\x01", $template); $tmp = preg_replace('/%(?:\d+\$)?[sd]/', "\x02", $tmp); $regex = preg_quote($tmp, '/'); $regex = str_replace("\x01", '%', $regex); $regex = str_replace("\x02", '.+?', $regex); $patterns[] = '/^' . $regex . '$/u'; } } foreach ($patterns as $pattern) { if (preg_match($pattern, $text)) { return true; } } return false; } /** * Whether a string exists as a product/variation title or taxonomy term name. * WooCommerce block cart/checkout renders product names and attribute values * client-side via the Store API, so they fail both the page-HTML and catalog * checks. Validating against the site's own database keeps the batch-strings * endpoint closed for arbitrary text while covering catalog content. Returns * false without querying when WooCommerce is not active. * * @param string $text Normalized source string. * @return bool */ function ai_translate_is_known_product_or_term_string($text) { $text = trim((string) $text); if ($text === '' || mb_strlen($text) > 150 || !post_type_exists('product')) { return false; } static $cache = []; if (array_key_exists($text, $cache)) { return $cache[$text]; } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- bounded lookup, static-cached per request $found = (bool) $wpdb->get_var($wpdb->prepare( "SELECT 1 FROM $wpdb->posts WHERE post_type IN ('product','product_variation') AND post_status = 'publish' AND post_title = %s LIMIT 1", $text )); if (!$found) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- bounded lookup, static-cached per request $found = (bool) $wpdb->get_var($wpdb->prepare( "SELECT 1 FROM $wpdb->terms WHERE name = %s LIMIT 1", $text )); } $cache[$text] = $found; return $found; } /** * REST endpoint for dynamic UI attribute translation. */ add_action('rest_api_init', function () { register_rest_route('ai-translate/v1', '/batch-strings', [ 'methods' => 'POST', 'permission_callback' => function (\WP_REST_Request $request) { // Bot check first: bots get empty response anyway, no need for referer/nonce if (ai_translate_is_known_bot_ua()) { $request->set_param('_ai_tr_bot_no_nonce', 1); return true; } // Referer check: must originate from this site (exact host, not prefix match) $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER'])) : ''; if ($referer === '' || !ai_translate_is_same_site_url($referer)) { return new \WP_Error('rest_forbidden', 'Invalid referer', ['status' => 403]); } $nonce = $request->get_header('X-WP-Nonce'); if ($nonce && wp_verify_nonce($nonce, 'wp_rest')) { return true; } $nonce_param = $request->get_param('nonce'); if ($nonce_param && wp_verify_nonce($nonce_param, 'ai_translate_front_nonce')) { return true; } // Public frontend pages can be heavily cached, causing stale inline nonces. // Allow anonymous same-site requests without requiring a valid nonce. if (!is_user_logged_in()) { $origin = isset($_SERVER['HTTP_ORIGIN']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_ORIGIN'])) : ''; // When Origin is present it must match this site; empty Origin is allowed // (some browsers omit it on same-site navigations) because Referer already passed. if ($origin !== '' && !ai_translate_is_same_site_url($origin)) { return new \WP_Error('rest_forbidden', 'Invalid origin', ['status' => 403]); } return true; } return new \WP_Error('rest_forbidden', 'Invalid nonce', ['status' => 403]); }, 'args' => [], 'callback' => function (\WP_REST_Request $request) { $is_bot_request = (bool) $request->get_param('_ai_tr_bot_no_nonce'); // Rate limiting: max 60 requests per minute per IP. // This endpoint is called by client-side JavaScript for UI attribute translation. // Warm cache does not trigger this endpoint (server-side only, no JS execution). // 60/min is generous enough for normal browsing (2-3 calls per page load). $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : 'unknown'; $rate_key = 'ai_tr_rate_' . md5($ip); $rate_count = (int) get_transient($rate_key); if ($rate_count >= 30) { return new \WP_REST_Response(['error' => 'Rate limit exceeded'], 429); } set_transient($rate_key, $rate_count + 1, 60); $arr = $request->get_param('strings'); if (!is_array($arr)) { $arr = []; } // Input limits: max 50 strings of max 150 chars each (UI attributes are short) $arr = array_slice($arr, 0, 50); $arr = array_filter($arr, function ($s) { return is_string($s) && mb_strlen($s) <= 150; }); // Normalize texts: trim and collapse multiple whitespace to single space // Keep mapping between original and normalized for response // Multiple originals can map to same normalized (e.g., "Naam " and "Naam" both become "Naam") $textsNormalized = []; $textsOriginal = []; foreach ($arr as $s) { $original = trim((string) $s); if ($original === '') { continue; } $normalized = preg_replace('/\s+/u', ' ', $original); // Store normalized text (deduplicate) if (!isset($textsNormalized[$normalized])) { $textsNormalized[$normalized] = $normalized; } // Map normalized to original (keep first occurrence, but all originals mapping to same normalized will work) if (!isset($textsOriginal[$normalized])) { $textsOriginal[$normalized] = $original; } } $texts = array_values($textsNormalized); $langParam = sanitize_key((string) ($request->get_param('lang') ?? '')); // Always use lang parameter from JavaScript if provided, as it has the correct page context // Only fall back to Referer/current() if lang param is missing (shouldn't happen in normal operation) if ($langParam !== '') { $lang = $langParam; } else { // Fallback: try to detect from Referer header if available (more reliable than current() for REST calls) $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_REFERER'])) : ''; // Normalize referrer: remove double slashes in path (e.g., /de// -> /de/) if ($referer !== '') { $refererParsed = wp_parse_url($referer); if (isset($refererParsed['path'])) { $refererParsed['path'] = preg_replace('#/+#', '/', $refererParsed['path']); $referer = ''; if (isset($refererParsed['scheme'])) { $referer .= $refererParsed['scheme'] . '://'; } if (isset($refererParsed['host'])) { $referer .= $refererParsed['host']; if (isset($refererParsed['port'])) { $referer .= ':' . $refererParsed['port']; } } $referer .= $refererParsed['path']; if (isset($refererParsed['query'])) { $referer .= '?' . $refererParsed['query']; } if (isset($refererParsed['fragment'])) { $referer .= '#' . $refererParsed['fragment']; } } } if ($referer !== '' && preg_match('#/([a-z]{2})(?:/|$)#i', wp_parse_url($referer, PHP_URL_PATH) ?: '', $m)) { $lang = strtolower($m[1]); } else { $lang = \AITranslate\AI_Lang::current(); } } $default = \AITranslate\AI_Lang::default(); if ($lang === null || $default === null) { return new \WP_REST_Response(['success' => true, 'data' => ['map' => []]], 200); } if (strtolower($lang) === strtolower($default)) { $map = []; foreach ($textsNormalized as $normalized => $orig) { $originalText = isset($textsOriginal[$normalized]) ? $textsOriginal[$normalized] : $normalized; $map[$originalText] = $originalText; } return new \WP_REST_Response(['success' => true, 'data' => ['map' => $map]], 200); } $expiry = max(1, \AITranslate\AI_Translate_Core::cache_expiration_hours()) * HOUR_IN_SECONDS; // Check if translations are stopped (except for cache invalidation) // For batch-strings, we block ALL new translations when stop_translations is enabled // This is different from page translations where we allow cache invalidation // Batch-strings are UI attributes that should not be translated if stop_translations is enabled $stop_translations = (bool) \AITranslate\AI_Translate_Core::get_setting('stop_translations_except_cache_invalidation', false); // Bots get cached translations but no API calls (same as stop_translations) $skip_api = $stop_translations || $is_bot_request; $map = []; $toTranslate = []; $idMap = []; $i = 0; $cacheHits = 0; $cacheMisses = 0; foreach ($texts as $t) { // $t is already normalized from the array_map above $normalized = (string) $t; // Skip empty texts if ($normalized === '') { continue; } // Check if text is already in target language (identical to what translation would be) // If so, skip API call and use source text directly // This prevents unnecessary API calls for texts already in target language $originalText = isset($textsOriginal[$normalized]) ? $textsOriginal[$normalized] : $normalized; // Simple heuristic: if source text looks like it's already in target language, // use it directly without API call. This works for all languages. // We check if the text contains characters typical of the target language $isAlreadyInTargetLang = false; if ($lang !== $default) { // For non-default languages, check if text contains target language specific patterns // This is a simple heuristic - if text already looks translated, use it as-is // We'll rely on the fact that if text is identical after "translation", it was already correct // But we need to detect this BEFORE the API call to avoid unnecessary calls // For now, we'll let it go through cache/API, but we'll handle identical results after API } // Check both cache locations: // 1. ai_tr_attr_* (JavaScript batch-strings cache) // 2. ai_tr_seg_* (PHP translation plan cache, format: ai_tr_seg_{lang}_{md5('attr|md5(text)')}) $cached = false; $attrCacheKey = ai_translate_attr_cache_key($lang, $normalized); $cached = ai_translate_get_attr_transient($attrCacheKey); // If not found in JavaScript cache, check PHP translation plan cache if ($cached === false) { $segCacheKey = ai_translate_seg_attr_cache_key($lang, $normalized); $cached = get_transient($segCacheKey); } if ($cached !== false) { $cachedText = (string) $cached; $cachedTextNormalized = trim($cachedText); $cachedTextNormalized = preg_replace('/\s+/u', ' ', $cachedTextNormalized); $srcLen = mb_strlen($normalized); $cacheInvalid = false; // If stop_translations is enabled or bot request, always use cache (don't validate) if (!$skip_api) { // Validate cache: check if translation is exactly identical to source // NOTE: Identical translations are now accepted as valid (text was already in target language) // This prevents unnecessary API calls for texts already in target language // We only invalidate if text is very short (likely a placeholder) or if it's clearly wrong // For texts > 3 chars, identical translation means text was already in target language - accept it if ($srcLen > 3 && $cachedTextNormalized === $normalized) { // Accept identical translations as valid - text was already in target language // This works for all languages without language-specific checks $cacheInvalid = false; } // For non-Latin target languages: additional check for Latin ratio // Only for longer texts to avoid false positives with brand names if (!$cacheInvalid && mb_strlen($cachedText) > 100 && \AITranslate\AI_Lang::is_non_latin($lang)) { $latinCount = preg_match_all('/[a-zA-Z]/', $cachedText); $latinRatio = mb_strlen($cachedText) > 0 ? ($latinCount / mb_strlen($cachedText)) : 0; if ($latinRatio > 0.4) { $cacheInvalid = true; } } } if ($cacheInvalid && !$skip_api) { // Cache entry is invalid - delete it and re-translate ai_translate_delete_attr_transient($attrCacheKey); $id = 's' . (++$i); $toTranslate[$id] = $normalized; $idMap[$id] = $normalized; $cacheMisses++; } else { // Use original text as key for JavaScript compatibility $originalText = isset($textsOriginal[$normalized]) ? $textsOriginal[$normalized] : $normalized; $map[$originalText] = $cachedText; $cacheHits++; } } else { // Text not in cache if ($skip_api) { // Stop translations or bot: use source text without API call $originalText = isset($textsOriginal[$normalized]) ? $textsOriginal[$normalized] : $normalized; $map[$originalText] = $originalText; $cacheHits++; } else { // Text not in cache - check if it's already in target language before API call // If source text is already in target language, use it directly without API call // This prevents unnecessary API calls for texts already in target language $srcLen = mb_strlen($normalized); $isAlreadyInTargetLang = false; // Simple check: if text is identical after normalization and longer than 3 chars, // it might already be in target language. But we can't know for sure without API. // However, if API returns identical text, we'll handle it after API call. // For now, we'll send it to API but handle identical results specially. $id = 's' . (++$i); $toTranslate[$id] = $normalized; $idMap[$id] = $normalized; $cacheMisses++; } } } if (!empty($toTranslate)) { if ($skip_api) { // Stop translations or bot: block API calls, use source texts // Use source texts for all segments that would have been translated foreach ($toTranslate as $id => $origNormalized) { $originalText = isset($textsOriginal[$origNormalized]) ? $textsOriginal[$origNormalized] : $origNormalized; $map[$originalText] = $originalText; } // Clear $toTranslate to prevent API call $toTranslate = []; } else { // Validate that strings actually exist on the page (security: prevent abuse) $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_REFERER'])) : ''; // Normalize referrer: remove double slashes in path (e.g., /de// -> /de/) if ($referer !== '') { $refererParsed = wp_parse_url($referer); if (isset($refererParsed['path'])) { $refererParsed['path'] = preg_replace('#/+#', '/', $refererParsed['path']); $referer = ''; if (isset($refererParsed['scheme'])) { $referer .= $refererParsed['scheme'] . '://'; } if (isset($refererParsed['host'])) { $referer .= $refererParsed['host']; if (isset($refererParsed['port'])) { $referer .= ':' . $refererParsed['port']; } } $referer .= $refererParsed['path']; if (isset($refererParsed['query'])) { $referer .= '?' . $refererParsed['query']; } if (isset($refererParsed['fragment'])) { $referer .= '#' . $refererParsed['fragment']; } } } if ($referer !== '' && ai_translate_is_same_site_url($referer)) { // Get page HTML (cached using same expiration as translations) $page_cache_key = 'ai_tr_page_html_' . md5($referer); $page_html = get_transient($page_cache_key); if ($page_html === false) { // Fetch page HTML $response = wp_remote_get($referer, array( 'timeout' => 5, 'sslverify' => true, 'headers' => array( 'User-Agent' => 'AI-Translate-Validator/1.0' ) )); if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) { $page_html = wp_remote_retrieve_body($response); // Cache using same expiration as translations $expiry = max(1, \AITranslate\AI_Translate_Core::cache_expiration_hours()) * HOUR_IN_SECONDS; set_transient($page_cache_key, $page_html, $expiry); } else { // Security: if page HTML cannot be fetched, block translation to prevent abuse $toTranslate = []; } } // Validate each string exists on page (in attributes or content) if ($page_html !== '') { $validated = []; foreach ($toTranslate as $id => $text) { // Check if string exists in HTML (escape special regex chars) $text_escaped = preg_quote($text, '/'); // Match in attributes (placeholder, title, aria-label, alt, value) or content if (preg_match('/' . $text_escaped . '/iu', $page_html)) { $validated[$id] = $text; } elseif (ai_translate_is_known_catalog_string($text)) { // Client-side rendered UI strings (e.g. WooCommerce block cart/checkout) // are not present in the server HTML; validate them against the // plugin's shipped translation catalog (.pot) instead. $validated[$id] = $text; } elseif (ai_translate_matches_catalog_pattern($text)) { // Rendered catalog strings with placeholders filled in // (e.g. AJAX WooCommerce notices containing a product name). $validated[$id] = $text; } elseif (ai_translate_is_known_product_or_term_string($text)) { // Client-side rendered catalog content (block cart product // names, attribute values) validated against the database. $validated[$id] = $text; } } // Only allow translation of validated strings $toTranslate = $validated; } else { // Security: if page HTML is empty, block translation to prevent abuse $toTranslate = []; } } else { // Security: if referer is invalid or missing, block translation $toTranslate = []; } } } // Only make API call if there are still segments to translate and stop_translations is not enabled if (!empty($toTranslate) && !$stop_translations) { $plan = ['segments' => []]; foreach ($toTranslate as $id => $text) { // Use 'node' type for longer texts (full sentences), 'meta' for short UI strings // Count words by splitting on whitespace $words = preg_split('/\s+/', trim($text), -1, PREG_SPLIT_NO_EMPTY); $wordCount = count($words); $segmentType = ($wordCount > 4) ? 'node' : 'meta'; $plan['segments'][] = ['id' => $id, 'text' => $text, 'type' => $segmentType]; } $ctx = ['website_context' => \AITranslate\AI_Translate_Core::get_website_context()]; $res = \AITranslate\AI_Batch::translate_plan($plan, $default, $lang, $ctx); $segs = isset($res['segments']) && is_array($res['segments']) ? $res['segments'] : array(); foreach ($toTranslate as $id => $origNormalized) { $tr = isset($segs[$id]) ? (string) $segs[$id] : $origNormalized; // Strip AI model language annotations from translations. // Models sometimes append "(français)", "(NL : tapez un message...)" etc. // Only strip trailing parenthetical text that wasn't in the source. if (strpos($origNormalized, '(') === false && preg_match('/\s*\((?:[a-zA-Z]{2}\s*:|[^)]{2,30}ais|[^)]{2,30}isch|[^)]{2,30}ish|[^)]{2,30}ese|[^)]{2,30}ñol|[^)]{2,30}iano)[^)]*\)\s*$/u', $tr)) { $tr = preg_replace('/\s*\([^)]*\)\s*$/u', '', $tr); // Handle multiple trailing annotations while (strpos($origNormalized, '(') === false && preg_match('/\s*\([^)]*\)\s*$/u', $tr)) { $tr = preg_replace('/\s*\([^)]*\)\s*$/u', '', $tr); } $tr = trim($tr); } // Use original text as key for JavaScript compatibility $originalText = isset($textsOriginal[$origNormalized]) ? $textsOriginal[$origNormalized] : $origNormalized; $map[$originalText] = $tr; // Store in cache using normalized version for consistency // Even if translation is identical to source (text was already in target language), // we cache it so it won't be sent to API again $cacheKey = ai_translate_attr_cache_key($lang, $origNormalized); $trNormalized = trim($tr); $trNormalized = preg_replace('/\s+/u', ' ', $trNormalized); $isIdentical = ($trNormalized === $origNormalized && mb_strlen($origNormalized) > 3); ai_translate_set_attr_transient($cacheKey, $tr, $expiry); } } return new \WP_REST_Response(['success' => true, 'data' => ['map' => $map]], 200); } ]); }); /** * Resolve _wp_old_slug in parse_request and redirect to canonical URL before 404 is set. * Priority 0 so this runs before any 404 redirect plugin (which would send 404s to homepage). */ add_action('parse_request', function ($wp) { if (is_admin() || wp_doing_ajax() || ai_translate_is_xml_request()) { return; } $reqUriRaw = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : ''; if (strpos($reqUriRaw, '%25') !== false) { $reqUriRaw = urldecode($reqUriRaw); } $request_path = ai_translate_strip_site_path(wp_parse_url($reqUriRaw, PHP_URL_PATH) ?: '/'); if (!is_string($request_path) || $request_path === '' || $request_path === '/') { return; } if (preg_match('#^/([a-z]{2})(?:/|$)#i', $request_path)) { return; } $path_parts = array_filter(explode('/', trim($request_path, '/'))); if (empty($path_parts)) { return; } $slug = end($path_parts); global $wpdb; $post_id = $wpdb->get_var($wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_old_slug' AND meta_value = %s LIMIT 1", $slug )); if (!$post_id) { return; } $post = get_post($post_id); if (!$post || $post->post_status !== 'publish') { return; } $permalink = get_permalink($post); if ($permalink) { wp_safe_redirect($permalink, 301); exit; } }, 0); /** * Ensure language-only URLs (e.g., /en/, /de/) route to the site's front page. */ add_action('parse_request', function ($wp) { if (is_admin() || wp_doing_ajax()) { return; } if (ai_translate_is_xml_request()) { return; } $reqUriRaw = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : ''; // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqUriRaw, '%25') !== false) { $reqUriRaw = urldecode($reqUriRaw); } $request_path = ai_translate_strip_site_path(wp_parse_url($reqUriRaw, PHP_URL_PATH) ?: '/'); if (!is_string($request_path)) { $request_path = '/'; } if (preg_match('#^/([a-z]{2})/?$#i', $request_path)) { // Mirror org behaviour: only force front when no other query vars (except 'lang'). // Special-case: when theme uses ?blogpage or native 'paged', route to the posts page. $qv = is_array($wp->query_vars) ? $wp->query_vars : array(); $blogPaged = isset($qv['blogpage']) ? (int)$qv['blogpage'] : (isset($_GET['blogpage']) ? (int) $_GET['blogpage'] : 0); $paged = isset($qv['paged']) ? (int)$qv['paged'] : (isset($_GET['paged']) ? (int) $_GET['paged'] : 0); if ($blogPaged > 0 || $paged > 0) { $posts_page_id = (int) get_option('page_for_posts'); if ($posts_page_id > 0) { $posts_page = get_post($posts_page_id); if ($posts_page) { $existing = is_array($wp->query_vars) ? $wp->query_vars : array(); // Route to posts index by pointing to the posts page slug and paged $wp->query_vars = array_merge($existing, array( 'pagename' => (string) get_page_uri($posts_page_id), 'paged' => $paged ?: $blogPaged, )); return; } } // If no posts page configured, fall back to home with pagination return; } $qv_no_lang = array_diff_key($qv, ['lang' => 1]); if (!empty($qv_no_lang)) { return; } $front_id = (int) get_option('page_on_front'); if ($front_id > 0) { $front_post = get_post($front_id); if ($front_post) { // Merge, do not drop existing query vars (e.g., blogpage/paged) $existing = is_array($wp->query_vars) ? $wp->query_vars : array(); $wp->query_vars = array_merge($existing, array( 'page_id' => $front_id, 'pagename' => (string) $front_post->post_name, 'post_type' => (string) $front_post->post_type, )); $wp->is_page = true; $wp->is_singular = true; $wp->is_home = false; $wp->is_404 = false; } } } }); /** * Route /{lang}/page/{n} to the posts page with proper pagination. */ add_action('parse_request', function ($wp) { if (is_admin() || wp_doing_ajax()) { return; } if (ai_translate_is_xml_request()) { return; } $reqUriRaw = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : ''; // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqUriRaw, '%25') !== false) { $reqUriRaw = urldecode($reqUriRaw); } $path = ai_translate_strip_site_path(wp_parse_url($reqUriRaw, PHP_URL_PATH) ?: '/'); if (!is_string($path) || $path === '/') { return; } if (!preg_match('#^/([a-z]{2})/page/([0-9]+)/?$#i', $path, $m)) { return; } $n = max(1, (int) $m[2]); $posts_page_id = (int) get_option('page_for_posts'); $existing = is_array($wp->query_vars) ? $wp->query_vars : array(); $wp->query_vars = $existing; $wp->query_vars['paged'] = $n; if ($posts_page_id > 0) { $wp->query_vars['pagename'] = (string) get_page_uri($posts_page_id); $wp->is_home = true; $wp->is_page = false; $wp->is_singular = false; $wp->is_404 = false; } else { $wp->is_home = true; $wp->is_404 = false; } }); /** * Ensure /{lang}/?blogpage={n} resolves to the posts index with pagination. * Some themes use a custom query var (?blogpage). Map this early and point to posts page slug. */ /** * Check if a URL path segment matches a public CPT archive. * Returns the post type name when the segment equals the post type name, * the has_archive slug, or the rewrite slug of a CPT that has an archive. * Returns null when no match is found. * * @param string $segment URL segment to test (single, no slashes). * @return string|null Post type name or null. */ function ai_translate_detect_cpt_archive($segment) { if ($segment === '') { return null; } $post_types = get_post_types(['public' => true, '_builtin' => false], 'objects'); foreach ($post_types as $pt) { if (!$pt->has_archive) { continue; } if ($pt->name === $segment) { return $pt->name; } if (is_string($pt->has_archive) && $pt->has_archive === $segment) { return $pt->name; } if (!empty($pt->rewrite['slug']) && $pt->rewrite['slug'] === $segment) { return $pt->name; } } return null; } /** * Return the public rewrite-slug prefix for a post type (e.g. 'product/' or 'urun/'). * Empty for built-in post/page or when the type has no rewrite slug. * * WooCommerce (and other CPTs) often use a rewrite slug that differs from the * post type name (product_base = 'urun' while post type remains 'product'). * All language-prefixed URLs must use the rewrite slug, not the type name. * * @param string $post_type Post type name. * @return string Prefix with trailing slash, or ''. */ function ai_translate_cpt_path_prefix($post_type) { $post_type = (string) $post_type; if ($post_type === '' || $post_type === 'post' || $post_type === 'page') { return ''; } $obj = get_post_type_object($post_type); if (!$obj || empty($obj->rewrite['slug'])) { return ''; } return trim((string) $obj->rewrite['slug'], '/') . '/'; } /** * Resolve a URL path segment to a public CPT name. * Matches the post type name OR its rewrite slug (e.g. 'urun' → 'product'). * * @param string $segment First path segment after the language code. * @return array{type:string,rewrite_slug:string}|null */ function ai_translate_match_cpt_segment($segment) { $segment = trim((string) $segment, '/'); if ($segment === '') { return null; } foreach (get_post_types(['public' => true, '_builtin' => false], 'objects') as $pt) { $rewrite_slug = !empty($pt->rewrite['slug']) ? trim((string) $pt->rewrite['slug'], '/') : (string) $pt->name; if ($segment === (string) $pt->name || $segment === $rewrite_slug) { return [ 'type' => (string) $pt->name, 'rewrite_slug' => $rewrite_slug, ]; } } return null; } /** * Resolve a language-stripped URL path to a taxonomy term archive. * Handles built-in category/tag slugs as well as custom taxonomies whose * rewrite slug differs from the taxonomy name (e.g. WooCommerce 'product_cat' * with rewrite slug 'product-category'). Supports hierarchical term paths * (parent/child) and a trailing /page/N pagination suffix. * * @param string $path Path without language prefix (e.g. 'product-category/dragons/page/2'). * @return array{term:\WP_Term,paged:int}|null Term plus page number, or null when no match. */ function ai_translate_resolve_term_from_path($path) { $path = trim((string) $path, '/'); if ($path === '') { return null; } $paged = 0; if (preg_match('#^(.+)/page/([0-9]+)$#i', $path, $pm)) { $path = trim($pm[1], '/'); $paged = (int) $pm[2]; } $parts = array_values(array_filter(explode('/', $path))); if (empty($parts)) { return null; } $term_slug = (string) end($parts); // Built-in taxonomies: bare term slug as last path segment. foreach (array('category', 'post_tag') as $builtin) { $term = get_term_by('slug', $term_slug, $builtin); if ($term && !is_wp_error($term)) { return array('term' => $term, 'paged' => $paged); } } if (count($parts) < 2) { return null; } // Custom taxonomies: match the URL base against the taxonomy name or its // rewrite slug (may contain multiple segments, e.g. 'shop/category'). $base = implode('/', array_slice($parts, 0, count($parts) - 1)); foreach (get_taxonomies(array('public' => true), 'objects') as $tax) { $candidates = array($tax->name); if (!empty($tax->rewrite['slug'])) { $candidates[] = trim((string) $tax->rewrite['slug'], '/'); } foreach (array_unique($candidates) as $slug_base) { if ($slug_base === '') { continue; } // Exact match, or prefix match for hierarchical term paths (base/parent/child). if ($base === $slug_base || str_starts_with($base, $slug_base . '/')) { $term = get_term_by('slug', $term_slug, $tax->name); if ($term && !is_wp_error($term)) { return array('term' => $term, 'paged' => $paged); } } } } return null; } /** * Map a resolved taxonomy term onto WP query vars (category_name / tag / {taxonomy} + paged). * * @param array $vars Query vars (request filter) or $wp->query_vars. * @param array $resolved_term Result of ai_translate_resolve_term_from_path(). * @return array */ function ai_translate_apply_resolved_term_to_vars(array $vars, array $resolved_term): array { if (empty($resolved_term['term']) || !($resolved_term['term'] instanceof \WP_Term)) { return $vars; } $term = $resolved_term['term']; $tax = $term->taxonomy; if ($tax === 'category') { $vars['category_name'] = $term->slug; } elseif ($tax === 'post_tag') { $vars['tag'] = $term->slug; } else { $vars[$tax] = $term->slug; } if (!empty($resolved_term['paged']) && (int) $resolved_term['paged'] > 1) { $vars['paged'] = (int) $resolved_term['paged']; } return $vars; } /** * Split a registered rewrite-endpoint suffix or a /page/N pagination suffix off * a language-stripped URL path. WooCommerce appends endpoints to the page URL * (e.g. 'my-account/orders', 'checkout/order-received/123') and page-based * archives such as the shop page paginate as 'shop/page/2'. The base path must * be resolved via the slug map; the suffix maps to extra query vars and must be * preserved in canonical redirects. * * @param string $path Path without language prefix (e.g. 'my-account/orders'). * @return array{base:string,suffix:string,endpoint:?string,value:string,paged:int} * base = path without suffix, suffix = raw suffix string ('' when none), * endpoint = query var name for a rewrite endpoint (null when none), * value = endpoint value (e.g. order ID), paged = page number (0 when none). */ function ai_translate_split_endpoint_suffix($path) { $result = array('base' => trim((string) $path, '/'), 'suffix' => '', 'endpoint' => null, 'value' => '', 'paged' => 0); $segments = array_values(array_filter(explode('/', $result['base']), 'strlen')); $count = count($segments); if ($count < 2) { return $result; } // Trailing /page/N pagination. Requires at least 3 segments so the base path // stays non-empty; bare /{lang}/page/N is handled by its dedicated handler. if ($count >= 3 && strtolower($segments[$count - 2]) === 'page' && ctype_digit($segments[$count - 1])) { $result['paged'] = (int) $segments[$count - 1]; $result['base'] = implode('/', array_slice($segments, 0, $count - 2)); $result['suffix'] = 'page/' . $result['paged']; return $result; } // Registered rewrite endpoints (WooCommerce my-account/checkout endpoints, core 'embed', etc.). global $wp_rewrite; if (!isset($wp_rewrite->endpoints) || !is_array($wp_rewrite->endpoints)) { return $result; } foreach ($segments as $i => $segment) { if ($i === 0) { continue; // First segment is always part of the page path. } foreach ($wp_rewrite->endpoints as $endpoint) { if (!is_array($endpoint) || !isset($endpoint[1]) || (string) $endpoint[1] !== $segment) { continue; } // Only endpoints valid on pages or the site root (WooCommerce uses EP_ROOT | EP_PAGES). $mask = isset($endpoint[0]) ? (int) $endpoint[0] : 0; if (($mask & (EP_PAGES | EP_ROOT)) === 0) { continue; } $result['endpoint'] = (isset($endpoint[2]) && $endpoint[2] !== '') ? (string) $endpoint[2] : $segment; $result['value'] = implode('/', array_slice($segments, $i + 1)); $result['base'] = implode('/', array_slice($segments, 0, $i)); $result['suffix'] = $segment . ($result['value'] !== '' ? '/' . $result['value'] : ''); return $result; } } return $result; } // Map translated paths like /{lang}/{translated-slug} to the original content (page or post) add_action('parse_request', function ($wp) { if (is_admin() || wp_doing_ajax()) { return; } if (ai_translate_is_xml_request()) { return; } $reqUriRaw = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : ''; // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqUriRaw, '%25') !== false) { $reqUriRaw = urldecode($reqUriRaw); } $path = ai_translate_strip_site_path(wp_parse_url($reqUriRaw, PHP_URL_PATH) ?: '/'); if (!is_string($path) || $path === '/') { return; } if (!preg_match('#^/([a-z]{2})(?:/(.*))?$#i', $path, $m)) { return; } $lang = strtolower($m[1]); $rest = isset($m[2]) ? (string) $m[2] : ''; $rest = trim($rest, '/'); if ($rest === '') { return; // handled by previous block (language root) } // Decode URL-encoded path (e.g. Hungarian slugs) so slug lookup matches DB if (strpos($rest, '%') !== false) { $rest_decoded = rawurldecode($rest); if (mb_check_encoding($rest_decoded, 'UTF-8')) { $rest = $rest_decoded; } } // Let the dedicated pagination handler manage /{lang}/page/{n} if (preg_match('#^page/[0-9]+/?$#i', $rest)) { return; } // Split a trailing rewrite-endpoint suffix (WooCommerce my-account/checkout // endpoints) or /page/N pagination off the path. The remaining base path is // resolved via the slug map; the suffix is mapped to query vars below and // preserved when redirecting to the canonical translated URL. $suffix_info = ai_translate_split_endpoint_suffix($rest); if ($suffix_info['suffix'] !== '' && $suffix_info['base'] !== '') { $rest = $suffix_info['base']; } // Try exact mapping from translated path to post ID via slug map $post_id = null; $expected_post_type = null; // Check if path contains a CPT rewrite-slug / post-type prefix (e.g. product/slug or urun/slug) $slug_used_for_lookup = null; $detected_post_type = null; $detected_rewrite_slug = null; if (strpos($rest, '/') !== false) { $parts = explode('/', $rest, 2); if (count($parts) === 2) { $potential_prefix = $parts[0]; $potential_slug = trim($parts[1], '/'); $slug_used_for_lookup = $potential_slug; // Match post type name OR rewrite slug (WooCommerce product_base may be 'urun'). $cpt_match = ai_translate_match_cpt_segment($potential_prefix); if ($cpt_match) { $detected_post_type = $cpt_match['type']; $detected_rewrite_slug = $cpt_match['rewrite_slug']; // If slug is empty (only CPT prefix, e.g., /it/product/), route to archive or redirect if ($potential_slug === '') { $cpt_obj = get_post_type_object($detected_post_type); if ($cpt_obj && $cpt_obj->has_archive) { $wp->query_vars = array_diff_key($wp->query_vars, ['ai_translate_path' => 1, 'name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1, 'post_type' => 1]); $wp->query_vars['post_type'] = $detected_post_type; $wp->is_archive = true; $wp->is_singular = false; $wp->is_404 = false; return; } nocache_headers(); wp_safe_redirect(home_url('/' . $lang . '/'), 301); exit; } $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $potential_slug); if ($post_id) { $post = get_post((int) $post_id); if ($post && $post->post_type === $detected_post_type) { $expected_post_type = $detected_post_type; } else { // Post type mismatch, invalid result $post_id = null; } } } } } else { // Single segment: CPT archive root by name or rewrite/archive slug (e.g. /it/product, /it/urun) $cpt_match = ai_translate_match_cpt_segment($rest); if ($cpt_match) { $detected_post_type = $cpt_match['type']; $detected_rewrite_slug = $cpt_match['rewrite_slug']; $cpt_obj = get_post_type_object($detected_post_type); if ($cpt_obj && $cpt_obj->has_archive) { $wp->query_vars = array_diff_key($wp->query_vars, ['ai_translate_path' => 1, 'name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1, 'post_type' => 1]); $wp->query_vars['post_type'] = $detected_post_type; $wp->is_archive = true; $wp->is_singular = false; $wp->is_404 = false; return; } nocache_headers(); wp_safe_redirect(home_url('/' . $lang . '/'), 301); exit; } } // History/cross-language fallback for CPT-prefixed paths (e.g. /fr/product//): // after a re-translation the previous translated slug only exists in the slug-history // table, and cached listing pages can still link to it. Resolve it (current map in any // language + history) so the canonical-redirect block below 301s to the current URL // instead of serving a 404. if (!$post_id && $detected_post_type && $slug_used_for_lookup !== null && $slug_used_for_lookup !== '') { $candidate_ids = \AITranslate\AI_Slugs::find_post_ids_by_translated_slug($slug_used_for_lookup); $unique_target = null; foreach ($candidate_ids as $cid) { $cp = get_post((int) $cid); if ($cp && $cp->post_status === 'publish' && $cp->post_type === $detected_post_type) { if ($unique_target === null) { $unique_target = (int) $cid; } elseif ($unique_target !== (int) $cid) { $unique_target = null; // ambiguous: multiple posts share this old slug break; } } } if ($unique_target !== null) { $post_id = $unique_target; $expected_post_type = $detected_post_type; } } // Fallback: try the entire path as slug (for pages/posts without post type prefix) if (!$post_id) { $slug_used_for_lookup = $rest; $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $rest); } // Cross-language fallback: a slug that exists as translated_slug for OTHER languages // (e.g. /uk/kontakt/ where 'kontakt' is the cs/de/da/etc slug for the same Contact page) // resolves to the correct post. The redirect block below (line ~2050) will then 301 // to the canonical URL for the current language. if (!$post_id && strpos($rest, '/') === false) { $candidate_ids = \AITranslate\AI_Slugs::find_post_ids_by_translated_slug($rest); if (!empty($candidate_ids)) { $unique_target = null; foreach ($candidate_ids as $cid) { $cp = get_post((int) $cid); if ($cp && $cp->post_status === 'publish' && $cp->post_type !== 'attachment') { if ($unique_target === null) { $unique_target = (int) $cid; } elseif ($unique_target !== (int) $cid) { $unique_target = null; break; } } } if ($unique_target !== null) { $post_id = $unique_target; $slug_used_for_lookup = $rest; } } } // CPT archive fallback: check if the segment matches an archive slug that differs from the // post type name (e.g. post type 'service' with has_archive/rewrite slug 'services'). // Only a single-segment path can be a CPT archive root. if (!$post_id && strpos($rest, '/') === false) { $cpt_archive_type = ai_translate_detect_cpt_archive($rest); if ($cpt_archive_type) { $wp->query_vars = array_diff_key($wp->query_vars, ['ai_translate_path' => 1, 'name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1, 'post_type' => 1]); $wp->query_vars['post_type'] = $cpt_archive_type; $wp->is_archive = true; $wp->is_singular = false; $wp->is_404 = false; return; } } if ($post_id) { // Get the post object for further processing $post = get_post((int) $post_id); // Normalize percent-encoded URL parts to UTF-8 before comparing. Slugs with // non-ASCII characters (e.g. legacy 'cannelé') arrive %-encoded from the // browser while the DB stores literal UTF-8; comparing raw strings made // logically identical URLs look different, causing 301s to the same URL // (redirect loop: "page isn't redirecting properly"). $ai_url_norm = static function ($value) { $value = (string) $value; if (strpos($value, '%') !== false) { $decoded = rawurldecode($value); if (mb_check_encoding($decoded, 'UTF-8')) { return $decoded; } } return $value; }; // Check if we found the post via the correct translated slug, or via fallback. // Also enforce the CPT rewrite-slug prefix (e.g. /en/witch/ → /en/urun/witch/). $correct_translated_slug = \AITranslate\AI_Slugs::get_or_generate($post_id, $lang); $found_via_correct_slug = ($correct_translated_slug && $ai_url_norm($slug_used_for_lookup) === $ai_url_norm($correct_translated_slug)); if ($correct_translated_slug && $post) { $cpt_prefix = ai_translate_cpt_path_prefix((string) $post->post_type); $correct_url = home_url('/' . $lang . '/' . $cpt_prefix . $correct_translated_slug . '/'); // Structure check: CPT URLs must include the rewrite slug prefix. $expected_rest = trim($cpt_prefix . $correct_translated_slug, '/'); $current_rest_norm = $ai_url_norm(trim($rest, '/')); $structure_ok = ($current_rest_norm === $ai_url_norm($expected_rest)); if (!$found_via_correct_slug || !$structure_ok) { // Re-attach endpoint/pagination suffix so e.g. order-received and // my-account endpoints survive the canonical redirect. if ($suffix_info['suffix'] !== '') { $correct_url .= $suffix_info['suffix'] . '/'; } // Only redirect if the URL is actually different in decoded form; // redirecting to a URL that only differs in percent-encoding loops forever. $current_url = home_url($path); if (untrailingslashit($ai_url_norm($correct_url)) !== untrailingslashit($ai_url_norm($current_url))) { // Preserve the query string (e.g. ?key=wc_order_... on order-received). $query = (string) wp_parse_url($reqUriRaw, PHP_URL_QUERY); if ($query !== '') { $correct_url .= '?' . $query; } nocache_headers(); wp_safe_redirect($correct_url, 301); exit; } } } $wp->query_vars = array_diff_key($wp->query_vars, ['name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1, 'post_type' => 1]); $posts_page_id = (int) get_option('page_for_posts'); if ($expected_post_type && post_type_exists($expected_post_type)) { // Custom post type $wp->query_vars['post_type'] = $expected_post_type; $wp->query_vars['name'] = $post->post_name; $wp->is_singular = true; $wp->is_single = true; } elseif ($post && $post->post_type === 'page') { if ($posts_page_id > 0 && (int)$post_id === $posts_page_id) { // Treat posts page as home (blog index) so pagination works $wp->query_vars['pagename'] = (string) get_page_uri($posts_page_id); $wp->is_home = true; $wp->is_page = false; $wp->is_singular = false; } else { $wp->query_vars['page_id'] = (int) $post_id; $wp->is_page = true; $wp->is_singular = true; } } else { // Regular post $wp->query_vars['p'] = (int) $post_id; if ($post && !empty($post->post_type)) { $wp->query_vars['post_type'] = $post->post_type; } $wp->is_single = true; $wp->is_singular = true; } // Apply the endpoint/pagination suffix (e.g. WooCommerce 'orders', // 'order-received/123', or 'page/2' on the shop page). if ($suffix_info['endpoint'] !== null) { $wp->query_vars[$suffix_info['endpoint']] = $suffix_info['value']; } elseif ($suffix_info['paged'] > 1) { $wp->query_vars['paged'] = $suffix_info['paged']; } $wp->is_404 = false; return; } // Replicate org behaviour: strip current language from path and map basename back to source $default = \AITranslate\AI_Lang::default(); $clean = preg_replace('#^' . preg_quote($lang, '#') . '/#i', '', ltrim($rest, '/')); $clean = trim($clean, '/'); $basename = trim(basename($clean), '/'); if ($basename !== '') { $srcBase = \AITranslate\AI_Slugs::resolve_any_to_source_slug($basename); if ($srcBase) { $dir = trim((string) dirname($clean), '/'); if ($dir === '\\' || $dir === '.') { $dir = ''; } $sourcePath = $dir !== '' ? ($dir . '/' . $srcBase) : $srcBase; // Resolve across all public post types (page, post, CPT) $public_types = get_post_types(['public' => true], 'names'); $post = get_page_by_path($sourcePath, OBJECT, array_values($public_types)); if ($post) { $wp->query_vars = array_diff_key($wp->query_vars, ['name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1]); $posts_page_id = (int) get_option('page_for_posts'); if ($post->post_type === 'page') { if ($posts_page_id > 0 && (int)$post->ID === $posts_page_id) { $wp->query_vars['pagename'] = (string) get_page_uri($posts_page_id); $wp->is_home = true; $wp->is_page = false; $wp->is_singular = false; } else { $wp->query_vars['page_id'] = (int) $post->ID; $wp->is_page = true; } } else { $wp->query_vars['p'] = (int) $post->ID; $wp->query_vars['post_type'] = $post->post_type; $wp->is_single = true; } $wp->is_singular = true; $wp->is_404 = false; return; } // Fallback: let WP try resolving as page path $wp->query_vars['pagename'] = $sourcePath; // Do not force 404 state here; allow core to resolve properly } } // Fallback als er geen slug-mapregel is (pagina nog nooit vertaald): zoek op post_name (bron) via get_page_by_path. // Zonder dit geeft /{lang}/{bron-slug}/ 404 en faalt warm cache. if ($rest !== '') { $public_types = get_post_types(['public' => true], 'names'); $public_types = array_diff((array) $public_types, ['attachment']); if (empty($public_types)) { $public_types = ['post', 'page']; } $public_types = array_values($public_types); $post = null; if (strpos($rest, '/') !== false) { $parts = explode('/', $rest, 2); $first = $parts[0]; foreach (get_post_types(['public' => true, '_builtin' => false], 'objects') as $pt) { if (!empty($pt->rewrite['slug']) && $pt->rewrite['slug'] === $first) { $post = get_page_by_path($parts[1], OBJECT, [$pt->name]); break; } } if (!$post) { $post = get_page_by_path($rest, OBJECT, $public_types); } } else { $post = get_page_by_path($rest, OBJECT, $public_types); } if (!$post) { $resolved_term = ai_translate_resolve_term_from_path($rest); if ($resolved_term) { $wp->query_vars = array_diff_key($wp->query_vars, ['name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1, 'post_type' => 1]); $wp->query_vars = ai_translate_apply_resolved_term_to_vars($wp->query_vars, $resolved_term); $wp->is_404 = false; return; } } if ($post && isset($post->ID) && isset($post->post_type) && $post->post_type !== 'attachment') { $wp->query_vars = array_diff_key($wp->query_vars, ['name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1, 'post_type' => 1]); $posts_page_id = (int) get_option('page_for_posts'); if ($post->post_type === 'page') { if ($posts_page_id > 0 && (int) $post->ID === $posts_page_id) { $wp->query_vars['pagename'] = (string) get_page_uri($posts_page_id); $wp->is_home = true; $wp->is_page = false; $wp->is_singular = false; } else { $wp->query_vars['page_id'] = (int) $post->ID; $wp->is_page = true; $wp->is_singular = true; } } else { $wp->query_vars['p'] = (int) $post->ID; $wp->query_vars['post_type'] = $post->post_type; $wp->is_single = true; $wp->is_singular = true; } $wp->is_404 = false; return; } } // No resolution found for this language-prefixed URL. // Remove the rewrite-generated pagename (e.g. "es/bestaat-niet") to prevent // WordPress from falling back to the blog index instead of properly triggering a 404. unset($wp->query_vars['pagename']); $wp->query_vars['error'] = '404'; }); /** * Build a root-relative translated path for a post in the given language. * Includes CPT rewrite prefix when applicable (e.g. WooCommerce product_base). * * @param int $post_id Post ID. * @param string $lang Target language code. * @param string $default Default/source language code. * @param string $trail Trailing slash (or empty). * @return string|null Path or null when slug cannot be resolved. */ function ai_translate_build_translated_path($post_id, $lang, $default, $trail = '/') { $post_id = (int) $post_id; $lang = sanitize_key((string) $lang); $default = sanitize_key((string) $default); $translated = \AITranslate\AI_Slugs::get_or_generate($post_id, $lang); if ($translated === null) { return null; } $cpt_prefix = ''; $post = get_post($post_id); if ($post && function_exists('ai_translate_cpt_path_prefix')) { $cpt_prefix = ai_translate_cpt_path_prefix((string) $post->post_type); } $slug = trim((string) $translated, '/'); if (strtolower($lang) === strtolower($default)) { return '/' . $cpt_prefix . $slug . $trail; } return '/' . $lang . '/' . $cpt_prefix . $slug . $trail; } add_filter('post_link', function ($permalink, $post, $leavename) { if (is_admin()) return $permalink; if (ai_translate_is_xml_request()) return $permalink; $lang = \AITranslate\AI_Lang::current(); $default = \AITranslate\AI_Lang::default(); if ($lang === null || $default === null || strtolower($lang) === strtolower($default)) { return $permalink; } $trail = substr($permalink, -1) === '/' ? '/' : ''; $path = ai_translate_build_translated_path((int) $post->ID, $lang, $default, $trail); return $path === null ? $permalink : home_url($path); }, 10, 3); add_filter('page_link', function ($permalink, $post_id, $sample) { if (is_admin()) return $permalink; if (ai_translate_is_xml_request()) return $permalink; $lang = \AITranslate\AI_Lang::current(); $default = \AITranslate\AI_Lang::default(); if ($lang === null || $default === null || strtolower($lang) === strtolower($default)) { return $permalink; } $trail = substr($permalink, -1) === '/' ? '/' : ''; $path = ai_translate_build_translated_path((int) $post_id, $lang, $default, $trail); return $path === null ? $permalink : home_url($path); }, 10, 3); /** * Rewrite internal permalinks (custom post types) to stable translated slugs for current language. */ add_filter('post_type_link', function ($permalink, $post, $leavename, $sample) { if (is_admin()) return $permalink; if (ai_translate_is_xml_request()) return $permalink; $lang = \AITranslate\AI_Lang::current(); $default = \AITranslate\AI_Lang::default(); if ($lang === null || $default === null || strtolower($lang) === strtolower($default)) { return $permalink; } $trail = substr($permalink, -1) === '/' ? '/' : ''; $path = ai_translate_build_translated_path((int) $post->ID, $lang, $default, $trail); return $path === null ? $permalink : home_url($path); }, 10, 4); /** * Keep translated slugs in sync when the original permalink (post_name) changes. * Only regenerates when the source slug actually changed to minimize API calls. */ add_action('save_post', function ($post_id, $post, $update) { static $processing = false; if ($processing) return; if (wp_is_post_revision($post_id)) return; if (!is_object($post) || $post->post_status !== 'publish') return; $current_slug = (string) $post->post_name; $stored = get_post_meta($post_id, '_ai_translate_original_slug', true); if ($stored === $current_slug && $stored !== '') return; $processing = true; update_post_meta($post_id, '_ai_translate_original_slug', $current_slug); $default = \AITranslate\AI_Lang::default(); $enabled = \AITranslate\AI_Translate_Core::enabled_languages(); $detectable = \AITranslate\AI_Translate_Core::detectable_languages(); // Limit synchronous slug translation to enabled+detectable languages. Translating to all // available languages here fired ~35 sequential API calls in the saving request (slow // post saves, painful for WooCommerce bulk imports); other languages generate on demand. $langs = array_values(array_unique(array_merge($enabled, $detectable))); foreach ($langs as $lang) { $lang = sanitize_key((string) $lang); if ($default !== null && strtolower($lang) === strtolower($default)) continue; \AITranslate\AI_Slugs::get_or_generate((int) $post_id, $lang); } $processing = false; }, 10, 3); add_action('post_updated', function ($post_id, $post_after, $post_before) { if (!is_object($post_before) || !is_object($post_after)) return; if ((string) $post_before->post_name === (string) $post_after->post_name) return; // Re-fire core 'save_post' so language switcher / meta handlers run when slug-only updates occur. $cb = function_exists('get_post') ? get_post($post_id) : $post_after; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- intentional: re-trigger WordPress core hook do_action_ref_array('save_post', array($post_id, $cb, true)); }, 10, 3); /** * Clear translation caches affected by a post change. * * Always clears the post's own cache. When the front page is configured to show * the latest blog posts (show_on_front = 'posts') and the changed post is a * regular 'post', also clears the homepage cache (post_id = 0) so the latest * posts list on the translated homepage no longer serves stale content. * * @param int $post_id Post ID. * @param \WP_Post|object|null $post Optional post object (avoids extra get_post call). * @return void */ function ai_translate_clear_caches_for_post_change($post_id, $post = null) { $post_id = (int) $post_id; if ($post_id <= 0) { return; } \AITranslate\AI_Cache_Meta::clear_post_cache($post_id); if (!is_object($post)) { $post = get_post($post_id); } if (!is_object($post) || empty($post->post_type)) { return; } if ($post->post_type !== 'post') { return; } if (get_option('show_on_front') !== 'posts') { return; } \AITranslate\AI_Cache_Meta::clear_post_cache(0); } /** * On content, title, or password changes of an existing published post: clear * translation cache for this post (and the homepage when it lists blog posts) * so the next visit triggers a fresh translation. Password changes must be * included because route_should_be_translated()/route_has_valid_content() skip * translation/caching entirely while a post is password-protected; removing the * password without this check would leave a stale (untranslated) cache in place. */ add_action('post_updated', function ($post_id, $post_after, $post_before) { if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) { return; } if (!is_object($post_before) || !is_object($post_after)) { return; } if ($post_after->post_status !== 'publish') { return; } if ((string) $post_before->post_content === (string) $post_after->post_content && (string) $post_before->post_title === (string) $post_after->post_title && (string) $post_before->post_password === (string) $post_after->post_password) { return; } ai_translate_clear_caches_for_post_change($post_id, $post_after); }, 10, 3); /** * Publish/unpublish/trash/restore transitions: post_updated only fires when an * existing post is updated, so first-time publication and status changes that * affect blog listings (publish<->trash, publish<->draft) need a separate hook. * Only acts when 'publish' is entered or left to avoid unrelated transitions * (e.g. draft -> auto-draft). */ add_action('transition_post_status', function ($new_status, $old_status, $post) { if (!is_object($post) || empty($post->ID)) { return; } if ($new_status === $old_status) { return; } if ($new_status !== 'publish' && $old_status !== 'publish') { return; } if (wp_is_post_revision($post->ID) || wp_is_post_autosave($post->ID)) { return; } ai_translate_clear_caches_for_post_change((int) $post->ID, $post); }, 10, 3); /** * Clear translation cache for a single post when its publicly visible comments change. * Only the affected post is flushed (all languages of that post), never the whole site. * * @param int $comment_id Comment ID * @return void */ function ai_translate_clear_caches_for_comment_change($comment_id, $comment = null) { $comment_id = (int) $comment_id; if ($comment_id <= 0) { return; } // On a force delete, core fires transition_comment_status AFTER the row is gone, // so get_comment() would return null; callers in that path pass the object along. if (!is_object($comment)) { $comment = get_comment($comment_id); } if (!is_object($comment) || empty($comment->comment_post_ID)) { return; } \AITranslate\AI_Cache_Meta::clear_post_cache((int) $comment->comment_post_ID); // Product reviews also change star ratings on listings (shop page, category/tag // archives). Flush those too; bounded because reviews are rare and listing sets small. if (get_post_type((int) $comment->comment_post_ID) === 'product') { ai_translate_flush_product_listing_caches((int) $comment->comment_post_ID); } } /** * Flush listing caches affected by a product change (e.g. review star ratings). * The shop page is a post-scoped route and flushes via clear_post_cache(). Product * category/tag archives are path-based routes without cache-meta rows, so their cache * files are deleted directly per enabled/detectable language. Paginated archive views * (/page/2/) and "related products" on other product pages refresh via normal expiry. * * @param int $product_id Product post ID. * @return void */ function ai_translate_flush_product_listing_caches($product_id) { if (function_exists('wc_get_page_id')) { $shop_id = wc_get_page_id('shop'); if ($shop_id > 0) { \AITranslate\AI_Cache_Meta::clear_post_cache($shop_id); } } $langs = array_values(array_unique(array_merge( \AITranslate\AI_Translate_Core::enabled_languages(), \AITranslate\AI_Translate_Core::detectable_languages() ))); if (empty($langs)) { return; } foreach (['product_cat', 'product_tag'] as $taxonomy) { $terms = wp_get_post_terms($product_id, $taxonomy); if (!is_array($terms)) { continue; } foreach ($terms as $term) { $link = get_term_link($term); if (!is_string($link) || $link === '') { continue; } $path = (string) wp_parse_url($link, PHP_URL_PATH); if ($path === '') { continue; } $path = ai_translate_strip_site_path($path); // Same route formula as AI_OB::current_route_id()'s taxonomy-archive branch. $route = 'path:' . md5(untrailingslashit($path) . '/'); foreach ($langs as $lang) { $lang = sanitize_key((string) $lang); if ($lang === '') { continue; } \AITranslate\AI_Cache::delete(\AITranslate\AI_Cache::key($lang, $route)); } } } } /** * Newly inserted comment: only flush when it was inserted as approved. Pending/spam * are skipped so spammers can never invalidate the cache by submitting comments. * Hooked on 'wp_insert_comment' rather than 'comment_post': wp_insert_comment() * itself never fires 'comment_post' (only wp_new_comment() does), so reviews added * directly (WP-CLI, review importers, programmatic insertion) would never flush. * wp_new_comment() internally calls wp_insert_comment(), so this hook covers both. */ add_action('wp_insert_comment', function ($comment_id, $comment) { if (!is_object($comment) || (string) $comment->comment_approved !== '1') { return; } ai_translate_clear_caches_for_comment_change((int) $comment_id); }, 10, 2); /** * Moderation transitions: flush whenever a comment enters or leaves 'approved' * (moderator approves a pending comment, marks an approved comment as spam/trash, * or restores one). Transitions between non-public states don't affect visitors. */ add_action('transition_comment_status', function ($new_status, $old_status, $comment) { if ($new_status === $old_status) { return; } if ($new_status !== 'approved' && $old_status !== 'approved') { return; } if (!is_object($comment) || empty($comment->comment_ID)) { return; } ai_translate_clear_caches_for_comment_change((int) $comment->comment_ID, $comment); }, 10, 3); /** * Editing an already-approved comment: content/author may have changed, so the * cached translation is stale. Edits on non-approved comments don't affect visitors. */ add_action('edit_comment', function ($comment_id) { $comment = get_comment($comment_id); if (!is_object($comment)) { return; } if ((string) $comment->comment_approved !== '1') { return; } ai_translate_clear_caches_for_comment_change((int) $comment_id); }, 10, 1); /** * One-time warmup: generate translated slugs for existing top-level pages so * language-prefixed URLs immediately resolve (prevents blank pages before first visit). * Mirrors robustness in the original implementation by pre-seeding the slug map. */ add_action('init', function () { if (get_option('ai_translate_slug_warmup_done')) { return; } // Only run on front-end to avoid slowing down admin if (is_admin()) { return; } $default = \AITranslate\AI_Lang::default(); if ($default === null) { update_option('ai_translate_slug_warmup_done', 1); return; } $enabled = \AITranslate\AI_Translate_Core::enabled_languages(); $detectable = \AITranslate\AI_Translate_Core::detectable_languages(); $langs = array_values(array_unique(array_merge($enabled, $detectable))); if (empty($langs)) { update_option('ai_translate_slug_warmup_done', 1); return; } // Warmup all published pages and posts so reverse mapping works immediately $pages = get_posts(array( 'post_type' => array('page', 'post'), 'post_status' => 'publish', 'posts_per_page' => 1000, // Limit to prevent memory issues 'fields' => 'ids', 'orderby' => 'ID', 'order' => 'ASC', 'no_found_rows' => true, // Performance optimization 'update_post_term_cache' => false, 'update_post_meta_cache' => false, )); if (empty($pages)) { update_option('ai_translate_slug_warmup_done', 1); return; } foreach ($pages as $pid) { foreach ($langs as $lang) { $lang = sanitize_key((string) $lang); if (strtolower($lang) === strtolower($default)) { continue; } \AITranslate\AI_Slugs::get_or_generate((int) $pid, $lang); } } update_option('ai_translate_slug_warmup_done', 1); }, 99); /** * Intercept imminent 404s and remap translated slugs to source before WP renders a 404. * This mirrors original behaviour and fixes empty pages when rewrite did not bind. */ add_filter('pre_handle_404', function ($preempt, $wp_query) { if (!is_object($wp_query) || !$wp_query->is_main_query()) { return $preempt; } // Skip admin and default language if (\AITranslate\AI_Lang::is_exempt_request()) { return $preempt; } // Already resolved → nothing to do if (!$wp_query->is_404()) { return $preempt; } $reqPathRaw = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : ''; // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqPathRaw, '%25') !== false) { $reqPathRaw = urldecode($reqPathRaw); } $reqPath = ai_translate_strip_site_path((string) wp_parse_url($reqPathRaw, PHP_URL_PATH)); if ($reqPath === '' || !preg_match('#^/([a-z]{2})(?:/(.*))?$#i', $reqPath, $m)) { return $preempt; } $lang = strtolower($m[1]); $rest = isset($m[2]) ? (string) $m[2] : ''; $rest = trim($rest, '/'); if ($rest === '') { // Language root → front page $front_id = (int) get_option('page_on_front'); if ($front_id > 0) { $wp_query->query_vars['page_id'] = $front_id; $wp_query->is_page = true; $wp_query->is_singular = true; $wp_query->is_home = false; $wp_query->is_404 = false; return true; // short-circuit 404 } return $preempt; } // Try slug mapping: resolve (translated) path to source pagename $source = \AITranslate\AI_Slugs::resolve_any_to_source_slug($rest); if ($source) { $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $source); $post = $post_id ? get_post($post_id) : get_page_by_path($source); if (!$post) { return $preempt; } $wp_query->query_vars = array_diff_key($wp_query->query_vars, ['name' => 1, 'pagename' => 1, 'p' => 1, 'post_type' => 1]); if ($post->post_type === 'page') { $wp_query->query_vars['pagename'] = get_page_uri($post->ID); $wp_query->is_page = true; } else { $wp_query->query_vars['p'] = (int) $post->ID; $wp_query->query_vars['post_type'] = $post->post_type; $wp_query->is_page = false; } $wp_query->is_404 = false; $wp_query->is_singular = true; $wp_query->is_author = false; $wp_query->is_date = false; $wp_query->is_category = false; $wp_query->is_tag = false; $wp_query->is_archive = false; $wp_query->posts = array($post); $wp_query->post = $post; $wp_query->post_count = 1; $wp_query->found_posts = 1; $wp_query->max_num_pages = 1; $wp_query->queried_object = $post; $wp_query->queried_object_id = (int) $post->ID; return true; } // Hierarchische paden: slug map slaat alleen de leaf (post_name) op, niet bv. service/cloud-management. // Probeer eerst het volledige pad, dan het laatste segment, daarna eventueel een slug-alias. if (strpos($rest, '/') !== false) { $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $rest); if (!$post_id) { $base = basename($rest); $post_id = \AITranslate\AI_Slugs::resolve_path_to_post($lang, $base); if (!$post_id) { // Generic fallback: find post by translated slug (prefers non-attachments) $post_id = \AITranslate\AI_Slugs::resolve_translated_slug_to_post($base, $lang); } } if ($post_id) { $post = get_post($post_id); if ($post) { $wp_query->query_vars = array_diff_key($wp_query->query_vars, ['name' => 1, 'pagename' => 1, 'p' => 1, 'post_type' => 1]); if ($post->post_type === 'page') { $wp_query->query_vars['pagename'] = get_page_uri($post_id); $wp_query->is_page = true; } else { $wp_query->query_vars['p'] = (int) $post->ID; $wp_query->query_vars['post_type'] = $post->post_type; $wp_query->is_page = false; } $wp_query->is_404 = false; $wp_query->is_singular = true; $wp_query->is_author = false; $wp_query->is_date = false; $wp_query->is_category = false; $wp_query->is_tag = false; $wp_query->is_archive = false; $wp_query->posts = array($post); $wp_query->post = $post; $wp_query->post_count = 1; $wp_query->found_posts = 1; $wp_query->max_num_pages = 1; $wp_query->queried_object = $post; $wp_query->queried_object_id = (int) $post->ID; return true; } } } return $preempt; }, 10, 2); /** * One-time flush of rewrite rules after deployment so language rules become active * without manual intervention. Safe due to option flag. */ add_action('init', function () { if (!get_option('ai_translate_rules_flushed_v1')) { flush_rewrite_rules(false); update_option('ai_translate_rules_flushed_v1', 1); } }, 20); // Ensure new rewrite rules are flushed once after deployment changes (CPT rules added) add_action('init', function () { if (!get_option('ai_translate_rules_flushed_v2')) { flush_rewrite_rules(false); update_option('ai_translate_rules_flushed_v2', 1); } }, 21); /** * Modify search form action URL to include language code when on a language-prefixed page. * This ensures search forms submit to the correct language URL. */ add_filter('home_url', function ($url, $path, $scheme) { // Only modify on front-end, skip admin/AJAX/REST if (is_admin() || wp_doing_ajax() || wp_is_json_request()) { return $url; } // Skip sitemap and XML requests if (ai_translate_is_xml_request()) { return $url; } // SKIP language switcher URLs - they should always go to root without language prefix if (strpos($url, 'switch_lang=') !== false) { return $url; } // Only modify if path is root (/) or empty - this is where search forms typically point to if ($path !== '/' && $path !== '') { return $url; } // Extract language from current URL if present $reqPathRaw = esc_url_raw(wp_unslash((string) ($_SERVER['REQUEST_URI'] ?? ''))); // URL decode only if double-encoded (contains %25 indicating double encoding) if (strpos($reqPathRaw, '%25') !== false) { $reqPathRaw = urldecode($reqPathRaw); } $reqPath = ai_translate_strip_site_path((string) wp_parse_url($reqPathRaw, PHP_URL_PATH)); $langFromUrl = null; if ($reqPath !== '' && preg_match('#^/([a-z]{2})(?:/|$)#i', $reqPath, $m)) { $langFromUrl = strtolower(sanitize_key($m[1])); } // Only modify if we're currently on a language-prefixed page if ($langFromUrl === null) { return $url; } $defaultLang = \AITranslate\AI_Lang::default(); // Only add language prefix if it's not the default language if ($langFromUrl !== '' && $defaultLang && strtolower($langFromUrl) !== strtolower((string) $defaultLang)) { // Check if URL already has language prefix $urlPath = wp_parse_url($url, PHP_URL_PATH); if ($urlPath && !preg_match('#^/([a-z]{2})(?:/|$)#i', $urlPath)) { // Add language prefix to the URL, preserving any site subpath (e.g. '/wordpress') $parsed = wp_parse_url($url); // Relatieve URLs hebben geen scheme/host; dan niet herschrijven if (!isset($parsed['scheme']) || !isset($parsed['host'])) { return $url; } $basePath = rtrim($parsed['path'] ?? '', '/'); $newPath = $basePath . '/' . $langFromUrl . '/'; $url = $parsed['scheme'] . '://' . $parsed['host']; if (isset($parsed['port'])) { $url .= ':' . $parsed['port']; } $url .= $newPath; if (isset($parsed['query'])) { $url .= '?' . $parsed['query']; } if (isset($parsed['fragment'])) { $url .= '#' . $parsed['fragment']; } } } return $url; }, 10, 3); /** * Add Settings quick link on the Plugins page. */ add_filter('plugin_action_links_' . plugin_basename(__FILE__), function ($links) { $url = admin_url('admin.php?page=ai-translate'); $settings_link = '' . esc_html__('Instellingen', 'ai-translate') . ''; array_unshift($links, $settings_link); return $links; }); /** * Translate search query into the default language before running WP_Query, * and keep the displayed search term as originally entered by the user. */ add_action('pre_get_posts', function ($query) { if (!is_object($query) || !method_exists($query, 'is_main_query')) { return; } if (is_admin() || !$query->is_main_query() || !$query->is_search()) { return; } // Skip when current request is exempt (admin/default language etc.) if (\AITranslate\AI_Lang::is_exempt_request()) { return; } $s = $query->get('s'); if (!is_string($s)) { return; } $s = trim((string) wp_unslash($s)); if ($s === '') { return; } $original = sanitize_text_field($s); // Preserve original for display on results templates $GLOBALS['ai_translate_original_search_query'] = $original; $current = \AITranslate\AI_Lang::current(); $default = \AITranslate\AI_Lang::default(); if ($current === null || $default === null || strtolower($current) === strtolower($default)) { return; } // Rate limiting: max 10 search queries per minute per IP (prevent abuse/cost attacks) // Normal users rarely exceed 1-2 searches per minute; 5 is generous but prevents abuse $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : 'unknown'; $rate_key = 'ai_tr_search_rate_' . md5($ip); $rate_count = (int) get_transient($rate_key); if ($rate_count >= 10) { // Rate limit exceeded: skip translation, use original query return; } set_transient($rate_key, $rate_count + 1, 60); $ctx = array( 'website_context' => (string) \AITranslate\AI_Translate_Core::get_setting('website_context', ''), ); $plan = array('segments' => array( array('id' => 'q1', 'text' => $original, 'type' => 'meta'), )); $res = \AITranslate\AI_Batch::translate_plan($plan, $current, $default, $ctx); $translated = ''; if (is_array($res) && isset($res['segments']) && is_array($res['segments'])) { $translated = (string) ($res['segments']['q1'] ?? ''); } if ($translated !== '') { $query->set('s', $translated); } }, 9); /** * Ensure the visible search query remains the user's original input (not the translated term). */ add_filter('get_search_query', function ($search, $escaped = true) { if (is_admin()) { return $search; } if (isset($GLOBALS['ai_translate_original_search_query'])) { $orig = (string) $GLOBALS['ai_translate_original_search_query']; return $escaped ? esc_attr($orig) : $orig; } return $search; }, 10, 2); /** * Check if permalinks are properly configured (not 'plain'). * Display a warning if they are set to 'plain' since the plugin requires rewrite rules. */ add_action('admin_notices', function () { if (!current_user_can('manage_options')) { return; } // Check if permalinks are set to 'plain' $permalink_structure = get_option('permalink_structure'); if ($permalink_structure === '' || $permalink_structure === null) { // 'plain' structure - show warning echo '
'; echo '

'; echo 'AI Translate Warning: '; echo esc_html__('This plugin requires a permalink structure other than "Plain". ', 'ai-translate'); echo 'Please set your permalinks to "Post name" or another structure. '; echo ''; echo esc_html__('Configure Permalinks', 'ai-translate'); echo ''; echo '

'; echo '
'; } }); /** * Generate language switcher HTML (shared between shortcode and menu) */ function ai_translate_generate_switcher_html($type = 'dropdown', $show_flags = true, $show_codes = true, $class = '') { // Get plugin settings $enabled_languages = \AITranslate\AI_Translate_Core::enabled_languages(); $default_language = \AITranslate\AI_Translate_Core::default_language(); if ($default_language !== '' && !in_array($default_language, $enabled_languages, true)) { $enabled_languages[] = $default_language; } if (empty($enabled_languages) || empty($default_language)) { return ''; } // Determine current language $current_lang = null; $req_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : '/'; $path = (string) wp_parse_url($req_uri, PHP_URL_PATH); if ($path === '') { $path = '/'; } $path = ai_translate_strip_site_path($path); if (preg_match('#^/([a-z]{2})(?=/|$)#i', $path, $matches)) { $current_lang = strtolower($matches[1]); } if (!$current_lang) { $current_lang = $default_language; } // Build base path (remove language prefix if present) $path_no_lang = preg_replace('#^/([a-z]{2})(?=/|$)#i', '', $path); if ($path_no_lang === '') { $path_no_lang = '/'; } $path_no_lang = ai_translate_canonical_path($path_no_lang); $flags_url = plugin_dir_url(__FILE__) . 'assets/flags/'; if ($type === 'inline') { $output = '
'; foreach ($enabled_languages as $lang_code) { $lang_code = sanitize_key($lang_code); if ($lang_code === $current_lang) continue; $lang_label = strtoupper($lang_code); $sub = ai_translate_site_path(); $lang_url = $lang_code === $default_language ? esc_url($sub . $path_no_lang) : esc_url($sub . '/' . $lang_code . $path_no_lang); $output .= ''; if ($show_flags) $output .= '' . esc_attr($lang_label) . ''; if ($show_codes) $output .= '' . esc_html($lang_label) . ''; $output .= ''; } $output .= '
'; } else { $unique_id = 'ai-trans-' . wp_generate_password(8, false); $current_flag = esc_url($flags_url . sanitize_key($current_lang) . '.png'); $current_label = strtoupper($current_lang); $output = '
'; $output .= ''; $output .= '
'; } return $output; } /** * Shortcode callback for [ai_language_switcher]. * * @param array|string $atts Shortcode attributes. * @return string */ function ai_translate_language_switcher_shortcode($atts = []) { $atts = shortcode_atts([ 'type' => 'dropdown', 'show_flags' => 'true', 'show_codes' => 'true', 'class' => '', ], $atts, 'ai_language_switcher'); $type = (isset($atts['type']) && $atts['type'] === 'inline') ? 'inline' : 'dropdown'; $falsey = ['false', '0', 'no', 'off']; $show_flags = !in_array(strtolower((string) $atts['show_flags']), $falsey, true); $show_codes = !in_array(strtolower((string) $atts['show_codes']), $falsey, true); $class = sanitize_text_field((string) $atts['class']); return ai_translate_generate_switcher_html($type, $show_flags, $show_codes, $class); } add_shortcode('ai_language_switcher', 'ai_translate_language_switcher_shortcode'); /** * Register the AI Language Switcher block for block themes (FSE) and the block editor. * Block themes have no Appearance → Menus screen, so the menu meta box integration is * unreachable there. Server-rendered via the same shared renderer as the shortcode. */ add_action('init', function () { if (!function_exists('register_block_type')) { return; } wp_register_script( 'ai-translate-block-editor', plugin_dir_url(__FILE__) . 'assets/ai-translate-block.js', ['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n'], filemtime(plugin_dir_path(__FILE__) . 'assets/ai-translate-block.js'), true ); register_block_type('ai-translate/language-switcher', [ 'editor_script' => 'ai-translate-block-editor', 'attributes' => [ 'type' => ['type' => 'string', 'default' => 'dropdown'], 'showFlags' => ['type' => 'boolean', 'default' => true], 'showCodes' => ['type' => 'boolean', 'default' => true], ], 'render_callback' => function ($attributes) { $type = isset($attributes['type']) && $attributes['type'] === 'inline' ? 'inline' : 'dropdown'; $show_flags = !isset($attributes['showFlags']) || (bool) $attributes['showFlags']; $show_codes = !isset($attributes['showCodes']) || (bool) $attributes['showCodes']; return ai_translate_generate_switcher_html($type, $show_flags, $show_codes); }, ]); }); /** * Enqueue CSS and JavaScript for the language switcher shortcode */ add_action('wp_enqueue_scripts', function() { // Always enqueue for frontend (needed for menu integration) if (!is_admin()) { wp_enqueue_style( 'ai-language-switcher', plugin_dir_url(__FILE__) . 'assets/language-switcher.css', array(), filemtime(plugin_dir_path(__FILE__) . 'assets/language-switcher.css') ); wp_enqueue_script( 'ai-language-switcher', plugin_dir_url(__FILE__) . 'assets/language-switcher.js', array(), filemtime(plugin_dir_path(__FILE__) . 'assets/language-switcher.js'), true ); } }); /** * Add Language Switcher meta box to menu editor */ add_action('admin_head-nav-menus.php', function() { add_meta_box( 'ai-translate-language-switcher', __('🌐 Language Switcher', 'ai-translate'), function() { ?>

// Using native WordPress meta box approach instead of JavaScript manipulation classes) ? $item->classes : array(); if (in_array('ai-language-switcher', $item_classes, true) || $item->object === 'ai_language_switcher') { $is_language_switcher = '1'; update_post_meta($item_id, '_menu_item_is_language_switcher', '1'); } } $switcher_type = get_post_meta($item_id, '_menu_item_switcher_type', true) ?: 'dropdown'; $show_flags = get_post_meta($item_id, '_menu_item_show_flags', true) !== 'false'; // Default true $show_codes = get_post_meta($item_id, '_menu_item_show_codes', true) !== 'false'; // Default true ?>

', '' ); ?>

object === 'ai_language_switcher' || get_post_meta($item->ID, '_menu_item_is_language_switcher', true) === '1'; if ($is_switcher) { if (!in_array('ai-language-switcher', $classes, true)) { $classes[] = 'ai-language-switcher'; } if (!in_array('menu-item-language-switcher', $classes, true)) { $classes[] = 'menu-item-language-switcher'; } if (!in_array('menu-item-has-children', $classes, true)) { $classes[] = 'menu-item-has-children'; } } return $classes; }, 10, 2); /** * Force custom walker when menu contains language switcher items */ add_filter('wp_nav_menu_args', function($args) { // Check if this menu contains language switcher items if (isset($args['menu']) && is_object($args['menu'])) { $menu_items = wp_get_nav_menu_items($args['menu']->term_id); } elseif (isset($args['menu']) && is_numeric($args['menu'])) { $menu_items = wp_get_nav_menu_items($args['menu']); } elseif (isset($args['theme_location'])) { $menu_locations = get_nav_menu_locations(); if (isset($menu_locations[$args['theme_location']])) { $menu_items = wp_get_nav_menu_items($menu_locations[$args['theme_location']]); } } if (isset($menu_items) && is_array($menu_items)) { foreach ($menu_items as $item) { $is_language_switcher = get_post_meta($item->ID, '_menu_item_is_language_switcher', true); if ($is_language_switcher === '1' || $item->object === 'ai_language_switcher') { // This menu contains a language switcher, force our custom walker $args['walker'] = new AI_Translate_Menu_Walker(); break; } } } return $args; }); // Add shortcode for menu language switcher add_shortcode('ai_menu_language_switcher', function($atts) { $atts = shortcode_atts(['show_flags' => 'true', 'show_codes' => 'true'], $atts); $html = ai_translate_generate_switcher_html( 'dropdown', $atts['show_flags'] === 'true', $atts['show_codes'] === 'true' ); if ($html === '') return ''; return ''; }); // Direct database approach: Update menu items when they are saved // Clean up existing menu items that have HTML in title add_action('admin_init', function() { $menu_items = get_posts(array( 'post_type' => 'nav_menu_item', 'meta_key' => '_menu_item_object', 'meta_value' => 'ai_language_switcher', 'posts_per_page' => -1 )); foreach ($menu_items as $menu_item) { $current_title = get_post_meta($menu_item->ID, '_menu_item_title', true); // If title contains HTML, clean it up if (strpos($current_title, 'ID, '_menu_item_menu_item_parent', true) ?: 0, $menu_item->ID, array( 'menu-item-title' => __('Language Switcher', 'ai-translate') ) ); } } }); // Add JavaScript to replace language switcher menu items on frontend add_action('wp_footer', function() { // Only run if we have language switcher menu items $enabled_languages = \AITranslate\AI_Translate_Core::enabled_languages(); $default_language = \AITranslate\AI_Translate_Core::default_language(); if ($default_language !== '' && !in_array($default_language, $enabled_languages, true)) { $enabled_languages[] = $default_language; } if (empty($enabled_languages) || empty($default_language)) { return; } // Determine current language $current_lang = null; $req_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash((string) $_SERVER['REQUEST_URI'])) : '/'; $path = (string) wp_parse_url($req_uri, PHP_URL_PATH); if ($path === '') { $path = '/'; } $path = ai_translate_strip_site_path($path); if (preg_match('#^/([a-z]{2})(?=/|$)#i', $path, $matches)) { $current_lang = strtolower($matches[1]); } if (!$current_lang) { $current_lang = $default_language; } // Build base path (remove language prefix if present) $path_no_lang = preg_replace('#^/([a-z]{2})(?=/|$)#i', '', $path); if ($path_no_lang === '') { $path_no_lang = '/'; } $path_no_lang = ai_translate_canonical_path($path_no_lang); $flags_url = plugin_dir_url(__FILE__) . 'assets/flags/'; // Generate submenu HTML (exclude current language) $submenu_html = ''; // Current language display $current_flag = esc_url($flags_url . sanitize_key($current_lang) . '.png'); $current_label = strtoupper($current_lang); $replacement_html = ''; ?> is always submitted (even when its * parent div is hidden), so its presence proves the form was rendered. On the * initial add via the meta box, custom fields are not yet rendered, and we must * not overwrite the defaults set by the meta-box save handler. */ add_action('wp_update_nav_menu_item', function($menu_id, $menu_item_db_id) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- runs inside core nav-menu save flow which verifies its own update-nav_menu nonce if (!isset($_POST['menu-item-switcher-type'][$menu_item_db_id])) { return; } // phpcs:disable WordPress.Security.NonceVerification.Missing -- this callback runs inside core's wp_update_nav_menu_item save flow which verifies its own update-nav_menu nonce if (isset($_POST['menu-item-is-language-switcher'][$menu_item_db_id])) { update_post_meta($menu_item_db_id, '_menu_item_is_language_switcher', '1'); $switcher_type = isset($_POST['menu-item-switcher-type'][$menu_item_db_id]) ? sanitize_text_field(wp_unslash((string) $_POST['menu-item-switcher-type'][$menu_item_db_id])) : ''; update_post_meta($menu_item_db_id, '_menu_item_switcher_type', $switcher_type); update_post_meta($menu_item_db_id, '_menu_item_show_flags', isset($_POST['menu-item-show-flags'][$menu_item_db_id]) ? 'true' : 'false'); update_post_meta($menu_item_db_id, '_menu_item_show_codes', isset($_POST['menu-item-show-codes'][$menu_item_db_id]) ? 'true' : 'false'); } else { delete_post_meta($menu_item_db_id, '_menu_item_is_language_switcher'); delete_post_meta($menu_item_db_id, '_menu_item_switcher_type'); delete_post_meta($menu_item_db_id, '_menu_item_show_flags'); delete_post_meta($menu_item_db_id, '_menu_item_show_codes'); } // phpcs:enable WordPress.Security.NonceVerification.Missing }, 10, 2); /** * Render language switcher via walker_nav_menu_start_el filter. * This fires for ANY walker (including Elementor Pro, Astra, etc.) so the * switcher is rendered server-side even when the custom walker is bypassed. * Our own AI_Translate_Menu_Walker returns early before parent::start_el(), * so this filter never fires for items already handled by the custom walker. */ add_filter('walker_nav_menu_start_el', function($item_output, $item, $depth, $args) { $classes = is_array($item->classes) ? $item->classes : array(); $is_switcher = in_array('ai-language-switcher', $classes, true) || in_array('menu-item-language-switcher', $classes, true) || $item->object === 'ai_language_switcher' || get_post_meta($item->ID, '_menu_item_is_language_switcher', true) === '1'; if (!$is_switcher) { return $item_output; } $switcher_type = get_post_meta($item->ID, '_menu_item_switcher_type', true) ?: 'dropdown'; $show_flags = get_post_meta($item->ID, '_menu_item_show_flags', true) !== 'false'; $show_codes = get_post_meta($item->ID, '_menu_item_show_codes', true) !== 'false'; return ai_translate_generate_switcher_html( $switcher_type === 'inline' ? 'inline' : 'dropdown', $show_flags, $show_codes ); }, 10, 4); /** * Custom menu walker to render language switcher items */ class AI_Translate_Menu_Walker extends Walker_Nav_Menu { private $skip_item_id = 0; private function is_switcher_item($item) { return $item->object === 'ai_language_switcher' || get_post_meta($item->ID, '_menu_item_is_language_switcher', true) === '1'; } public function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) { if ($this->is_switcher_item($item)) { $position = \AITranslate\AI_Translate_Core::switcher_position(); if ($position !== 'none') { $this->skip_item_id = $item->ID; return; } $this->render_language_switcher_menu_item($output, $item, $depth, $args, $id); return; } parent::start_el($output, $item, $depth, $args, $id); } public function end_el(&$output, $item, $depth = 0, $args = null) { if ($this->skip_item_id === $item->ID) { $this->skip_item_id = 0; return; } parent::end_el($output, $item, $depth, $args); } /** * Render language switcher as a menu item with submenu */ private function render_language_switcher_menu_item(&$output, $item, $depth, $args, $id) { $switcher_type = get_post_meta($item->ID, '_menu_item_switcher_type', true) ?: 'dropdown'; $show_flags = get_post_meta($item->ID, '_menu_item_show_flags', true) !== 'false'; $show_codes = get_post_meta($item->ID, '_menu_item_show_codes', true) !== 'false'; $classes = array('menu-item', 'menu-item-language-switcher'); if ($switcher_type !== 'inline') { $classes[] = 'menu-item-has-children'; } if (!empty($item->classes)) { $classes = array_merge($classes, (array) $item->classes); } $output .= ''; } }