'ai_translate_new_post', 'type'=>'boolean', 'title'=>'Auto Translate New Translation Posts', 'default'=>'1'), array('id'=>'ai_translate_prompt', 'type'=>'text', 'title'=>'Custom Prompt', 'description'=>'Used for post content and excerpts. {FROM_CODE} and {TO_CODE} will be replaced by from and to languages.', 'default'=>self::$PROMPT), array('id'=>'ai_translate_title_prompt', 'type'=>'text', 'title'=>'Custom Title Prompt', 'description'=>'Used for post titles. A title needs its own prompt: a content prompt makes models expand a bare headline into a whole article.', 'default'=>self::$TITLE_PROMPT), array('id'=>'ai_translate_llm', 'type'=>'select', 'title'=>'LLM Service', 'default'=>'OpenAI', 'values'=>array( 'OpenAI', 'Claude', 'Gemini', 'OpenRouter' )), array('id'=>'ai_translate_openai', 'type'=>'title', 'title'=>'OpenAI', 'description'=>''), array('id'=>'ai_translate_openai_key', 'type'=>'string', 'title'=>'OpenAI API Key', 'description'=>''), array('id'=>'ai_translate_openai_org', 'type'=>'string', 'title'=>'OpenAI Organization', 'description'=>'(Optional)'), array('id'=>'ai_translate_openai_model', 'type'=>'string', 'title'=>'OpenAI Model', 'default'=>self::$OPENAI_MODEL, 'values'=>array( 'gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo' )), array('id'=>'ai_translate_claude', 'type'=>'title', 'title'=>'Claude', 'description'=>''), array('id'=>'ai_translate_claude_key', 'type'=>'string', 'title'=>'Claude API Key', 'description'=>''), array('id'=>'ai_translate_claude_model', 'type'=>'string', 'title'=>'Claude Model', 'default'=>self::$CLAUDE_MODEL, 'values'=>array( 'claude-3-5-sonnet-20240620', 'claude-3-opus-20240229', 'claude-3-sonnet-20240229', 'claude-3-haiku-20240307' )), array('id'=>'ai_translate_gemini', 'type'=>'title', 'title'=>'Gemini', 'description'=>''), array('id'=>'ai_translate_gemini_key', 'type'=>'string', 'title'=>'Gemini API Key', 'description'=>''), array('id'=>'ai_translate_gemini_model', 'type'=>'string', 'title'=>'Gemini Model', 'default'=>self::$GEMINI_MODEL, 'values'=>array( 'gemini-2.5-flash', 'gemini-2.0-flash', 'gemini-1.5-flash', 'gemini-1.5-pro' )), array('id'=>'ai_translate_openrouter', 'type'=>'title', 'title'=>'OpenRouter', 'description'=>''), array('id'=>'ai_translate_openrouter_key', 'type'=>'string', 'title'=>'OpenRouter API Key', 'description'=>''), array('id'=>'ai_translate_openrouter_model', 'type'=>'string', 'title'=>'OpenRouter Model', 'description'=>'Any model id from https://openrouter.ai/models. Ids ending in :free are rate limited and may let OpenRouter train on the content.', 'default'=>self::$OPENROUTER_MODEL, 'values'=>array( 'google/gemma-4-31b-it:free', 'google/gemma-4-26b-a4b-it:free', 'z-ai/glm-5.2:free', 'minimax/minimax-m3:free', 'openrouter/free', 'google/gemini-2.5-flash', 'anthropic/claude-sonnet-4.5', 'openai/gpt-4o' )), array('id'=>'ai_translate_meta', 'type'=>'title', 'title'=>'Meta', 'description'=>''), array('id'=>'ai_translate_meta_clear', 'type'=>'text', 'title'=>'Meta keys to clear', 'description'=>'', 'default'=>''), array('id'=>'ai_translate_meta_translate', 'type'=>'text', 'title'=>'Meta keys to translate', 'description'=>'', 'default'=>''), ), 'AI Translate', 'mlang', false, 'manage_options', null, null, '', '_'); } public static function default_title($title, $post) { $translated = self::translate_field($title, 'post_title'); return is_string($translated) ? self::clean($translated, 'title') : $title; } public static function default_content($content, $post) { return self::translate_field($content, 'post_content'); } public static function default_excerpt($excerpt, $post) { return self::translate_field($excerpt, 'post_excerpt'); } public static function pll_copy_post_metas($keys, $sync, $from, $to, $lang) { $keys = array_diff($keys, self::meta_clear()); return $keys; } public static function pll_translate_post_meta($value, $key, $lang) { if (in_array($key, self::meta_clear())) { $value = ''; } else if (in_array($key, self::meta_translate())) { $value = self::translate_field($value, $key, true); } return $value; } private static function meta_keys($option) { $clear = get_option($option); if ($clear) { return preg_split('/\s+/', $clear); } else { return array(); } } private static function meta_clear() { if (!self::$meta_clear) { self::$meta_clear = self::meta_keys('ai_translate_meta_clear'); } return self::$meta_clear; } private static function meta_translate(){ if (!self::$meta_translate) { self::$meta_translate = self::meta_keys('ai_translate_meta_translate'); } return self::$meta_translate; } /* Translation */ public static function translate_field($original, $field = '', $meta = false) { if (get_option('ai_translate_new_post', '0') != '1' || empty($_GET['new_lang']) || empty($_GET['from_post'])) { return $original; } $to = sanitize_key($_GET['new_lang']); $post_id = (int) $_GET['from_post']; if (!$to || !$post_id) { return $original; } if ($field) { if ($meta) { $original = get_post_meta($post_id, $field, true); } else { $post = get_post($post_id); if (!$post) { return $original; } $original = $post->$field; } } $translation = self::translate($original, $to, pll_get_post_language($post_id), $field === 'post_title' ? 'title' : 'content'); //Never hand the editor a failed translation, fall back to the source text return $translation === null ? $original : $translation; } public static function prompt($to, $from = 'en', $kind = 'content') { $default = $kind === 'title' ? self::$TITLE_PROMPT : self::$PROMPT; $prompt = get_option($kind === 'title' ? 'ai_translate_title_prompt' : 'ai_translate_prompt', $default); if (!is_string($prompt) || trim($prompt) === '') { $prompt = $default; } return str_replace('{TO_CODE}', $to, str_replace('{FROM_CODE}', $from, $prompt)); } public static function log($message) { self::$last_error = $message; error_log('[ai-translate-for-polylang] '.$message); } /* * Pull the translated text out of a provider response, or explain why we can't. * Returns array('ok'=>bool, 'text'=>string, 'error'=>string). */ public static function read_response($service, $result) { if (is_wp_error($result)) { return array('ok'=>false, 'text'=>'', 'error'=>$service.' request failed: '.$result->get_error_message()); } $code = isset($result['response']['code']) ? (int) $result['response']['code'] : 0; $body = json_decode(isset($result['body']) ? $result['body'] : '', true); if (!is_array($body)) { return array('ok'=>false, 'text'=>'', 'error'=>$service.' returned an unparsable body (HTTP '.$code.')'); } //Some providers, OpenRouter especially, return HTTP 200 with an error envelope if (isset($body['error'])) { $message = isset($body['error']['message']) ? $body['error']['message'] : wp_json_encode($body['error']); return array('ok'=>false, 'text'=>'', 'error'=>$service.' error (HTTP '.$code.'): '.$message); } if ($code != 200) { return array('ok'=>false, 'text'=>'', 'error'=>$service.' returned HTTP '.$code); } $text = null; $finish = ''; if ($service == 'Claude') { $finish = isset($body['stop_reason']) ? $body['stop_reason'] : ''; if (isset($body['content']) && is_array($body['content'])) { foreach ($body['content'] as $block) { //Skip thinking and tool blocks if (isset($block['type']) && $block['type'] === 'text' && isset($block['text'])) { $text = $block['text']; break; } } } if ($finish === 'max_tokens') { return array('ok'=>false, 'text'=>'', 'error'=>'Claude response truncated (max_tokens)'); } } elseif ($service == 'Gemini') { $finish = isset($body['candidates'][0]['finishReason']) ? $body['candidates'][0]['finishReason'] : ''; if (isset($body['candidates'][0]['content']['parts']) && is_array($body['candidates'][0]['content']['parts'])) { foreach ($body['candidates'][0]['content']['parts'] as $part) { //Skip thought parts if (!empty($part['thought'])) { continue; } if (isset($part['text'])) { $text = $part['text']; break; } } } if ($finish && $finish !== 'STOP') { return array('ok'=>false, 'text'=>'', 'error'=>'Gemini stopped early ('.$finish.')'); } } else { //OpenAI and OpenRouter share the chat completion shape $finish = isset($body['choices'][0]['finish_reason']) ? $body['choices'][0]['finish_reason'] : ''; if (isset($body['choices'][0]['message']['content'])) { $content = $body['choices'][0]['message']['content']; if (is_array($content)) { //Some models answer with content parts $parts = array(); foreach ($content as $part) { if (is_string($part)) { $parts[] = $part; } elseif (isset($part['text'])) { $parts[] = $part['text']; } } $content = implode('', $parts); } $text = $content; } if ($finish === 'length') { return array('ok'=>false, 'text'=>'', 'error'=>$service.' response truncated (max_tokens)'); } } if (!is_string($text) || trim($text) === '') { return array('ok'=>false, 'text'=>'', 'error'=>$service.' returned no text'.($finish ? ' (finish: '.$finish.')' : '')); } return array('ok'=>true, 'text'=>$text, 'error'=>''); } /* Strip the wrappers models like to put around an answer */ public static function clean($text, $kind = 'content') { $text = trim($text); if (strpos($text, '```') === 0) { //Fenced code block around the whole answer $text = preg_replace('/\A```[a-zA-Z]*[ \t]*\r?\n?/', '', $text); $text = trim(preg_replace('/\r?\n?```\s*\z/', '', $text)); } if ($kind === 'title') { $text = trim(wp_strip_all_tags($text)); $pairs = array(array('"', '"'), array("'", "'"), array("\xE2\x80\x9C", "\xE2\x80\x9D"), array("\xE2\x80\x98", "\xE2\x80\x99")); foreach ($pairs as $pair) { //Drop quotes wrapping the whole headline list($open, $close) = $pair; if (strlen($text) > strlen($open) + strlen($close) && strpos($text, $open) === 0 && substr($text, -strlen($close)) === $close && strpos(substr($text, strlen($open), -strlen($close)), $close) === false) { $text = trim(substr($text, strlen($open), -strlen($close))); break; } } //Remove trailing punctuation models tack on, but keep closing quotes, brackets and ellipses if (preg_match('/(\.\.\.|\x{2026})\s*\z/u', $text)) { $text = rtrim($text); } else { $stripped = preg_replace('/[\s.,:;\x{2013}\x{2014}-]+$/u', '', $text); if ($stripped !== null && $stripped !== '') { //preg_replace returns null on invalid utf-8 $text = $stripped; } } } return $text; } /* Reject anything that clearly isn't a translation of $original */ public static function is_valid($text, $original, $kind = 'content') { if (!is_string($text) || trim($text) === '') { self::log('Rejected empty '.$kind); return false; } //Chain of thought leaking into the answer instead of the translation $leak = '/\A\s*(