';
// Minimal toggle script + pure JS cookie handling
$restUrl = esc_url_raw(rest_url('ai-translate/v1/batch-strings'));
$nonce = wp_create_nonce('ai_translate_front_nonce');
$is_ssl = is_ssl() ? 'true' : 'false';
echo '';
});
/**
* 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
$ua = isset($_SERVER['HTTP_USER_AGENT']) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';
$is_bot = $ua !== '' && preg_match('/googlebot|googleother|bingbot|yandexbot|baiduspider|duckduckbot|slurp|facebot|ia_archiver/i', $ua);
if ($is_bot) {
$request->set_param('_ai_tr_bot_no_nonce', 1);
return true;
}
// Referer check: must originate from this site
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if ($referer === '' || strpos($referer, home_url()) !== 0) {
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']) ? (string) $_SERVER['HTTP_ORIGIN'] : '';
if ($origin !== '' && strpos($origin, home_url()) !== 0) {
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($_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']) ? (string) $_SERVER['HTTP_REFERER'] : '';
// Normalize referrer: remove double slashes in path (e.g., /de// -> /de/)
if ($referer !== '') {
$refererParsed = 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', 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_tr_attr_' . $lang . '_' . md5($normalized);
$cached = ai_translate_get_attr_transient($attrCacheKey);
// If not found in JavaScript cache, check PHP translation plan cache
if ($cached === false) {
$segKey = 'attr|' . md5($normalized);
$segCacheKey = 'ai_tr_seg_' . $lang . '_' . md5($segKey);
$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) {
$nonLatinLangs = ['zh', 'ja', 'ko', 'ar', 'he', 'th', 'ka'];
if (in_array($lang, $nonLatinLangs, true)) {
$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']) ? (string) $_SERVER['HTTP_REFERER'] : '';
// Normalize referrer: remove double slashes in path (e.g., /de// -> /de/)
if ($referer !== '') {
$refererParsed = 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 !== '' && strpos($referer, home_url()) === 0) {
// 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_hours = isset($settings['cache_expiration']) ? (int) $settings['cache_expiration'] : (14 * 24);
$expiry = max(1, $expiry_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;
}
}
// 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' => isset($settings['website_context']) ? (string)$settings['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_tr_attr_' . $lang . '_' . md5($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']) ? (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']) ? (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']) ? (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;
}
// 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']) ? (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;
}
// Try exact mapping from translated path to post ID via slug map
$post_id = null;
$expected_post_type = null;
// Check if path contains a post type prefix (e.g., service/slug)
$slug_used_for_lookup = null;
$detected_post_type = null;
if (strpos($rest, '/') !== false) {
$parts = explode('/', $rest, 2);
if (count($parts) === 2) {
$potential_post_type = $parts[0];
$potential_slug = trim($parts[1], '/');
$slug_used_for_lookup = $potential_slug;
// Check if this is a registered post type
if (post_type_exists($potential_post_type)) {
$detected_post_type = $potential_post_type;
// If slug is empty (only post type, e.g., /it/service/), route to archive or redirect
if ($potential_slug === '') {
$cpt_obj = get_post_type_object($potential_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'] = $potential_post_type;
$wp->is_archive = true;
$wp->is_singular = false;
$wp->is_404 = false;
return;
}
nocache_headers();
wp_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 === $potential_post_type) {
$expected_post_type = $potential_post_type;
} else {
// Post type mismatch, invalid result
$post_id = null;
}
}
}
}
} else {
// Single segment: check if it's a post type without slug (e.g., /it/service)
if (post_type_exists($rest)) {
$detected_post_type = $rest;
$cpt_obj = get_post_type_object($rest);
if ($cpt_obj && $cpt_obj->has_archive) {
// Route to CPT archive (e.g. /de/service/ → service 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'] = $rest;
$wp->is_archive = true;
$wp->is_singular = false;
$wp->is_404 = false;
return;
}
// Post type without archive, redirect to language root
nocache_headers();
wp_redirect(home_url('/' . $lang . '/'), 301);
exit;
}
}
// 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);
// Check if we found the post via the correct translated slug, or via fallback
$correct_translated_slug = \AITranslate\AI_Slugs::get_or_generate($post_id, $lang);
$found_via_correct_slug = ($correct_translated_slug && $slug_used_for_lookup === $correct_translated_slug);
if (!$found_via_correct_slug && $correct_translated_slug) {
// Found via fallback (source slug), redirect to correct translated URL
if ($expected_post_type && post_type_exists($expected_post_type)) {
$correct_url = home_url('/' . $lang . '/' . $expected_post_type . '/' . $correct_translated_slug . '/');
} elseif ($post && $post->post_type === 'page') {
$correct_url = home_url('/' . $lang . '/' . $correct_translated_slug . '/');
} else {
$correct_url = home_url('/' . $lang . '/' . $correct_translated_slug . '/');
}
// Only redirect if the URL is different
$current_url = home_url($path);
if ($correct_url !== $current_url) {
nocache_headers();
wp_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;
}
$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) {
$term_slug = (strpos($rest, '/') !== false) ? basename($rest) : $rest;
$term = null;
if ($term_slug !== '') {
$term = get_term_by('slug', $term_slug, 'category');
if (!$term || is_wp_error($term)) {
$term = get_term_by('slug', $term_slug, 'post_tag');
}
if (!$term || is_wp_error($term)) {
$parts = array_values(array_filter(explode('/', trim($rest, '/'))));
if (count($parts) >= 2 && taxonomy_exists($parts[0])) {
$term = get_term_by('slug', $parts[1], $parts[0]);
}
}
}
if ($term && !is_wp_error($term)) {
$tax = $term->taxonomy;
$wp->query_vars = array_diff_key($wp->query_vars, ['name' => 1, 'pagename' => 1, 'page_id' => 1, 'p' => 1, 'post_type' => 1]);
if ($tax === 'category') {
$wp->query_vars['category_name'] = $term->slug;
} elseif ($tax === 'post_tag') {
$wp->query_vars['tag'] = $term->slug;
} else {
$wp->query_vars[$tax] = $term->slug;
}
$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';
});
/**
* Rewrite internal permalinks (post/page) to stable translated slugs for current language.
*/
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;
}
$translated = \AITranslate\AI_Slugs::get_or_generate((int) $post->ID, $lang);
if ($translated === null) return $permalink;
// Build path /{lang}/{translated-slug}/ respecting trailing slash (support Unicode slugs)
$trail = substr($permalink, -1) === '/' ? '/' : '';
$path = '/' . $lang . '/' . trim($translated, '/') . $trail;
return 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;
}
$translated = \AITranslate\AI_Slugs::get_or_generate((int) $post_id, $lang);
if ($translated === null) return $permalink;
$trail = substr($permalink, -1) === '/' ? '/' : '';
$path = '/' . $lang . '/' . trim($translated, '/') . $trail;
return 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;
}
$translated = \AITranslate\AI_Slugs::get_or_generate((int) $post->ID, $lang);
if ($translated === null) return $permalink;
// For custom post types, we need to build the path manually
// Extract the post type from the current permalink structure
$post_type = $post->post_type;
$trail = substr($permalink, -1) === '/' ? '/' : '';
// Build path: /{lang}/{post_type}/{translated-slug}/
$path = '/' . $lang . '/' . $post_type . '/' . trim($translated, '/') . $trail;
return 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();
$core = \AITranslate\AI_Translate_Core::get_instance();
$available = array_keys($core->get_available_languages());
$langs = array_values(array_unique(array_merge($enabled, $detectable, $available)));
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;
// Direct call instead of do_action to avoid infinite loop
$cb = function_exists('get_post') ? get_post($post_id) : $post_after;
do_action_ref_array('save_post', array($post_id, $cb, true));
}, 10, 3);
/**
* On content or title changes: clear translation cache for this post so the next
* visit triggers a fresh translation (retranslation).
*/
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) {
return;
}
\AITranslate\AI_Cache_Meta::clear_post_cache($post_id);
}, 10, 3);
/**
* 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']) ? (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) 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 = (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) 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 = 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 = parse_url($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($_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']) ? (string) $_SERVER['REQUEST_URI'] : '/';
$path = (string) 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 = '