'Bearer ' . $api_key, 'Content-Type' => 'application/json', ]; $custom = isset($settings['custom_api_url']) ? (string) $settings['custom_api_url'] : ''; if ($provider === 'custom' && self::is_anthropic_url($custom)) { // Anthropic also expects its own headers (the Bearer header alone is not accepted everywhere). $headers['x-api-key'] = $api_key; $headers['anthropic-version'] = '2023-06-01'; } if ($provider === 'openrouter' || ($provider === 'custom' && strpos($custom, 'openrouter.ai') !== false)) { $headers['HTTP-Referer'] = 'https://github.com/gerard-kanters/ai-translate'; $headers['X-Title'] = 'AI Translate'; } return $headers; } /** * Send a JSON API request with a consistent HTTP lifecycle. * * @param string $endpoint API endpoint. * @param array $headers Request headers. * @param string|array $body Request body. * @param int $timeout Request timeout in seconds. * @return array|\WP_Error */ public static function remote_api_post(string $endpoint, array $headers, $body, int $timeout = 45, bool $adaptReasoning = true) { $send = static function ($payload) use ($endpoint, $headers, $timeout) { return wp_remote_post($endpoint, [ 'headers' => $headers, 'timeout' => $timeout, 'connect_timeout' => min(10, max(1, $timeout)), 'sslverify' => true, 'body' => is_string($payload) ? $payload : wp_json_encode($payload), ]); }; $resp = $send($body); if (!$adaptReasoning || is_wp_error($resp) || (int) wp_remote_retrieve_response_code($resp) !== 400) { return $resp; } // Some models (e.g. Gemini via OpenRouter) cannot switch thinking off. Retry once with the // lowest effort the model accepts and remember it, so the next request is right at once. $text = (string) wp_remote_retrieve_body($resp); if (!\AITranslate\is_mandatory_reasoning_error($text)) { return $resp; } $data = is_string($body) ? json_decode($body, true) : $body; if (!is_array($data)) { return $resp; } $adapted = \AITranslate\mandatory_reasoning_retry($data); if ($adapted === null) { return $resp; } [$data, $learned] = $adapted; $retry = $send($data); if (!is_wp_error($retry) && (int) wp_remote_retrieve_response_code($retry) === 200 && $learned !== []) { $provider = (string) (self::settings()['api_provider'] ?? ''); $model = (string) ($data['model'] ?? ''); if ($provider !== '' && $model !== '') { self::remember_reasoning_params($provider, $model, ['params' => $learned, 'v' => self::REASONING_PROBE_VERSION, 'mandatory' => true]); } } return $retry; } /** Providers that have a preferred (default) model list. */ private const DEFAULT_PROVIDERS = ['openai', 'openrouter', 'deepinfra', 'deepseek', 'groq']; /** * Preferred models per provider, best first, from includes/default-models.json. * * @return array */ public static function default_model_lists(): array { return \AITranslate\default_model_lists(); } /** Preferred models for a provider key, or for the host of a custom API URL. */ public static function default_models_for(string $provider, string $api_url = ''): array { $lists = self::default_model_lists(); if ($provider === 'custom') { if (self::is_anthropic_url($api_url)) { return $lists['anthropic'] ?? []; } $host = self::api_host($api_url); $provider = $host === 'openrouter.ai' ? 'openrouter' : ($host === 'api.openai.com' ? 'openai' : ''); } return $lists[$provider] ?? []; } /** The default (best) model of a provider, '' when there is none. */ private static function default_model(string $provider): string { return in_array($provider, self::DEFAULT_PROVIDERS, true) ? (self::default_model_lists()[$provider][0] ?? '') : ''; } /** * The model to use for translating. A saved model that the plugin no longer offers (removed from the * model list because it is not a text model or does not work) falls back to the provider's default. */ public static function effective_model(string $provider, string $model): string { if ($provider === 'custom' && $model !== '' && self::is_anthropic_url((string) (self::settings()['custom_api_url'] ?? ''))) { // Anthropic only has Claude models: a model left over from another API host cannot work. return stripos($model, 'claude') === 0 ? $model : self::ANTHROPIC_FALLBACK_MODELS[0]; } $default = self::default_model($provider); if ($model === '' || $default === '') { return $model; } if (self::filter_admin_models([['id' => $model]], $provider) === []) { return $default; } // The provider stopped offering the model (retired): use the first preferred model still offered. if (self::model_is_retired($provider, $model)) { foreach (self::default_model_lists()[$provider] as $candidate) { if (!self::model_is_retired($provider, $candidate)) { return $candidate; } } } return $model; } /** Cron hook that refreshes the stored model list of the active provider. */ public const LIVE_MODELS_HOOK = 'ai_translate_refresh_live_models'; public static function store_live_models(string $provider, array $rawModels): void { if (self::default_model($provider) !== '') { \AITranslate\store_live_models($provider, $rawModels); } } public static function model_is_retired(string $provider, string $model): bool { return self::default_model($provider) !== '' && \AITranslate\model_is_retired($provider, $model); } /** Cron callback for LIVE_MODELS_HOOK: fetch /models for the active provider and store the IDs. */ public static function refresh_live_models(): void { \AITranslate\refresh_default_models(); // Weekly check inside; does nothing on the other days. $settings = self::settings(true); $provider = (string) ($settings['api_provider'] ?? ''); if (self::default_model($provider) === '') { return; } $key = self::api_key_for($settings, $provider); $base = self::get_api_url_for_provider($provider); if ($key === '' || $base === '') { return; } $resp = wp_remote_get(rtrim($base, '/') . '/models', [ 'headers' => self::build_api_headers($key, $provider, []), 'timeout' => 20, 'sslverify' => true, ]); if (is_wp_error($resp) || (int) wp_remote_retrieve_response_code($resp) !== 200) { return; // Keep the previous list; it expires by itself. } $data = json_decode((string) wp_remote_retrieve_body($resp), true); if (is_array($data) && isset($data['data']) && is_array($data['data'])) { self::store_live_models($provider, $data['data']); } } /** Make sure the daily refresh is scheduled, and run one soon when nothing is stored yet. */ public static function schedule_live_models_refresh(): void { if (!wp_next_scheduled(self::LIVE_MODELS_HOOK)) { wp_schedule_event(time() + 60, 'daily', self::LIVE_MODELS_HOOK); } } public static function unschedule_live_models_refresh(): void { wp_clear_scheduled_hook(self::LIVE_MODELS_HOOK); } /** * Notice for the admin when the saved model can no longer be used, naming what is used instead. * Empty string when the saved model is fine. */ public static function unavailable_model_notice(string $provider, string $saved): string { if ($provider === '' || $saved === '' || self::default_model($provider) === '') { return ''; } $effective = self::effective_model($provider, $saved); if ($effective === $saved) { return ''; } return sprintf( /* translators: 1: saved model ID, 2: model used instead */ __('The model "%1$s" is no longer offered by the provider. Translations now use "%2$s". Save the settings to keep this choice, or pick another model.', 'ai-translate'), $saved, $effective ); } /** Cron hook that measures reasoning behaviour of a thinking model in the background. */ public const PROBE_HOOK = 'ai_translate_probe_reasoning'; /** @var array Probes requested during this request, queued once settings are saved. */ private static $probeRequests = []; private static function probe_pending_key(string $provider, string $model): string { return 'ai_tr_probe_pending_' . md5($provider . '|' . $model); } /** Whether a background probe for this model is queued or running (the page polls for its result). */ public static function reasoning_probe_pending(string $provider, string $model): bool { return get_transient(self::probe_pending_key($provider, $model)) !== false; } /** * Ask for a background reasoning probe. It is queued at the end of the request, after the settings * were saved, because the job reads the saved API key (the cron event carries no credentials). */ public static function request_reasoning_probe(string $provider, string $model): bool { if (!function_exists('wp_schedule_single_event')) { return false; } if (self::$probeRequests === []) { add_action('shutdown', [self::class, 'flush_reasoning_probes']); } self::$probeRequests[] = [$provider, $model]; set_transient(self::probe_pending_key($provider, $model), 1, 10 * MINUTE_IN_SECONDS); return true; } public static function flush_reasoning_probes(): void { $requests = self::$probeRequests; self::$probeRequests = []; foreach ($requests as [$provider, $model]) { $saved = self::api_key_for(self::settings(true), $provider); $args = [$provider, $model]; $queued = $saved !== '' && (wp_next_scheduled(self::PROBE_HOOK, $args) !== false || wp_schedule_single_event(time(), self::PROBE_HOOK, $args) !== false); if (!$queued) { delete_transient(self::probe_pending_key($provider, $model)); } } if ($requests !== [] && function_exists('spawn_cron')) { spawn_cron(); } } /** Cron callback for PROBE_HOOK. */ public static function run_scheduled_probe($provider, $model): void { $provider = (string) $provider; $model = (string) $model; $settings = self::settings(true); $key = self::api_key_for($settings, $provider); $base = $provider === 'custom' ? (string) ($settings['custom_api_url'] ?? '') : self::get_api_url_for_provider($provider); if ($key === '' || $base === '' || $model === '') { delete_transient(self::probe_pending_key($provider, $model)); return; } if (function_exists('set_time_limit')) { @set_time_limit(240); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged } $endpoint = rtrim($base, '/') . self::get_model_endpoint_path($model); $headers = self::build_api_headers($key, $provider, ['custom_api_url' => (string) ($settings['custom_api_url'] ?? '')]); try { $entry = self::probe_reasoning_params($endpoint, $headers, $model); } catch (\Throwable $e) { $entry = null; } if ($entry !== null) { self::remember_reasoning_params($provider, $model, $entry); } delete_transient(self::probe_pending_key($provider, $model)); } /** * Cached accessor for plugin settings. Avoids repeated get_option() calls per request. * * @return array */ public static function settings(bool $refresh = false): array { static $s = null; if ($s === null || $refresh) { $s = get_option('ai_translate_settings', []); } return is_array($s) ? $s : []; } /** * Get a single setting value from the cached settings array. * * @param string $key * @param mixed $default * @return mixed */ public static function get_setting(string $key, $default = null) { $s = self::settings(); return isset($s[$key]) ? $s[$key] : $default; } /** * @return array */ public static function enabled_languages(): array { $v = self::settings()['enabled_languages'] ?? []; return is_array($v) ? array_values($v) : []; } /** * @return string */ public static function default_language(): string { return (string) (self::settings()['default_language'] ?? ''); } /** * @return array */ public static function detectable_languages(): array { $v = self::settings()['detectable_languages'] ?? []; return is_array($v) ? array_values($v) : []; } /** * @return bool */ public static function is_multi_domain(): bool { return !empty(self::settings()['multi_domain_caching']); } /** * Cache expiration in hours. Minimum value is 14 days (336 h). * * @return int */ public static function cache_expiration_hours(): int { return (int) (self::settings()['cache_expiration'] ?? (14 * 24)); } /** * Language switcher position. * * @return string */ public static function switcher_position(): string { return (string) (self::settings()['switcher_position'] ?? 'bottom-left'); } /** * Resolve the active domain from the current HTTP request. * Falls back to SERVER_NAME and home_url() host. * * @return string */ public static function get_active_domain(): string { static $domain = null; if ($domain !== null) { return $domain; } $domain = ''; if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) { $domain = sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])); if (strpos($domain, ':') !== false) { $domain = strtok($domain, ':'); } } if (empty($domain) && isset($_SERVER['SERVER_NAME']) && !empty($_SERVER['SERVER_NAME'])) { $domain = sanitize_text_field(wp_unslash($_SERVER['SERVER_NAME'])); } if (empty($domain)) { $domain = wp_parse_url(home_url(), PHP_URL_HOST); if (empty($domain)) { $domain = 'default'; } } return $domain; } /** * Get website context for a domain. Supports per-domain context when multi-domain caching is enabled. * * @param string $domain Optional domain override. * @return string */ public static function get_website_context(string $domain = ''): string { $settings = self::settings(); $multi_domain = !empty($settings['multi_domain_caching']); if ($multi_domain) { $active = $domain !== '' ? $domain : self::get_active_domain(); $domain_context = isset($settings['website_context_per_domain']) && is_array($settings['website_context_per_domain']) ? $settings['website_context_per_domain'] : []; if (isset($domain_context[$active]) && trim((string) $domain_context[$active]) !== '') { return trim((string) $domain_context[$active]); } } $context = isset($settings['website_context']) ? (string) $settings['website_context'] : ''; return trim($context); } /** * Get homepage meta description for a domain. Per-domain when multi-domain caching is enabled. * * @param string $domain Optional domain override. * @return string */ public static function get_homepage_meta_description(string $domain = ''): string { $settings = self::settings(); $multi_domain = !empty($settings['multi_domain_caching']); if ($multi_domain) { $active = $domain !== '' ? $domain : self::get_active_domain(); $domain_meta = isset($settings['homepage_meta_description_per_domain']) && is_array($settings['homepage_meta_description_per_domain']) ? $settings['homepage_meta_description_per_domain'] : []; if (isset($domain_meta[$active]) && trim((string) $domain_meta[$active]) !== '') { return trim((string) $domain_meta[$active]); } } $homepage = isset($settings['homepage_meta_description']) ? (string) $settings['homepage_meta_description'] : ''; return trim($homepage); } /** * List of supported API providers. * * @return array */ public static function get_api_providers() { return [ 'openai' => [ 'name' => 'OpenAI/ChatGPT', 'base_url' => 'https://api.openai.com/v1' ], 'deepseek' => [ 'name' => 'DeepSeek', 'base_url' => 'https://api.deepseek.com/v1' ], 'openrouter' => [ 'name' => 'OpenRouter', 'base_url' => 'https://openrouter.ai/api/v1' ], 'groq' => [ 'name' => 'Groq', 'base_url' => 'https://api.groq.com/openai/v1' ], 'deepinfra' => [ 'name' => 'DeepInfra', 'base_url' => 'https://api.deepinfra.com/v1/openai' ], 'custom' => [ 'name' => 'Custom API', 'base_url' => '' ], ]; } /** * Resolve API base URL for a provider. * * @param string $provider * @return string */ public static function get_api_url_for_provider($provider) { $providers = self::get_api_providers(); if (isset($providers[$provider])) { return (string) ($providers[$provider]['base_url'] ?? ''); } return ''; } /** * Base URL of the API for a provider: the provider's own, or for "custom" the URL from the settings. * * @param string $provider Provider key. * @param array $settings Plugin settings. * @return string Empty when there is none. */ public static function api_base_url($provider, array $settings): string { if ($provider === 'custom') { return isset($settings['custom_api_url']) ? (string) $settings['custom_api_url'] : ''; } return (string) self::get_api_url_for_provider($provider); } /** * Keep the models the admin dropdown shows: text in and out, no image/audio/embedding families. * * @param array $rawModels Rows from the provider /models response. * @param string $provider Provider key. * @return string[] Model IDs. */ public static function filter_admin_models(array $rawModels, string $provider): array { $rawModels = array_filter($rawModels, function ($m) use ($provider) { if (!is_array($m)) { return true; } $arch = isset($m['architecture']) && is_array($m['architecture']) ? $m['architecture'] : null; if ($arch !== null) { $output = isset($arch['output_modalities']) && is_array($arch['output_modalities']) ? $arch['output_modalities'] : null; $input = isset($arch['input_modalities']) && is_array($arch['input_modalities']) ? $arch['input_modalities'] : null; if ($output !== null && !in_array('text', $output, true)) { return false; } if ($input !== null && !in_array('text', $input, true)) { return false; } } if ($provider === 'deepinfra' && array_key_exists('metadata', $m)) { $meta = is_array($m['metadata']) ? $m['metadata'] : null; if ($meta === null || empty($meta['context_length'])) { return false; } } return true; }); $models = array_map(function ($m) { return is_array($m) && isset($m['id']) ? $m['id'] : (is_string($m) ? $m : null); }, $rawModels); $models = array_filter($models, function ($model) use ($provider) { if (!is_string($model) || $model === '') { return false; } if (preg_match('/^(babbage-|davinci-)/i', $model)) { return false; } // Image/audio/embedding families (all providers), including Groq Orpheus speech. if (preg_match('/(dall-e|whisper|audio|image|realtime|transcribe|tts|embedding|moderation|codex|seedream|bria|sora|computer-use|deep-research|orpheus)/i', $model)) { return false; } // Embedding IDs without the word "embedding" (bge/e5/gte/text2vec/…). if (preg_match('/sentence-transformers\/|(?:^|\/|[-_])(?:bge|e5|gte|text2vec)(?:[-_\/]|$)|embed(?:ding)?[-_\/]|[-_\/]embed(?:ding)?(?:[-_\/]|$)|nemotron-embed/i', $model)) { return false; } // OpenRouter batch-only IDs are not chat/completions models. if (preg_match('/:batch$/i', $model)) { return false; } // OpenAI: chat-test failures for instruct / search-preview / chat-latest / pro / live / o3-pro. // Keep bare chat-latest, gpt-4o, gpt-5/mini, gpt-6-luna/sol, o1-pro. if ($provider === 'openai') { if (preg_match('/instruct|search-preview|search-api|-chat-latest|^gpt-live|^o3-pro(?:-|$)/i', $model)) { return false; } if (preg_match('/^gpt-.*-pro(?:-\d{4}-\d{2}-\d{2})?$/i', $model)) { return false; } } // OpenRouter: account/policy, harness-only, region, apply-tools, broken chat IDs, media/stealth/tool models. if ($provider === 'openrouter') { if (preg_match('/muse-spark|(?:^|\/)sakana\/|relace-apply|thinkingmachines\/inkling(?:-small)?:free|lyria|gemini-omni|nano-banana|bodybuilder|scaledown|^stealth\/|ripple-65b|prompt-guard/i', $model)) { return false; } static $openrouterDrop = [ 'amazon/nova-premier-v1' => true, 'anthracite-org/magnum-v4-72b' => true, 'baidu/ernie-4.5-vl-424b-a47b' => true, 'cognitivecomputations/dolphin-mistral-24b-venice-edition' => true, 'deepseek/deepseek-chat-v3-0324' => true, 'deepseek/deepseek-r1' => true, 'deepseek/deepseek-r1-distill-llama-70b' => true, 'deepseek/deepseek-v3.2-exp' => true, 'google/gemma-2-27b-it' => true, 'google/gemma-3-12b-it' => true, 'google/gemma-3-4b-it' => true, 'inclusionai/ling-3.0-flash' => true, 'inclusionai/ling-3.0-flash-fin' => true, 'inclusionai/ling-3.0-flash-fin:free' => true, 'inclusionai/ling-3.0-flash-sante:free' => true, 'inclusionai/ling-3.0-flash-vl' => true, 'kwaipilot/kat-coder-pro-v2.5' => true, 'mancer/weaver' => true, 'meta-llama/llama-4-scout' => true, 'meta-llama/llama-guard-4-12b' => true, 'microsoft/phi-4' => true, 'microsoft/wizardlm-2-8x22b' => true, 'mistralai/mistral-small-24b-instruct-2501' => true, 'moonshotai/kimi-k2' => true, 'moonshotai/kimi-k2-0905' => true, 'moonshotai/kimi-k2-thinking' => true, 'nousresearch/hermes-3-llama-3.1-405b' => true, 'nousresearch/hermes-3-llama-3.1-70b' => true, 'nvidia/nemotron-3.5-content-safety' => true, 'nvidia/nemotron-3.5-lightning:free' => true, 'google/lyria-3-pro-preview' => true, 'openai/gpt-5-pro' => true, 'openai/gpt-5.2-chat' => true, 'openai/gpt-5.2-pro' => true, 'openai/gpt-5.4-pro' => true, 'openai/gpt-5.5-pro' => true, 'openai/o1-pro' => true, 'prism-ml/ternary-bonsai-2-27b' => true, 'qwen/qwen-2.5-72b-instruct' => true, 'qwen/qwen-2.5-7b-instruct' => true, 'qwen/qwen3-32b' => true, 'rekaai/reka-flash-3' => true, 'sao10k/l3.1-euryale-70b' => true, 'sao10k/l3.3-euryale-70b' => true, 'stepfun/step-3.5-flash' => true, 'tencent/hunyuan-a13b-instruct' => true, 'xiaomi/mimo-v2.5' => true, 'xiaomi/mimo-v2.6-pro' => true, 'xiaomi/mimo-v2.6-pro-ultraspeed' => true, '~z-ai/glm-latest' => true, 'undi95/remm-slerp-l2-13b' => true, ]; if (isset($openrouterDrop[$model])) { return false; } } // Groq: safety classifiers (not chat models) and a model that writes its thinking into the text. if ($provider === 'groq' && preg_match('/prompt-guard|safeguard|^qwen\/qwen3\.6-27b$/i', $model)) { return false; } // DeepInfra: full-context default max_tokens, or chat test timed out at 20s. if ($provider === 'deepinfra') { static $deepinfraDrop = [ 'Qwen/Qwen2.5-72B-Instruct' => true, 'Qwen/Qwen3-14B' => true, 'Qwen/Qwen3.5-9B' => true, 'Qwen/Qwen3.8-27B' => true, 'Qwen/Qwen3-30B-A3B' => true, 'Qwen/Qwen3-32B' => true, 'Qwen/Qwen3.6-27B' => true, 'XiaomiMiMo/MiMo-V2.6-Flash' => true, 'deepseek-ai/DeepSeek-R1-0528' => true, 'deepseek-ai/DeepSeek-V3.1' => true, 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo' => true, 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo' => true, 'nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B' => true, 'nvidia/NVIDIA-Nemotron-3.5-Lightning' => true, 'openai/gpt-oss-120b-Ultra' => true, 'thinkingmachines/Inkling' => true, 'zai-org/GLM-4.6' => true, 'zai-org/GLM-5.3' => true, ]; if (isset($deepinfraDrop[$model])) { return false; } } return true; }); $models = array_values($models); sort($models); return $models; } // ── Responses API helpers ────────────────────────────────────────── // Some models (e.g. OpenAI Codex) only support /v1/responses instead of // /v1/chat/completions. The helpers below detect this automatically from // the 404 error body and cache the result so subsequent calls go directly // to the correct endpoint. /** * Return the endpoint path for a model: '/responses' or '/chat/completions'. * Uses a transient cache so the detection only happens once. * * @param string $model * @return string '/responses' | '/chat/completions' */ public static function get_model_endpoint_path(string $model): string { if ($model === '') { return '/chat/completions'; } $key = 'ai_tr_resp_' . md5($model); if (get_transient($key)) { return '/responses'; } return '/chat/completions'; } /** * Mark a model as requiring the /responses endpoint (cached 24 h). * * @param string $model */ public static function mark_model_responses_api(string $model): void { $key = 'ai_tr_resp_' . md5($model); set_transient($key, '1', DAY_IN_SECONDS); } /** * Check whether an HTTP error body indicates the model requires /responses. * * @param string $body Raw HTTP response body. * @return bool */ public static function is_responses_api_error(string $body): bool { if (strpos($body, 'v1/responses') !== false) { return true; } return strpos(strtolower($body), 'not a chat model') !== false; } /** * Convert a chat/completions request body to the /responses format. * * @param array $body Body with 'model' and 'messages'. * @return array Body with 'model', 'instructions', 'input'. */ public static function convert_body_to_responses(array $body): array { $result = ['model' => $body['model']]; $input = []; if (isset($body['messages']) && is_array($body['messages'])) { foreach ($body['messages'] as $msg) { if (isset($msg['role']) && $msg['role'] === 'system') { $result['instructions'] = $msg['content']; } else { $input[] = $msg; } } } $result['input'] = $input; // Pass through compatible parameters if (isset($body['temperature'])) { $result['temperature'] = $body['temperature']; } if (isset($body['reasoning_effort'])) { $result['reasoning'] = ['effort' => $body['reasoning_effort']]; } elseif (isset($body['reasoning'])) { $result['reasoning'] = $body['reasoning']; } return $result; } /** * Whether a model ID is in the GPT-5 family or newer (gpt-5, gpt-5.1, gpt-6-luna, gpt-6.1-terra, …). * These are reasoning models: without an explicit reasoning_effort they pick their own default and * spend extra time and output tokens thinking about a translation. gpt-4o / gpt-4.1 do not match. * * @param string $model Model ID (may include a provider prefix such as openai/). * @return bool */ public static function is_gpt5_or_newer(string $model): bool { return (bool) preg_match('#(?:^|/)gpt-(?:[5-9]|[1-9]\d)(?:[.\-_/]|$)#i', $model); } /** * Lowest practical reasoning effort for translation workloads. * * GPT-5.1+ and GPT-6+ (incl. Luna, Terra): low — OpenAI's recommended starting point for * latency-sensitive work; more stable than none for translation quality ('minimal' is * rejected by these models; measured: an explicit effort cut a 15-segment call from * 3.7–4.7s to ~2.6s and removed the hidden reasoning tokens). * Original GPT-5: minimal (none not supported). O-series: low. * gpt-5-pro: high (only supported value). DeepSeek/Gemini: none (off). * * @param string $model Model ID (may include provider prefix). * @return string Effort level: none|minimal|low|high. */ public static function resolve_min_reasoning_effort(string $model): string { $isGpt5 = self::is_gpt5_or_newer($model); $isOSeries = (bool) preg_match('/(?:^|\/)o\d/i', $model); $isPro = (bool) preg_match('/(?:^|\/|-)pro(?:-|\/|$)/i', $model); // gpt-5-pro only supports high. if ($isGpt5 && $isPro) { return 'high'; } // O-series: none is often unsupported. if ($isOSeries) { return 'low'; } // GPT-5.1+ and GPT-6+ (Luna, Terra, …): low (better quality/stability than none for translations). // Original GPT-5 family (gpt-5, gpt-5-mini, gpt-5-nano): minimal (lowest supported; none not available). if ($isGpt5) { if (preg_match('#(?:^|/)gpt-5(?![.\d])#i', $model)) { return 'minimal'; } return 'low'; } // DeepSeek V4, Gemini (via OpenRouter/DeepInfra): fully off. return 'none'; } /** * Whether an API error body rejects the temperature value sent with the request. * * @param string $body Raw HTTP response body. * @return bool */ public static function is_unsupported_temperature_error(string $body): bool { return \AITranslate\is_temperature_error($body); } /** * Remember whether a model accepts temperature 0, for later translation requests. * * @param string $provider Provider key. * @param string $model Model ID. * @param bool $supported True when temperature 0 was accepted. * @return void */ public static function remember_temperature_supported(string $provider, string $model, bool $supported): void { if ($provider === '' || $model === '') { return; } self::with_settings_lock(static function () use ($provider, $model, $supported) { $settings = self::settings(true); if (($settings['temperature_supported'][$provider][$model] ?? null) === $supported) { return; } if (!isset($settings['temperature_supported']) || !is_array($settings['temperature_supported'])) { $settings['temperature_supported'] = []; } if (!isset($settings['temperature_supported'][$provider]) || !is_array($settings['temperature_supported'][$provider])) { $settings['temperature_supported'][$provider] = []; } $settings['temperature_supported'][$provider][$model] = $supported; update_option('ai_translate_settings', $settings); self::settings(true); }); } /** Bump when the probe changes in a way that makes earlier results worth measuring again. */ private const REASONING_PROBE_VERSION = 2; /** * Parameter sets that providers use to limit or switch off a model's hidden reasoning, in the * order the probe tries them. The probe keeps the first one that measurably lowers the * reasoning tokens, so a provider that silently ignores a parameter is skipped. */ private const REASONING_PROBE_CANDIDATES = [ ['reasoning_effort' => 'low'], ['reasoning_effort' => 'none'], ['reasoning_effort' => 'minimal'], ['reasoning' => ['effort' => 'low']], ['reasoning' => ['effort' => 'none']], ['thinking' => ['type' => 'disabled']], ['reasoning' => ['enabled' => false]], ]; /** * Number of hidden reasoning tokens a response reports, or null when the provider does not * report them (chat/completions and /responses use different fields). * * @param mixed $data Decoded JSON response. * @return int|null */ public static function extract_reasoning_tokens($data): ?int { if (!is_array($data) || !isset($data['usage']) || !is_array($data['usage'])) { return null; } $usage = $data['usage']; foreach (['completion_tokens_details', 'output_tokens_details'] as $details) { if (isset($usage[$details]) && is_array($usage[$details]) && isset($usage[$details]['reasoning_tokens'])) { return (int) $usage[$details]['reasoning_tokens']; } } return null; } /** * Find out how to keep a model from thinking when it translates, by measuring. * * Sends one translation request without any reasoning parameter and reads the reasoning * tokens from the response. A model that does not think (or a provider that does not report * tokens) needs nothing, so null comes back. Otherwise the candidate parameter sets are tried * one by one until one cuts the reasoning tokens to a fifth or less; that set is returned. * The result is stored by remember_reasoning_params() and used by adjust_body_for_model(). * * @param string $endpoint Full chat/completions or /responses URL. * @param array $headers Request headers. * @param string $model Model ID. * @return array{params:array,baseline_tokens:int,tokens:int}|null */ public static function probe_reasoning_params(string $endpoint, array $headers, string $model): ?array { $isResponses = substr($endpoint, -10) === '/responses'; $start = microtime(true); // A model that thinks a lot can take 20+ seconds for the baseline request alone. if (function_exists('set_time_limit')) { @set_time_limit(150); } $payload = wp_json_encode([ 'segments' => [ ['id' => 't1', 'text' => 'Samenwerken in een veilige digitale werkomgeving', 'type' => 'node'], ['id' => 't2', 'text' => 'Beheer documenten, groepen en discussies op één plek.', 'type' => 'node'], ['id' => 't3', 'text' => 'Kies een pakket dat bij uw organisatie past.', 'type' => 'node'], ['id' => 't4', 'text' => 'Neem contact met ons op voor een demonstratie.', 'type' => 'node'], ['id' => 't5', 'text' => 'Werk op uw laptop, telefoon of tablet.', 'type' => 'node'], ['id' => 't6', 'text' => 'Start vandaag nog met een gratis proefperiode.', 'type' => 'node'], ], 'instruction' => 'Translate every segment from Dutch to Swedish. Return ONLY valid JSON in this exact format: {"translations": {"": ""}}.', ]); $send = static function (array $extra, int $timeout = 30) use ($endpoint, $headers, $model, $payload, $isResponses) { $body = [ 'model' => $model, 'messages' => [ ['role' => 'system', 'content' => 'You are a professional translator. Follow the instruction exactly.'], ['role' => 'user', 'content' => $payload], ], ]; foreach ($extra as $key => $value) { $body[$key] = $value; } if ($isResponses) { $body = self::convert_body_to_responses($body); } $resp = self::remote_api_post($endpoint, $headers, $body, $timeout, false); if (is_wp_error($resp) || (int) wp_remote_retrieve_response_code($resp) !== 200) { return null; } return json_decode((string) wp_remote_retrieve_body($resp), true); }; // The baseline is the slow one: a model that thinks hard can need half a minute. $baselineData = $send([], 40); if ($baselineData === null) { // One failed request is often a busy moment at the provider: try once more before giving up. sleep(2); $baselineData = $send([], 40); } if ($baselineData === null) { return null; // the request failed: nothing was measured, so try again next time } $baseline = self::extract_reasoning_tokens($baselineData); $baselineReported = $baseline !== null; if ($baseline === null) { // Not reported (e.g. Anthropic): estimate it from the output tokens the answer does not explain. $baseline = \AITranslate\estimate_hidden_reasoning_tokens($baselineData, (string) self::extract_message_content($baselineData)); } if ($baseline === null || $baseline < 20) { // Measured: this model does not think (or the provider does not say). Remember that. return ['params' => [], 'baseline_tokens' => (int) $baseline, 'tokens' => (int) $baseline, 'v' => self::REASONING_PROBE_VERSION]; } $budgetSpent = false; $best = null; // the candidate that lowered the reasoning most, kept in case none reaches a fifth foreach (self::REASONING_PROBE_CANDIDATES as $candidate) { if (microtime(true) - $start > 100) { // under the 150 s limit set above $budgetSpent = true; break; } $data = $send($candidate); if ($data === null) { continue; // the model rejected this parameter } $tokens = self::extract_reasoning_tokens($data); if ($tokens === null && !$baselineReported) { $tokens = \AITranslate\estimate_hidden_reasoning_tokens($data, (string) self::extract_message_content($data)); } if ($tokens === null && isset($data['usage'])) { // The baseline reported reasoning tokens, so a response that leaves the field out // (DeepSeek does this once thinking is off) did not reason. $tokens = 0; } if ($tokens !== null && $tokens <= max(2, intdiv($baseline, 5))) { return ['params' => $candidate, 'baseline_tokens' => $baseline, 'tokens' => $tokens, 'v' => self::REASONING_PROBE_VERSION]; } if ($tokens !== null && ($best === null || $tokens < $best['tokens'])) { $best = ['params' => $candidate, 'baseline_tokens' => $baseline, 'tokens' => $tokens, 'v' => self::REASONING_PROBE_VERSION]; } } // No candidate reached a fifth, but one cut the reasoning by at least 60%: that is still a switch // worth using (a model such as gpt-oss-120b on Groq only goes from ~300 to ~70 tokens at 'low'). if ($best !== null && $best['tokens'] <= intdiv($baseline * 2, 5)) { return $best; } if ($budgetSpent) { // Not every candidate was tried (a slow baseline used up the time), so "nothing helped" // would be a guess: report that nothing was measured and try again later. return null; } // It thinks, but no parameter set helped. Remember that too; the name-based guesses still apply. return ['params' => [], 'baseline_tokens' => $baseline, 'tokens' => $baseline, 'v' => self::REASONING_PROBE_VERSION]; } /** * Whether the reasoning probe has to run for a model: only when nothing is stored yet (or the * stored result comes from an older version of the probe). The probe costs several requests, * and the settings page validates the connection every time it opens. */ public static function reasoning_probe_needed(string $provider, string $model): bool { $stored = self::settings()['reasoning_params'][$provider][$model] ?? null; return !is_array($stored) || (int) ($stored['v'] ?? 0) < self::REASONING_PROBE_VERSION; } /** * Whether the reasoning probe failed for this model in the last hour (no answer or an error). * Without this a model that cannot translate, or answers too slowly, is probed again on every * validation, which makes the settings page wait for the probe's timeout each time. */ public static function reasoning_probe_failed_recently(string $provider, string $model): bool { return get_transient(self::reasoning_probe_failure_key($provider, $model)) !== false; } public static function note_reasoning_probe_failure(string $provider, string $model): void { set_transient(self::reasoning_probe_failure_key($provider, $model), 1, HOUR_IN_SECONDS); } private static function reasoning_probe_failure_key(string $provider, string $model): string { return 'ai_tr_probe_fail_' . md5($provider . '|' . $model); } /** * Run a read-modify-write of the settings option while holding a short lock. * * Probe results are written from several requests at once (validations and background * probes). Without a lock each one reads the whole option, adds its own entry and writes it * back, so a slower request overwrites the entries of the others. * * @param callable $callback Receives nothing; reads settings(true) itself and writes. * @return void */ private static function with_settings_lock(callable $callback): void { $lock = 'ai_translate_settings_lock'; $held = false; for ($i = 0; $i < 100; $i++) { if (add_option($lock, (string) time(), '', 'no')) { $held = true; break; } // A lock older than 30 seconds belongs to a request that died. if (time() - (int) get_option($lock, 0) > 30) { delete_option($lock); continue; } usleep(100000); } try { $callback(); } finally { if ($held) { delete_option($lock); } } } /** * Store (or, with null, forget) the reasoning parameters found for a model. * * @param string $provider Provider key. * @param string $model Model ID. * @param array|null $entry Result of probe_reasoning_params(). * @return void */ public static function remember_reasoning_params(string $provider, string $model, ?array $entry): void { if ($provider === '' || $model === '') { return; } self::with_settings_lock(static function () use ($provider, $model, $entry) { $settings = self::settings(true); $current = $settings['reasoning_params'][$provider][$model] ?? null; if ($current === $entry) { return; } if (!isset($settings['reasoning_params']) || !is_array($settings['reasoning_params'])) { $settings['reasoning_params'] = []; } if (!isset($settings['reasoning_params'][$provider]) || !is_array($settings['reasoning_params'][$provider])) { $settings['reasoning_params'][$provider] = []; } if ($entry === null) { unset($settings['reasoning_params'][$provider][$model]); } else { $settings['reasoning_params'][$provider][$model] = $entry; } update_option('ai_translate_settings', $settings); self::settings(true); }); } /** * Adjust an API request body for model-specific requirements. * * Disables or minimizes reasoning/thinking for translation (cost + latency). * Provider formats differ: OpenAI uses reasoning_effort, DeepSeek uses * thinking.type, OpenRouter/DeepInfra use reasoning.effort. * * @param array $body Request body with 'model' and 'messages'. * @param string $model Model ID. * @param string $provider Provider key (openai, openrouter, deepinfra, …). * @return array Adjusted body. */ public static function adjust_body_for_model(array $body, string $model, string $provider): array { $isOSeries = (bool) preg_match('/(?:^|\/)o\d/i', $model); $isGpt5 = self::is_gpt5_or_newer($model); // deepseek-flash (no "v4" in the name) also thinks by default; measured: 3.7–6.3s and // ~3x the output tokens versus 1.9s with thinking disabled. $isDeepSeekV = (bool) preg_match('/deepseek[-_]?(?:v\d|reasoner|flash)/i', $model); $isGemini = stripos($model, 'gemini') !== false; // Claude 5 Haiku on OpenRouter thinks by default (measured: 14k instead of 6k output tokens for // the same page, 48 s against the 45 s request limit); reasoning effort none switches it off. $isClaudeOpenRouter = $provider === 'openrouter' && (bool) preg_match('/(?:^|\/)claude/i', $model); $isReasoning = $isOSeries || $isGpt5 || $isDeepSeekV || $isGemini || $isClaudeOpenRouter; // Temperature 0 is only omitted when activation in admin proved this model // rejects that value. GPT-5 / O-series stay omitted until that check exists. $omitTemperature = ($isOSeries || $isGpt5); $temperatureCap = self::settings()['temperature_supported'][$provider][$model] ?? null; if ($temperatureCap === false) { $omitTemperature = true; } elseif ($temperatureCap === true) { $omitTemperature = false; } if ($omitTemperature) { unset($body['temperature']); } // Anthropic's OpenAI-compatible endpoint: Claude 5 models think by default and the thinking // is not returned. A page translation then needs 20-45 s (the request limit is 45 s) and // fails silently. Thinking can be switched off with the native field; reasoning_effort is ignored. if ($provider === 'custom' && self::is_anthropic_url((string) (self::settings()['custom_api_url'] ?? ''))) { if (!isset($body['thinking'])) { $body['thinking'] = ['type' => 'disabled']; } return $body; } // Parameters the activation probe measured to work for this exact model win over the // name-based guesses below. $learned = self::settings()['reasoning_params'][$provider][$model] ?? null; if (is_array($learned) && !empty($learned['params']) && is_array($learned['params'])) { foreach ($learned['params'] as $key => $value) { if (!isset($body[$key])) { $body[$key] = $value; } } return $body; } if ( !$isReasoning || isset($body['reasoning_effort']) || isset($body['reasoning']) || isset($body['thinking']) ) { return $body; } $effort = self::resolve_min_reasoning_effort($model); // DeepSeek native API: thinking is ON by default on V4; must disable explicitly. if ($provider === 'deepseek') { if ($effort === 'none') { $body['thinking'] = ['type' => 'disabled']; } else { $body['thinking'] = ['type' => 'enabled']; // DeepSeek only accepts low|high|max when thinking is enabled. $body['reasoning_effort'] = in_array($effort, ['low', 'high', 'max'], true) ? $effort : 'low'; } return $body; } if ($provider === 'openai') { $body['reasoning_effort'] = $effort; return $body; } // OpenRouter, DeepInfra, Groq, custom OpenAI-compatible gateways. $body['reasoning'] = ['effort' => $effort]; // DeepSeek-V behind a gateway often still honors the native thinking toggle. if ($isDeepSeekV && $effort === 'none') { $body['thinking'] = ['type' => 'disabled']; } return $body; } /** * Extract assistant text from either a chat/completions or /responses response. * * @param array|null $data Decoded JSON response body. * @return string|null The assistant text, or null when not found. */ public static function extract_message_content($data) { if (!is_array($data)) { return null; } // Standard chat/completions format if (isset($data['choices'][0]['message']['content'])) { return \AITranslate\strip_thinking_blocks((string) $data['choices'][0]['message']['content']); } // Responses API format if (isset($data['output']) && is_array($data['output'])) { foreach ($data['output'] as $output) { if ( isset($output['type']) && $output['type'] === 'message' && isset($output['content']) && is_array($output['content']) ) { foreach ($output['content'] as $item) { if (isset($item['type']) && $item['type'] === 'output_text' && isset($item['text'])) { return \AITranslate\strip_thinking_blocks((string) $item['text']); } } } } } if (isset($data['output_text'])) { return \AITranslate\strip_thinking_blocks((string) $data['output_text']); } return null; } // ── End Responses API helpers ──────────────────────────────────────── /** * What the activation probe measured for a model: 'limited' when a parameter switches (most of) * its thinking off, 'always' when thinking was measured and nothing helped, null when unknown. * * @param string $provider Provider key. * @param string $model Model ID. * @return string|null */ public static function measured_thinking_state(string $provider, string $model): ?string { $entry = self::settings()['reasoning_params'][$provider][$model] ?? null; if (!is_array($entry)) { return null; } // The provider refused to run without thinking: it always thinks. if (!empty($entry['mandatory'])) { return 'always'; } $baseline = (int) ($entry['baseline_tokens'] ?? 0); if (!empty($entry['params'])) { // Thinking is only "off" when (nearly) nothing is left of it. A model that still spends // over 100 tokens, and over a tenth of what it used before, only thinks less at its lowest // setting (o3 at effort "low" is an example): it cannot be switched off. $left = (int) ($entry['tokens'] ?? 0); return ($left > 100 && $left * 10 > $baseline) ? 'always' : 'limited'; } // Under 20 reasoning tokens is no thinking (the probe uses the same limit): a few tokens of "reasoning" // are reported by models such as Claude Fable 5, which do not think when they translate. return $baseline >= 20 ? 'always' : null; } /** * Read from the provider's model list whether a model thinks, and whether that can be limited. * * DeepInfra tags models "reasoning" and, when an effort parameter works, "reasoning_effort". * OpenRouter lists "reasoning" / "reasoning_effort" / "include_reasoning" in supported_parameters. * Other providers give no such data. * * @param string $provider Provider key. * @param array|null $modelData Row of the model from the /models response. * @return array{thinks:bool,can_limit:bool}|null Null when the list does not say. */ public static function model_thinking_hint(string $provider, $modelData): ?array { if (!is_array($modelData)) { return null; } if ($provider === 'deepinfra' && isset($modelData['metadata']['tags']) && is_array($modelData['metadata']['tags'])) { $tags = $modelData['metadata']['tags']; return [ 'thinks' => in_array('reasoning', $tags, true) || in_array('reasoning_effort', $tags, true), 'can_limit' => in_array('reasoning_effort', $tags, true), ]; } if ($provider === 'openrouter' && isset($modelData['supported_parameters']) && is_array($modelData['supported_parameters'])) { $params = $modelData['supported_parameters']; $effort = in_array('reasoning_effort', $params, true); return [ 'thinks' => $effort || in_array('reasoning', $params, true) || in_array('include_reasoning', $params, true), 'can_limit' => $effort, ]; } return null; } /** * Start a streaming chat request and stop as soon as the provider has accepted it. * * Returns an array shaped like a wp_remote_* response, so wp_remote_retrieve_* work on it. * HTTP 200 means key, model and balance were accepted. Error statuses keep their body. * * @param string $endpoint Full chat/completions or /responses URL. * @param array $headers Request headers. * @param array $body Request body (stream is switched on here). * @param int $timeout Seconds to wait for the provider to answer at all. * @return array|\WP_Error */ private static function stream_start_probe(string $endpoint, array $headers, array $body, int $timeout = 30) { $body['stream'] = true; $lines = []; foreach ($headers as $name => $value) { $lines[] = $name . ': ' . $value; } $code = 0; $buffer = ''; $ch = curl_init($endpoint); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => wp_json_encode($body), CURLOPT_HTTPHEADER => $lines, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => $timeout, CURLOPT_HEADERFUNCTION => static function ($handle, $line) use (&$code) { if (preg_match('#^HTTP/\S+\s+(\d{3})#', $line, $m)) { $code = (int) $m[1]; } return strlen($line); }, CURLOPT_WRITEFUNCTION => static function ($handle, $data) use (&$code, &$buffer) { if ($code === 200) { return 0; // accepted: stop reading, the answer itself is not needed } $buffer .= $data; return strlen($data); }, ]); curl_exec($ch); $errno = curl_errno($ch); $error = curl_error($ch); if ($code === 0) { return new \WP_Error('http_request_failed', $error !== '' ? $error : 'cURL error ' . $errno); } return ['response' => ['code' => $code], 'body' => $buffer]; } /** * Whether a chat test result is worth another try: a timeout, or a busy/overloaded provider. * * @param array|\WP_Error $resp Result of the request. * @return bool */ private static function is_transient_failure($resp): bool { if (is_wp_error($resp)) { return stripos($resp->get_error_message(), 'timed out') !== false; } return self::is_transient_busy_response($resp); } /** * Whether a response is a temporary capacity problem (busy model, overloaded provider) * rather than a bad key or an empty balance. * * @param array $resp Response from wp_remote_*. * @return bool */ private static function is_transient_busy_response($resp): bool { $code = (int) wp_remote_retrieve_response_code($resp); if (in_array($code, [502, 503, 504], true)) { return true; } if ($code !== 429) { return false; } $h = strtolower((string) wp_remote_retrieve_body($resp)); foreach (['credit', 'quota', 'billing', 'insufficient'] as $needle) { if (strpos($h, $needle) !== false) { return false; } } return true; } /** * Turn a failed chat test into a message that tells the user what to do. * * @param int $code HTTP status of the chat test. * @param string $detail Error message returned by the provider. * @param string $provider_key Provider key. * @return string */ private static function friendly_chat_test_error(int $code, string $detail, string $provider_key): string { $raw = sprintf('Chat test failed (HTTP %d): %s', $code, $detail); $haystack = strtolower($detail); if ($code === 401 || $code === 403) { return $raw . ' — ' . __('The provider rejected the API key. Check that the key is complete (no missing or extra characters), that it belongs to the selected provider, and that it has not been deleted or revoked.', 'ai-translate'); } if ($code === 402 || ($code === 429 && (strpos($haystack, 'credit') !== false || strpos($haystack, 'quota') !== false || strpos($haystack, 'billing') !== false || strpos($haystack, 'insufficient') !== false))) { return $raw . ' — ' . __('The API key is valid, but the account has no credit left. Add credit or a payment method at your provider (API credit is separate from a chat subscription such as ChatGPT Plus) and try again.', 'ai-translate'); } if ($code === 429) { return $raw . ' — ' . __('The provider is rate limiting requests. Wait a moment and try again.', 'ai-translate'); } return $raw; } /** * Validate API settings by performing a light request to the provider. * - For OpenAI-compatible APIs: GET /models with Bearer key. * - Optionally tests chat/completions endpoint with the selected model. * - Throws \Exception on failure. * * @param string $provider_key * @param string $api_key * @param string $custom_api_url * @param string $model Optional model to test with chat/completions * @return array{ok:bool,temperature_supported?:bool} * @throws \Exception */ public function validate_api_settings($provider_key, $api_key, $custom_api_url = '', $model = '') { $provider_key = (string) $provider_key; $api_key = (string) $api_key; $custom_api_url = (string) $custom_api_url; $model = (string) $model; if ($provider_key === '') { throw new \Exception('Provider missing'); } if ($api_key === '') { throw new \Exception('API key missing'); } $base = self::get_api_url_for_provider($provider_key); if ($provider_key === 'custom') { $base = $custom_api_url; } if ($base === '') { throw new \Exception('API URL missing'); } // Custom API: reject Google API URL (not OpenAI-compatible) if ($provider_key === 'custom' && strpos($custom_api_url, 'googleapis.com') !== false) { throw new \Exception(esc_html__('Google API is not OpenAI compatible. Use Openrouter or Deepinfra for Gemini.', 'ai-translate')); } $endpoint = rtrim($base, '/') . '/models'; $headers = self::build_api_headers($api_key, $provider_key, ['custom_api_url' => $custom_api_url]); $resp = wp_remote_get($endpoint, [ 'headers' => $headers, 'timeout' => 15, 'sslverify' => true, ]); if (is_wp_error($resp)) { throw new \Exception(esc_html($resp->get_error_message())); } $code = (int) wp_remote_retrieve_response_code($resp); if ($code !== 200) { $body = (string) wp_remote_retrieve_body($resp); throw new \Exception(esc_html('HTTP ' . $code . ' ' . $body)); } $body = (string) wp_remote_retrieve_body($resp); $data = json_decode($body, true); if (!is_array($data)) { throw new \Exception('Unknown response from API'); } // If model is provided, check if it exists in the models list first if ($model !== '') { $modelFound = false; $modelData = null; if (isset($data['data']) && is_array($data['data'])) { foreach ($data['data'] as $m) { if (is_array($m) && isset($m['id']) && $m['id'] === $model) { $modelFound = true; $modelData = $m; break; } } } if (!$modelFound) { throw new \Exception(esc_html('Model "' . $model . '" not found in available models list. Please check the model name.')); } } // If model is provided, test the API endpoint to ensure model is actually usable if ($model !== '') { // Early guard for model families that are known to be non-chat/non-translation models. if (preg_match('/(dall-e|whisper|audio|image|realtime|transcribe|tts|embedding|moderation|codex|seedream|bria|:batch$)/i', $model) || preg_match('/sentence-transformers\/|(?:^|\/|[-_])(?:bge|e5|gte|text2vec)(?:[-_\/]|$)|nemotron-embed/i', $model) ) { throw new \Exception( esc_html(sprintf( /* translators: %s is the selected model ID */ __('Selected model "%s" is not a chat/completions model and cannot be used for translations. Choose a text chat model (for example: gpt-4o-mini, gpt-4.1-mini, deepseek-chat).', 'ai-translate'), $model )) ); } $endpointPath = self::get_model_endpoint_path($model); $chatEndpoint = rtrim($base, '/') . $endpointPath; $chatHeaders = self::build_api_headers($api_key, $provider_key, ['custom_api_url' => $custom_api_url]); $chatBody = [ 'model' => $model, 'messages' => [ ['role' => 'user', 'content' => 'Test'], ], ]; $chatBody = self::adjust_body_for_model($chatBody, $model, $provider_key); if ($endpointPath === '/responses') { $chatBody = self::convert_body_to_responses($chatBody); } elseif ($provider_key !== 'openai') { // The test only has to prove the key and model work. Without a cap, gateways such as // DeepInfra default to the full context and a thinking model can exceed the timeout. // OpenAI is skipped: its newer models reject max_tokens. $chatBody['max_tokens'] = 64; } // A model the provider lists as thinking can need longer before the first byte. $thinkingHint = self::model_thinking_hint((string) $provider_key, $modelData ?? null); // A thinking model can sit in the provider's queue for a long time before it produces a // token, so a full answer is no proof of anything. Open a streaming request instead: the // provider answers 401/404/429 at once for a bad key, model or balance, and 200 once it // accepts the request. That is all the validation needs. $useStream = $thinkingHint !== null && $thinkingHint['thinks'] && function_exists('curl_init'); $chatTimeout = 20; $chatResp = $useStream ? self::stream_start_probe($chatEndpoint, $chatHeaders, $chatBody, 30) : self::remote_api_post($chatEndpoint, $chatHeaders, $chatBody, $chatTimeout); // Providers such as DeepInfra answer 429 "Model busy" or 503 while a model is briefly // at capacity, and a busy provider can time out. Retry twice with a short pause before reporting a failure. for ($attempt = 1; $attempt <= 2 && self::is_transient_failure($chatResp); $attempt++) { sleep($attempt * 2); $chatResp = $useStream ? self::stream_start_probe($chatEndpoint, $chatHeaders, $chatBody, 30) : self::remote_api_post($chatEndpoint, $chatHeaders, $chatBody, $chatTimeout); } // Models such as some Gemini versions refuse "thinking off": retry with the lowest effort. if (!is_wp_error($chatResp) && (int) wp_remote_retrieve_response_code($chatResp) === 400 && \AITranslate\is_mandatory_reasoning_error((string) wp_remote_retrieve_body($chatResp)) ) { $adapted = \AITranslate\mandatory_reasoning_retry($chatBody); if ($adapted !== null) { $retryResp = $useStream ? self::stream_start_probe($chatEndpoint, $chatHeaders, $adapted[0], 30) : self::remote_api_post($chatEndpoint, $chatHeaders, $adapted[0], $chatTimeout, false); if (!is_wp_error($retryResp) && (int) wp_remote_retrieve_response_code($retryResp) === 200) { $chatBody = $adapted[0]; $chatResp = $retryResp; self::remember_reasoning_params((string) $provider_key, (string) $model, [ 'params' => $adapted[1], 'v' => self::REASONING_PROBE_VERSION, 'mandatory' => true, ]); } } } if (is_wp_error($chatResp)) { throw new \Exception(esc_html('Chat test failed: ' . $chatResp->get_error_message())); } $chatCode = (int) wp_remote_retrieve_response_code($chatResp); if ($chatCode !== 200) { $chatBodyText = (string) wp_remote_retrieve_body($chatResp); $chatErrorMessage = ''; $chatErrorData = json_decode($chatBodyText, true); if ( is_array($chatErrorData) && isset($chatErrorData['error']) && is_array($chatErrorData['error']) && isset($chatErrorData['error']['message']) ) { $chatErrorMessage = (string) $chatErrorData['error']['message']; } $haystack = strtolower($chatErrorMessage . ' ' . $chatBodyText); $nonChatModelError = ( strpos($haystack, 'not allowed to sample from this model') !== false || strpos($haystack, 'not a chat model') !== false || strpos($haystack, 'v1/completions') !== false || strpos($haystack, 'completions endpoint') !== false || strpos($haystack, 'does not support') !== false || strpos($haystack, 'image generation') !== false || strpos($haystack, 'embedding') !== false || strpos($haystack, 'moderation') !== false || strpos($haystack, 'audio') !== false || strpos($haystack, 'codex') !== false || strpos($haystack, 'model_not_found') !== false || strpos($haystack, 'does not exist') !== false ); if ($nonChatModelError) { throw new \Exception( esc_html(sprintf( /* translators: %s is the selected model ID */ __('Selected model "%s" is not supported for chat-based translations. Choose a chat/completions model instead.', 'ai-translate'), $model )) ); } // Auto-detect /responses API requirement and retry once if ($chatCode === 404 && self::is_responses_api_error($chatBodyText)) { self::mark_model_responses_api($model); $chatEndpoint = rtrim($base, '/') . '/responses'; $chatBody = self::adjust_body_for_model([ 'model' => $model, 'messages' => [['role' => 'user', 'content' => 'Test']], ], $model, $provider_key); $chatBody = self::convert_body_to_responses($chatBody); $chatResp = self::remote_api_post($chatEndpoint, $chatHeaders, $chatBody, 20); if (is_wp_error($chatResp)) { throw new \Exception(esc_html('Chat test failed: ' . $chatResp->get_error_message())); } $chatCode = (int) wp_remote_retrieve_response_code($chatResp); if ($chatCode !== 200) { $chatBodyText = (string) wp_remote_retrieve_body($chatResp); $chatErrorMessage = ''; $chatErrorData = json_decode($chatBodyText, true); if ( is_array($chatErrorData) && isset($chatErrorData['error']['message']) && is_string($chatErrorData['error']['message']) ) { $chatErrorMessage = $chatErrorData['error']['message']; } $detail = $chatErrorMessage !== '' ? $chatErrorMessage : substr($chatBodyText, 0, 500); throw new \Exception(esc_html(self::friendly_chat_test_error((int) $chatCode, (string) $detail, (string) $provider_key))); } } else { $detail = $chatErrorMessage !== '' ? $chatErrorMessage : substr($chatBodyText, 0, 500); throw new \Exception(esc_html(self::friendly_chat_test_error((int) $chatCode, (string) $detail, (string) $provider_key))); } } // Probe the temperature value used for translations. A rejection does not // fail activation: the model stays usable and later requests omit temperature. $temperatureSupported = null; // Known from an earlier activation: do not ask again (this runs every time the settings page opens). $knownTemperature = self::settings()['temperature_supported'][$provider_key][$model] ?? null; $tempBody = self::adjust_body_for_model([ 'model' => $model, 'messages' => [ ['role' => 'user', 'content' => 'Test'], ], 'temperature' => 0, ], $model, $provider_key); // Force the probe value even when adjust_body would omit temperature. $tempBody['temperature'] = 0; if (substr($chatEndpoint, -10) === '/responses') { $tempBody = self::convert_body_to_responses($tempBody); } elseif ($provider_key !== 'openai') { $tempBody['max_tokens'] = 64; } $tempResp = (is_bool($knownTemperature) || !empty($useStream)) ? null : self::remote_api_post($chatEndpoint, $chatHeaders, $tempBody, 20); if (is_bool($knownTemperature)) { $temperatureSupported = $knownTemperature; } elseif ($tempResp !== null && !is_wp_error($tempResp)) { $tempCode = (int) wp_remote_retrieve_response_code($tempResp); if ($tempCode === 200) { $temperatureSupported = true; } elseif (self::is_unsupported_temperature_error((string) wp_remote_retrieve_body($tempResp))) { $temperatureSupported = false; } if (is_bool($temperatureSupported)) { self::remember_temperature_supported($provider_key, $model, $temperatureSupported); } } // Measure whether this model thinks while it translates and, if so, which parameter // stops that. Best effort: a failed probe never fails activation. // Only the first time for a model: this runs every time the settings page opens. $reasoningEntry = null; // The model list already says this model does not think: nothing to measure. A thinking model is // still measured, because the list does not show every parameter that can switch thinking off. $skipProbe = $thinkingHint !== null && !$thinkingHint['thinks']; // Measuring a thinking model (the probe tries parameter sets until one works) can take minutes. Run it // as a one-off WP-Cron event, so the settings page does not wait. This works on any PHP setup. if (!$skipProbe) { if ( self::reasoning_probe_needed($provider_key, $model) && !self::reasoning_probe_failed_recently($provider_key, $model) && self::request_reasoning_probe((string) $provider_key, (string) $model) ) { // Mark it as tried first, so a second validation does not start another probe. self::note_reasoning_probe_failure($provider_key, $model); } $skipProbe = true; } if (!$skipProbe && self::reasoning_probe_needed($provider_key, $model) && !self::reasoning_probe_failed_recently($provider_key, $model)) { try { $reasoningEntry = self::probe_reasoning_params($chatEndpoint, $chatHeaders, $model); } catch (\Throwable $e) { $reasoningEntry = null; } if ($reasoningEntry !== null) { self::remember_reasoning_params($provider_key, $model, $reasoningEntry); } else { // Nothing was measured: try again in an hour, not on every validation self::note_reasoning_probe_failure($provider_key, $model); } } } $result = ['ok' => true]; if (isset($temperatureSupported) && is_bool($temperatureSupported)) { $result['temperature_supported'] = $temperatureSupported; } if (!empty($reasoningEntry) && is_array($reasoningEntry)) { $result['reasoning'] = $reasoningEntry; } return $result; } /** * Return available languages (code => label). * * @return array */ public function get_available_languages() { // Extensive but curated list aligned with assets/flags return [ 'en' => 'English', 'nl' => 'Dutch', 'de' => 'German', 'fr' => 'French', 'es' => 'Spanish', 'it' => 'Italian', 'pt' => 'Portuguese', 'pl' => 'Polish', 'cs' => 'Czech', 'da' => 'Danish', 'fi' => 'Finnish', 'sv' => 'Swedish', 'no' => 'Norwegian', 'ro' => 'Romanian', 'ru' => 'Russian', 'uk' => 'Ukrainian', 'tr' => 'Turkish', 'el' => 'Greek', 'hu' => 'Hungarian', 'bg' => 'Bulgarian', 'ar' => 'Arabic', 'he' => 'Hebrew', 'hi' => 'Hindi', 'th' => 'Thai', 'zh' => 'Chinese', 'ja' => 'Japanese', 'ko' => 'Korean', 'ka' => 'Georgian', 'kk' => 'Kazakh', 'et' => 'Estonian', 'ga' => 'Irish', 'hr' => 'Croatian', 'lv' => 'Latvian', 'lt' => 'Lithuanian', 'mt' => 'Maltese', 'sl' => 'Slovenian', 'sk' => 'Slovak', 'id' => 'Indonesian', ]; } /** * Clear translation cache for a language. * Returns stats with success, count and optional warning. * * @param string $lang * @return array{success:bool,count:int,warning?:string} */ public function clear_cache_for_language($lang) { $lang = sanitize_key((string) $lang); // Clear disk cache for this language $uploads = wp_upload_dir(); $base = trailingslashit($uploads['basedir']) . 'ai-translate/cache/'; // Add site-specific directory if multi-domain caching is enabled $site_dir = self::get_site_cache_dir(); if (!empty($site_dir)) { $base = trailingslashit($base) . $site_dir . '/'; } $base = trailingslashit($base) . $lang . '/pages/'; $count = 0; if (is_dir($base)) { $rii = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($rii as $file) { /** @var \SplFileInfo $file */ if ($file->isFile()) { wp_delete_file($file->getPathname()); $count++; } } // Remove empty directories. Plugin-owned cache subdirectories under uploads/ai-translate/cache/; // WP_Filesystem would require admin-side credential init and is overkill for local cleanup. foreach ($rii as $file) { if ($file->isDir()) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- plugin-owned cache directory cleanup @rmdir($file->getPathname()); } } } \AITranslate\AI_Cache_Meta::delete_by_path_prefix($base); // Clear segment + attribute translation transients for this language global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query($wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", '_transient_ai_tr_seg_' . $lang . '_%', '_transient_timeout_ai_tr_seg_' . $lang . '_%' )); // Segments live in the segment store (the transients above only exist on installs without // an external object cache, or from before the store existed). AI_Segment_Store::delete_lang((string) $lang); // Attribute keys use dual-write (object cache + DB); delete via helper so both layers clear. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $attr_option_names = $wpdb->get_col($wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", '_transient_ai_tr_attr_' . $lang . '_%' )); if (is_array($attr_option_names)) { foreach ($attr_option_names as $option_name) { $option_name = (string) $option_name; if (strpos($option_name, '_transient_') !== 0) { continue; } $key = substr($option_name, strlen('_transient_')); if (function_exists('ai_translate_delete_attr_transient')) { ai_translate_delete_attr_transient($key); } else { delete_transient($key); } } } return ['success' => true, 'count' => $count]; } /** * Clear AI Translate transient caches (segment + attribute) except slugs. * Only deletes transients owned by this plugin, not those of other plugins. */ public function clear_memory_and_transients_except_slugs() { global $wpdb; // Only clear AI Translate transients (ai_tr_seg_* and ai_tr_attr_*) // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query($wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s", '_transient_ai_tr_seg_%', '_transient_timeout_ai_tr_seg_%', '_transient_ai_tr_attr_%', '_transient_timeout_ai_tr_attr_%' )); AI_Segment_Store::delete_all(); // Flush object cache for AI Translate entries wp_cache_flush(); } /** * Clear all caches (disk + transients); optionally preserve slugs. * * @param bool $preserve_slugs * @return void */ public function clear_all_cache($preserve_slugs = false) { $uploads = wp_upload_dir(); $root = trailingslashit($uploads['basedir']) . 'ai-translate/cache/'; // Add site-specific directory if multi-domain caching is enabled $site_dir = self::get_site_cache_dir(); if (!empty($site_dir)) { $root = trailingslashit($root) . $site_dir . '/'; } if (is_dir($root)) { $rii = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($rii as $file) { /** @var \SplFileInfo $file */ if ($file->isDir()) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- plugin-owned cache directory cleanup @rmdir($file->getPathname()); } else { wp_delete_file($file->getPathname()); } } } \AITranslate\AI_Cache_Meta::delete_by_path_prefix($root); $this->clear_memory_and_transients_except_slugs(); } /** * Clear only disk-based language caches (HTML artifacts) for this site and preserve menu and slug caches. * Does not touch transients or object cache. * Clears only the site-specific cache dir (e.g. cache/netcare.nl) using this WordPress site's home host, * so the correct dir is cleared regardless of whether admin is opened via www or non-www. * * @return void */ public function clear_language_disk_caches_only() { $uploads = wp_upload_dir(); $root = trailingslashit($uploads['basedir']) . 'ai-translate/cache/'; $site_dir = self::get_site_cache_dir_for_clearing(); if (!empty($site_dir)) { $root = trailingslashit($root) . $site_dir . '/'; } if (!is_dir($root)) { \AITranslate\AI_Cache_Meta::delete_by_path_prefix($root); return; } $rii = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($rii as $file) { /** @var \SplFileInfo $file */ if ($file->isDir()) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- plugin-owned cache directory cleanup @rmdir($file->getPathname()); } else { wp_delete_file($file->getPathname()); } } \AITranslate\AI_Cache_Meta::delete_by_path_prefix($root); } /** * Site cache subdir name for clearing: based on home_url() host (not HTTP_HOST). * Ensures we clear the correct dir even when admin is opened via www subdomain. * * @return string */ public static function get_site_cache_dir_for_clearing(): string { $settings = self::settings(); if (empty($settings['multi_domain_caching'])) { return ''; } $host = wp_parse_url(home_url(), PHP_URL_HOST); if (empty($host)) { return 'default'; } $sanitized = sanitize_file_name($host); return $sanitized !== '' ? $sanitized : 'default'; } /** * Clear prompt cache (currently same as memory/transients for simplicity). */ public function clear_prompt_cache() { $this->clear_memory_and_transients_except_slugs(); } /** * Clear menu caches and optional plugin menu tables if present. * - Clears WordPress nav menu transients and object cache entries. * - Clears all menu-item translation transients (ai_tr_attr_*). * - If legacy plugin tables for menu translations exist, truncates them. * - Never touches slug map table. * * @return array{wp_caches_cleared:bool,tables_cleared:array,transients_cleared:int} */ public function clear_menu_cache() { // Clear common WordPress menu caches delete_transient('nav_menu'); delete_transient('nav_menu_items'); delete_transient('nav_menu_cache'); // Clear object cache entries for registered menus and locations if (function_exists('get_nav_menu_locations')) { $menu_locations = get_nav_menu_locations(); if (is_array($menu_locations)) { foreach ($menu_locations as $location => $menu_id) { wp_cache_delete($menu_id, 'nav_menu'); wp_cache_delete($location, 'nav_menu_locations'); } } } if (function_exists('wp_get_nav_menus')) { $menus = wp_get_nav_menus(); if (is_array($menus)) { foreach ($menus as $menu) { if (is_object($menu) && isset($menu->term_id)) { wp_cache_delete($menu->term_id, 'nav_menu'); } } } } // Best-effort flush of a cache group if available (not standard in core) if (function_exists('wp_cache_flush_group')) { @wp_cache_flush_group('nav_menu'); } // Clear ALL translation transients (ai_tr_attr_* for menu items and ai_tr_seg_* for segments) // This ensures renamed menu items and updated content get fresh translations $transients_cleared = 0; global $wpdb; // Delete all transients starting with ai_tr_attr_ or ai_tr_seg_ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query($wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s", '_transient_ai_tr_attr_%', '_transient_timeout_ai_tr_attr_%', '_transient_ai_tr_seg_%', '_transient_timeout_ai_tr_seg_%' )); if ($result !== false) { $transients_cleared = (int) $result; } // Renamed menu items need fresh translations; the rest of the page text does not. AI_Segment_Store::delete_type('menu'); // Optionally truncate legacy/alternate plugin tables if they exist $tablesCleared = []; $candidates = [ $wpdb->prefix . 'ai_translate_menus', $wpdb->prefix . 'ai_translate_menu_items', ]; foreach ($candidates as $tbl) { $exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tbl)); if ($exists === $tbl) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->query($wpdb->prepare("TRUNCATE TABLE %i", $tbl)); $tablesCleared[] = $tbl; } } return [ 'wp_caches_cleared' => true, 'tables_cleared' => $tablesCleared, 'transients_cleared' => $transients_cleared, ]; } /** * Clear slug map table used for translated slugs. * Does not modify rewrite rules or other caches. * * @return array{success:bool,cleared:int,message?:string} */ public function clear_slug_map() { global $wpdb; $table = $wpdb->prefix . 'ai_translate_slugs'; // Verify table exists $exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)); if ($exists !== $table) { return ['success' => false, 'cleared' => 0, 'message' => 'Slug table not found']; } // Count rows for reporting // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %i", $table)); // Truncate the table // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->query($wpdb->prepare("TRUNCATE TABLE %i", $table)); return ['success' => true, 'cleared' => $count]; } /** * Convert language code to full language name with code. * * @param string $code Language code (e.g. 'ka', 'en', 'nl'). * @return string Full language name with code, e.g. "Georgian (ka)" or 'unknown' if not found. */ private static function get_language_name($code) { if ($code === '' || $code === null) { return 'unknown'; } $code = strtolower((string) $code); $core = self::get_instance(); $languages = $core->get_available_languages(); if (isset($languages[$code])) { return $languages[$code] . ' (' . strtoupper($code) . ')'; } return 'unknown'; } /** * Build a single, centralized system prompt for all translation requests. * * This ensures consistent instruction to the LLM across batch and any future single-call translations. * * @param string|null $source_language The expected source language code (nullable/empty if unknown). * @param string $target_language The desired target language code. * @param array $context Optional context array; supports 'website_context' and 'is_title'. * @return string */ public static function build_translation_system_prompt($source_language, $target_language, array $context = []) { $sourceLangName = $source_language ? self::get_language_name((string) $source_language) : 'unknown'; $targetLangName = self::get_language_name((string) $target_language); $websiteContext = isset($context['website_context']) && $context['website_context'] !== '' ? "\n\nWebsite context: " . (string) $context['website_context'] : ''; $titleHint = isset($context['is_title']) && $context['is_title'] ? "\n- If the text is a title or menu label, keep it concise and natural." : ''; $prompt = sprintf( 'You are a professional translation engine. Translate text from %s to %s. MANDATORY REQUIREMENTS: - The input text is in %s. You MUST translate every segment to %s. NEVER return source text unchanged. - Do NOT analyze or detect the language. Translate from %s to %s as instructed. - Even if input appears to already be in %s, still translate it to ensure proper %s output. - Every word must be translated. The output MUST be entirely in %s.%s%s TRANSLATION QUALITY STANDARDS: - Preserve the original meaning, intent, nuance, and tone of the %s source text. Do NOT add or remove information. - Produce grammatically correct, idiomatic, and natural text that reads as if originally written in %s by a native speaker. - Avoid literal, word-for-word translations. Render concepts in culturally natural and linguistically appropriate expressions. - Do NOT preserve metaphors or idiomatic expressions literally if they sound unnatural in %s. Use culturally appropriate equivalents instead. - Maintain consistent terminology for recurring concepts throughout the site. - Translate technical terms using standard professional equivalents in %s, not literal translations. - Use appropriate tone for a personal website: friendly, informative, clear, and professional but not overly formal. - For languages with gendered pronouns or formal/informal address (e.g., German \'Sie\' vs \'du\', French \'vous\' vs \'tu\', Chinese polite conventions), use the form most appropriate for a public professional site. SEGMENT-SPECIFIC GUIDELINES: - Menu items (segment.type = "menu"): Translate accurately and concisely (1-3 words). Preserve exact meaning. Translate the actual words provided, not generic substitutes. Make clear, concise, and natural in %s. - Navigational text, headings, buttons, calls to action, form labels: Ensure clarity, conciseness, and natural flow in %s. - URL slugs (segment.type = "meta"): Keep SHORT and URL-friendly - maximum 2-3 words (ideally one compound word) for Latin-based languages, 2-4 characters for UTF-8 languages. Use hyphens (-) to separate words if needed. Never use full sentences or long phrases. CRITICAL SCRIPT RULES: Arabic (AR) → Arabic script أ-ي, Bulgarian (BG) → Cyrillic script а-я, Greek (EL) → Greek script α-ω, Hebrew (HE) → Hebrew script א-ת, Hindi (HI) → Devanagari script अ-ह, Japanese (JA) → Kanji/Kana, Korean (KO) → Hangul 가-힣, Russian (RU) → Cyrillic а-я, Thai (TH) → Thai script ก-ฮ, Ukrainian (UK) → Cyrillic а-я. NEVER use Latin characters for these languages. Example: "ai-consultancy" → "ai-beratung" (DE), "ai-conseil" (FR), "ai咨询" (ZH), "استشارات-ذكاء" (AR), "ייעוץ-בינה" (HE), "ai-консалтинг" (BG/RU/UK), "ai-συμβουλευτική" (EL).%s OUTPUT FORMAT: - Return ONLY valid JSON: {"translations": {"": ""}} - Every segment ID must have translated text in %s. - No explanations, comments, or text outside the JSON. - The translated_text MUST be in %s, not in %s.', $sourceLangName, $targetLangName, $sourceLangName, $targetLangName, $sourceLangName, $targetLangName, $targetLangName, $targetLangName, $targetLangName, $websiteContext, $titleHint, $sourceLangName, $targetLangName, $targetLangName, $targetLangName, $targetLangName, $targetLangName, $titleHint, $targetLangName, $targetLangName, $sourceLangName ); $prompt .= self::build_glossary_prompt_hint((string) $target_language); return $prompt; } /** * Build the glossary section of the translation system prompt for a target language. * Parses the 'glossary' setting (one term per line: "Bike = de: Fahrrad, nl: Fiets") * and enforces the configured translation of each source term for that language. * * @param string $target_language Target language code. * @return string Prompt fragment (empty when no rules apply to the target language). */ private static function build_glossary_prompt_hint($target_language) { $rules = []; foreach (self::glossary_rules((string) $target_language) as [$source, $term]) { $rules[] = sprintf("Translate '%s' exactly as '%s'", $source, $term); } if (empty($rules)) { return ''; } return "\n\nTERMINOLOGY (mandatory, override your own choice for these terms):\n- " . implode("\n- ", $rules); } /** * Glossary rules that apply to a target language, parsed from the 'glossary' setting. * * @param string $target_language Target language code. * @return array List of [source term, required translation]. */ private static function glossary_rules(string $target_language): array { static $parsed = []; $settings = self::settings(); $raw = isset($settings['glossary']) ? trim((string) $settings['glossary']) : ''; if ($raw === '') { return []; } $target = strtolower(trim($target_language)); $cacheKey = md5($raw) . '|' . $target; if (isset($parsed[$cacheKey])) { return $parsed[$cacheKey]; } $rules = []; foreach (preg_split('/\r\n|\r|\n/', $raw) as $line) { $line = trim($line); if ($line === '' || strpos($line, '=') === false) { continue; } [$source, $targets] = array_map('trim', explode('=', $line, 2)); if ($source === '') { continue; } foreach (explode(',', $targets) as $pair) { if (strpos($pair, ':') === false) { continue; } [$lang, $term] = array_map('trim', explode(':', $pair, 2)); if (strtolower($lang) === $target && $term !== '') { $rules[] = [$source, $term]; break; } } } $parsed[$cacheKey] = $rules; return $rules; } /** * Short signature of the glossary rules that apply to a text in a target language. * Empty when no rule matches, so segments without glossary terms keep their old cache key. * It becomes part of the stored segment's hash: changing a rule invalidates only the * segments that contain its source term. * * @param string $text Source text. * @param string $target_language Target language code. * @return string 8 hex characters, or '' when no glossary rule applies. */ public static function glossary_signature(string $text, string $target_language): string { $rules = self::glossary_rules($target_language); if ($rules === []) { return ''; } $matched = []; foreach ($rules as [$source, $term]) { if (mb_stripos($text, $source) !== false) { $matched[] = $source . '=' . $term; } } return $matched === [] ? '' : substr(md5(implode("\n", $matched)), 0, 8); } /** * Get site-specific cache directory name based on the active domain (HTTP_HOST). * * @return string Sanitized domain name or empty string when multi-domain is disabled. */ public static function get_site_cache_dir(): string { $settings = self::settings(); if (empty($settings['multi_domain_caching'])) { return ''; } $active_domain = self::get_active_domain(); $sanitized = sanitize_file_name($active_domain); return $sanitized !== '' ? $sanitized : 'default'; } /** * Compute cache statistics for admin display. * * @return array{ * total_files:int,total_size:int,expired_files:int,last_modified:int, * languages:array,languages_details:array * } */ public function get_cache_statistics() { $uploads = wp_upload_dir(); $root = trailingslashit($uploads['basedir']) . 'ai-translate/cache/'; // Add site-specific directory if multi-domain caching is enabled $site_dir = self::get_site_cache_dir(); $stats = [ 'total_files' => 0, 'total_size' => 0, 'expired_files' => 0, 'last_modified' => 0, 'languages' => [], 'languages_details' => [], ]; // Respect admin setting (cache_expiration in hours) // Admin validation ensures minimum 14 days, so we respect the setting directly $expiry_hours = self::cache_expiration_hours(); $expiry_seconds = $expiry_hours * HOUR_IN_SECONDS; $now = time(); $roots = []; if (!empty($site_dir)) { $roots[] = trailingslashit($root) . $site_dir . '/'; } else { $roots[] = $root; // Backward compatibility: when shared cache mode is active but files are still in // /cache/{domain}/{lang}/pages/, include those domain roots in the overview. $entries = @scandir($root); $has_flat_layout = false; if (is_array($entries)) { foreach ($entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } if (strlen($entry) === 2 && ctype_alpha($entry) && is_dir($root . $entry . '/pages/')) { $has_flat_layout = true; break; } } if (!$has_flat_layout) { foreach ($entries as $entry) { if ($entry === '.' || $entry === '..') { continue; } $domain_root = $root . $entry . '/'; if (!is_dir($domain_root)) { continue; } $domain_entries = @scandir($domain_root); if (!is_array($domain_entries)) { continue; } $has_lang_dirs = false; foreach ($domain_entries as $lang_entry) { if ($lang_entry === '.' || $lang_entry === '..') { continue; } if (strlen($lang_entry) === 2 && ctype_alpha($lang_entry) && is_dir($domain_root . $lang_entry . '/pages/')) { $has_lang_dirs = true; break; } } if ($has_lang_dirs) { $roots[] = $domain_root; } } } } } $seen_files = []; foreach ($roots as $cache_root) { if (!is_dir($cache_root)) { continue; } $langs = scandir($cache_root); if (!is_array($langs)) { continue; } foreach ($langs as $lang) { if ($lang === '.' || $lang === '..') continue; $langDir = $cache_root . $lang . '/pages/'; if (!is_dir($langDir)) continue; if (!isset($stats['languages'][$lang])) { $stats['languages'][$lang] = 0; $stats['languages_details'][$lang] = [ 'size' => 0, 'expired_count' => 0, 'last_modified' => 0, ]; } $rii = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($langDir, \FilesystemIterator::SKIP_DOTS) ); foreach ($rii as $file) { /** @var \SplFileInfo $file */ if (!$file->isFile()) { continue; } $path = wp_normalize_path($file->getPathname()); if (isset($seen_files[$path])) { continue; } $seen_files[$path] = true; $stats['languages'][$lang]++; $filesize = (int) $file->getSize(); $stats['languages_details'][$lang]['size'] += $filesize; $mtime = (int) $file->getMTime(); if ($mtime > $stats['languages_details'][$lang]['last_modified']) { $stats['languages_details'][$lang]['last_modified'] = $mtime; } if (($now - $mtime) > $expiry_seconds) { $stats['languages_details'][$lang]['expired_count']++; $stats['expired_files']++; } $stats['total_files']++; $stats['total_size'] += $filesize; if ($mtime > $stats['last_modified']) { $stats['last_modified'] = $mtime; } } } } return $stats; } /** * Generate a website context suggestion based on homepage content. * This is a lightweight heuristic (no external calls) to avoid failures without API. * Get clean homepage content, optionally for a specific domain. * * @param string $domain Optional. Domain to fetch content from. If provided, fetches via HTTP. * @return string */ private function get_clean_homepage_content($domain = '') { // Use WordPress-rendered content for highest fidelity $content = ''; $home_id = (int) get_option('page_on_front'); $site_name = (string) get_bloginfo('name'); if ($site_name === '') { $site_name = self::get_active_domain(); } $tagline = (string) get_bloginfo('description'); if ($home_id > 0) { $post = get_post($home_id); if ($post) { // Render content through WordPress filters to match frontend output $raw_content = $site_name . "\n"; if ($tagline !== '') { $raw_content .= $tagline . "\n"; } $raw_content .= $post->post_title . "\n"; if (!empty($post->post_excerpt)) { $raw_content .= $post->post_excerpt . "\n"; } // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- intentional: run WordPress core 'the_content' filter chain $rendered = apply_filters('the_content', $post->post_content); if (is_string($rendered) && $rendered !== '') { $raw_content .= $rendered; } else { $raw_content .= $post->post_content; } // Strip HTML tags and normalize whitespace $content = wp_strip_all_tags($raw_content); $content = preg_replace('/\s+/', ' ', $content); } } else { $raw_content = $site_name . "\n"; if ($tagline !== '') { $raw_content .= $tagline . "\n"; } $recent_posts = get_posts([ 'posts_per_page' => 5, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'suppress_filters' => false, 'ignore_sticky_posts' => true, ]); foreach ($recent_posts as $post) { $title = trim($post->post_title); if ($title !== '') { $raw_content .= $title . "\n"; } // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- intentional: run WordPress core 'the_content' filter chain $rendered = apply_filters('the_content', $post->post_content); if (is_string($rendered) && $rendered !== '') { $raw_content .= $rendered . "\n"; } else { $raw_content .= $post->post_content . "\n"; } } if (!empty($raw_content)) { $content = wp_strip_all_tags($raw_content); $content = preg_replace('/\s+/', ' ', $content); } } if (empty($content)) { $content = $site_name . ($tagline !== '' ? ' - ' . $tagline : ''); } return $content; } /** * Generate a website context suggestion using the configured AI provider. * Falls back to local generation if API is not configured or fails. * * @param string $domain Optional. Domain to use for content fetching. If not provided, uses active domain. * @return string */ public function generate_website_context_suggestion($domain = '') { // 1. Get settings $settings = self::settings(); $provider = isset($settings['api_provider']) ? (string)$settings['api_provider'] : ''; $models = isset($settings['models']) && is_array($settings['models']) ? $settings['models'] : []; $model = $provider !== '' ? self::effective_model($provider, (string) ($models[$provider] ?? '')) : ''; $apiKeys = isset($settings['api_keys']) && is_array($settings['api_keys']) ? $settings['api_keys'] : []; $apiKey = $provider !== '' ? self::api_key_for($settings, $provider) : ''; // Custom provider settings $baseUrl = self::api_base_url($provider, $settings); // 2. Prepare content - use provided domain $content = $this->get_clean_homepage_content($domain); // Get site name - use domain-specific if multi-domain caching is enabled $multi_domain = isset($settings['multi_domain_caching']) ? (bool) $settings['multi_domain_caching'] : false; $site_name = ''; if ($multi_domain && !empty($domain)) { // For multi-domain, try to extract site name from content or use domain $lines = explode("\n", $content); if (!empty($lines[0]) && trim($lines[0]) !== '') { $site_name = trim($lines[0]); if (mb_strlen($site_name) > 100) { $site_name = mb_substr($site_name, 0, 100); } } else { $site_name = strtok($domain, ':'); } } else { $site_name = (string) get_bloginfo('name'); } // 3. Try AI generation if configured if ($provider !== '' && $model !== '' && $apiKey !== '' && $baseUrl !== '') { try { $endpointPath = self::get_model_endpoint_path($model); $endpoint = rtrim($baseUrl, '/') . $endpointPath; $prompt = "Analyze the following website content and generate a concise website context description of maximum 5 lines.\n" . "This description will be used to inform an AI translator about the nature, tone, and subject matter of the site.\n" . "Rules:\n" . "1. Plain text only. No Markdown, no HTML, no special formatting.\n" . "2. Maximum 5 lines / sentences.\n" . "3. Focus on what the company/site does, who it serves, and the key terminology.\n" . "4. Include the mission or slogan (tagline) if present.\n" . "5. Include key USPs if they are present on the homepage content.\n" . "6. Do NOT include navigation menus, footer links, or irrelevant UI text.\n\n" . "Website Content:\n" . $content; $body = [ 'model' => $model, 'messages' => [ ['role' => 'system', 'content' => 'You are a helpful assistant that summarizes website content.'], ['role' => 'user', 'content' => $prompt], ], ]; $body = self::adjust_body_for_model($body, $model, $provider); if ($provider === 'openrouter' || ($provider === 'custom' && strpos($baseUrl, 'openrouter.ai') !== false)) { $body['user'] = !empty($domain) ? $domain : wp_parse_url(home_url(), PHP_URL_HOST); } if ($endpointPath === '/responses') { $body = self::convert_body_to_responses($body); } $headers = self::build_api_headers($apiKey, $provider, ['custom_api_url' => $baseUrl]); $response = self::remote_api_post($endpoint, $headers, $body, 30); // Auto-detect /responses API and retry once on 404 if (!is_wp_error($response) && (int) wp_remote_retrieve_response_code($response) === 404) { $errBody = (string) wp_remote_retrieve_body($response); if (self::is_responses_api_error($errBody)) { self::mark_model_responses_api($model); $endpoint = rtrim($baseUrl, '/') . '/responses'; $retryBody = [ 'model' => $model, 'messages' => [ ['role' => 'system', 'content' => 'You are a helpful assistant that summarizes website content.'], ['role' => 'user', 'content' => $prompt], ], ]; $retryBody = self::adjust_body_for_model($retryBody, $model, $provider); $body = self::convert_body_to_responses($retryBody); $response = self::remote_api_post($endpoint, $headers, $body, 30); } } if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) { $data = json_decode(wp_remote_retrieve_body($response), true); $ai_context = self::extract_message_content($data); if ($ai_context !== null) { $ai_context = trim($ai_context); // Remove markdown code blocks if present $ai_context = str_replace(["```json", "```JSON", "```"], '', $ai_context); // Final cleanup $ai_context = wp_strip_all_tags($ai_context); return $ai_context; } } } catch (\Exception $e) { // Fall through to fallback } } // 4. Fallback (Local generation) $parts = []; if ($site_name !== '') $parts[] = $site_name; $desc = get_bloginfo('description'); if ($desc) $parts[] = $desc; // Use the content we already prepared but much shorter for fallback if (!empty($content)) { // Take a smaller chunk for the simple fallback $fallback_content = mb_substr($content, 0, 280); if ($fallback_content !== $site_name && $fallback_content !== $desc) { $parts[] = $fallback_content; } } return implode(' — ', $parts); } /** * Generate a homepage meta description using the configured AI provider. * * @param string $domain Optional. Domain to use for content fetching. If not provided, uses active domain. * @return string */ public function generate_homepage_meta_description($domain = '') { // 1. Get settings $settings = self::settings(); $provider = isset($settings['api_provider']) ? (string)$settings['api_provider'] : ''; $models = isset($settings['models']) && is_array($settings['models']) ? $settings['models'] : []; $model = $provider !== '' ? self::effective_model($provider, (string) ($models[$provider] ?? '')) : ''; $apiKeys = isset($settings['api_keys']) && is_array($settings['api_keys']) ? $settings['api_keys'] : []; $apiKey = $provider !== '' ? self::api_key_for($settings, $provider) : ''; // Target language (default language of the site) $default_lang = isset($settings['default_language']) ? (string)$settings['default_language'] : 'en'; $targetLangName = $this->get_language_name($default_lang); // Custom provider settings $baseUrl = self::api_base_url($provider, $settings); // 2. Prepare content - use provided domain or active domain $content = $this->get_clean_homepage_content($domain); // Get site name - use domain-specific if multi-domain caching is enabled $multi_domain = isset($settings['multi_domain_caching']) ? (bool) $settings['multi_domain_caching'] : false; $site_name = ''; if ($multi_domain && !empty($domain)) { // For multi-domain, try to extract site name from content or use domain // The content should already contain the title from the specific domain // Extract first line (title) if available $lines = explode("\n", $content); if (!empty($lines[0]) && trim($lines[0]) !== '') { $site_name = trim($lines[0]); // Limit to reasonable length for site name if (mb_strlen($site_name) > 100) { $site_name = mb_substr($site_name, 0, 100); } } else { // Fallback to domain name (remove port if present) $site_name = strtok($domain, ':'); } } else { $site_name = (string) get_bloginfo('name'); } // Get website context (per-domain if multi-domain caching is enabled) $website_context = self::get_website_context($domain); // 3. Try AI generation if configured if ($provider !== '' && $model !== '' && $apiKey !== '' && $baseUrl !== '') { try { $context_section = ''; if ($website_context !== '') { $context_section = "\n\nWebsite Context (use this to understand the business/industry):\n" . $website_context; } $prompt = "You are creating a tag content for a website homepage.\n\n" . "CRITICAL REQUIREMENTS:\n" . "1. Language: Write in " . $targetLangName . ".\n" . "2. Length: EXACTLY 150-160 characters (not 180). This is the optimal length for search engines.\n" . "3. Content: Extract and use the PRIMARY KEYWORDS from the website content. Be SPECIFIC about what the company/site does.\n" . "4. NO generic phrases like 'hoogwaardige diensten', 'innovatieve oplossingen', 'expertise en kwaliteit', 'aansluiten bij uw behoeften'.\n" . "5. Include the company name (" . $site_name . ") if it fits naturally.\n" . "6. Be SPECIFIC: mention actual services, products, or unique value propositions mentioned in the content.\n" . "7. Include a subtle call-to-action (e.g., 'Ontdek...', 'Bekijk...', 'Vraag...') but keep it natural.\n" . "8. Write as if a professional SEO expert wrote it: keyword-rich, specific, compelling, and unique.\n" . "9. Output ONLY the meta description text. No quotes, no HTML tags, no explanations.\n\n" . "Website Content:\n" . $content . $context_section; // Use cheaper model for meta descriptions when a reasoning model is selected. $metaModel = (stripos($model, 'gpt-5') !== false || preg_match('/^o\d/i', $model)) ? 'gpt-4.1-mini' : $model; $endpointPath = self::get_model_endpoint_path($metaModel); $endpoint = rtrim($baseUrl, '/') . $endpointPath; $body = [ 'model' => $metaModel, 'messages' => [ ['role' => 'system', 'content' => 'You are an expert SEO copywriter specializing in writing compelling, keyword-rich meta descriptions that drive click-through rates. You understand that generic descriptions hurt SEO performance.'], ['role' => 'user', 'content' => $prompt], ], ]; $body = self::adjust_body_for_model($body, $metaModel, $provider); if ($provider === 'openrouter' || ($provider === 'custom' && strpos($baseUrl, 'openrouter.ai') !== false)) { $body['user'] = !empty($domain) ? $domain : wp_parse_url(home_url(), PHP_URL_HOST); } if ($endpointPath === '/responses') { $body = self::convert_body_to_responses($body); } $headers = self::build_api_headers($apiKey, $provider, ['custom_api_url' => $baseUrl]); $response = self::remote_api_post($endpoint, $headers, $body, 60); // Auto-detect /responses API and retry once on 404 if (!is_wp_error($response) && (int) wp_remote_retrieve_response_code($response) === 404) { $errBody = (string) wp_remote_retrieve_body($response); if (self::is_responses_api_error($errBody)) { self::mark_model_responses_api($metaModel); $endpoint = rtrim($baseUrl, '/') . '/responses'; $retryBody = [ 'model' => $metaModel, 'messages' => [ ['role' => 'system', 'content' => 'You are an expert SEO copywriter specializing in writing compelling, keyword-rich meta descriptions that drive click-through rates. You understand that generic descriptions hurt SEO performance.'], ['role' => 'user', 'content' => $prompt], ], ]; $retryBody = self::adjust_body_for_model($retryBody, $metaModel, $provider); $body = self::convert_body_to_responses($retryBody); $response = self::remote_api_post($endpoint, $headers, $body, 60); } } if (is_wp_error($response)) { throw new \Exception(esc_html('API request failed: ' . $response->get_error_message())); } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = wp_remote_retrieve_body($response); throw new \Exception(esc_html('API returned error code ' . $response_code . ': ' . $response_body)); } $response_body = wp_remote_retrieve_body($response); $data = json_decode($response_body, true); $meta = self::extract_message_content($data); if ($meta === null) { throw new \Exception('Invalid API response: missing content'); } $meta = trim($meta); $meta = str_replace(["```json", "```JSON", "```"], '', $meta); $meta = wp_strip_all_tags($meta); $meta = trim($meta); if (empty($meta)) { throw new \Exception('API returned empty meta description'); } return $meta; } catch (\Exception $e) { // Re-throw exception so AJAX handler can show proper error message throw $e; } } // 4. Fallback only if AI is not configured if ($provider === '' || $model === '' || $apiKey === '' || $baseUrl === '') { return mb_substr($content, 0, 160); } // If AI is configured but failed, throw exception instead of using fallback throw new \Exception('AI generation failed but no error was caught'); } }