'English', 'fr' => 'French', 'es' => 'Spanish', 'de' => 'German', 'it' => 'Italian', 'pt' => 'Portuguese', 'pt-br' => 'Portuguese (Brazil)', 'nl' => 'Dutch', 'ru' => 'Russian', 'zh-cn' => 'Chinese (Simplified)', 'zh-tw' => 'Chinese (Traditional)', 'ja' => 'Japanese', 'ko' => 'Korean', 'ar' => 'Arabic', 'hi' => 'Hindi', 'bn' => 'Bengali', 'tr' => 'Turkish', 'ur' => 'Urdu', 'pl' => 'Polish', 'sv' => 'Swedish', 'no' => 'Norwegian', 'da' => 'Danish', 'fi' => 'Finnish', 'cs' => 'Czech', 'el' => 'Greek', 'he' => 'Hebrew', 'ro' => 'Romanian', 'hu' => 'Hungarian', 'th' => 'Thai', 'ta' => 'Tamil', 'mr' => 'Marathi', 'pa' => 'Punjabi', 'id' => 'Indonesian', 'vi' => 'Vietnamese' ); /** @var AIBUI_Translation_Handler|null */ private static $instance = null; /** * Caractères envoyés à l'IA pour traduire ce contenu (titre, meta * description, textes des blocs), comptés en caractères Unicode comme * l'API : sert à afficher le prix quand il dépend de la taille. */ public static function translation_chars($post_id) { $post = get_post($post_id); if (!$post || !self::$instance) { return 0; } $chars = mb_strlen($post->post_title) + mb_strlen((string) self::$instance->get_meta_description($post_id)); foreach (self::$instance->extract_texts_from_blocks(parse_blocks($post->post_content)) as $text) { $chars += mb_strlen((string) $text); } return $chars; } public static function get_supported_languages() { return self::SUPPORTED_LANGUAGES; } public function __construct() { self::$instance = $this; // Add row actions for posts and pages add_filter('post_row_actions', array($this, 'add_translate_action'), 10, 2); add_filter('page_row_actions', array($this, 'add_translate_action'), 10, 2); // Enqueue scripts and styles add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts')); add_action('admin_enqueue_scripts', array($this, 'enqueue_site_editor_scripts')); // AJAX handlers add_action('wp_ajax_aibui_translate_post', array($this, 'handle_translation')); add_action('wp_ajax_aibui_translate_part', array($this, 'handle_part_translation')); add_action('wp_ajax_aibui_translate_template_part', array($this, 'handle_part_translation')); add_action('wp_ajax_aibui_translation_status', array($this, 'ajax_post_status')); add_action('wp_ajax_aibui_parts_translation_status', array($this, 'ajax_parts_status')); add_action('wp_ajax_aibui_add_switcher_to_header', array($this, 'ajax_add_switcher_to_header')); // Panneau « Languages » dans l'éditeur de pages / articles add_action('enqueue_block_editor_assets', array($this, 'enqueue_editor_panel')); } // --- Langues --------------------------------------------------------------- /** Libellés des langues configurées (réglages Translations), dans l'ordre. */ public static function configured_languages() { $settings = AIBUI_Translation_Settings::get_settings(); $langs = array_values(array_unique(array_merge(array($settings['default_lang']), (array) $settings['available_langs']))); $out = array(); foreach ($langs as $code) { if (isset(self::SUPPORTED_LANGUAGES[$code])) { $out[$code] = self::SUPPORTED_LANGUAGES[$code]; } } return $out; } public static function default_language() { $settings = AIBUI_Translation_Settings::get_settings(); return $settings['default_lang']; } /** Langue d'un contenu : meta _ai_lang, sinon langue par défaut du site. */ public static function post_language($post_id) { $lang = get_post_meta($post_id, '_ai_lang', true); return $lang ? $lang : self::default_language(); } /** Traductions d'un contenu (toutes langues, brouillons compris), par langue. */ public static function group_translations($post_id) { $group = get_post_meta($post_id, '_ai_translation_group', true); $by_lang = array(); if (!$group) { return $by_lang; } $posts = get_posts(array( 'post_type' => get_post_type($post_id), 'post_status' => array('publish', 'draft', 'pending', 'future', 'private'), 'posts_per_page' => -1, 'meta_key' => '_ai_translation_group', 'meta_value' => $group, )); foreach ($posts as $post) { $lang = self::post_language($post->ID); if (!isset($by_lang[$lang])) { $by_lang[$lang] = $post; } } return $by_lang; } /** Empreinte du contenu source, pour détecter une traduction périmée. */ private static function source_hash($post) { return md5($post->post_title . "\n" . $post->post_content); } /** Ligne d'état d'une langue pour un contenu (liste, panneau éditeur). */ private static function language_rows($post_id) { $post = get_post($post_id); $by_lang = self::group_translations($post_id); $current_lang = self::post_language($post_id); $by_lang[$current_lang] = $post; $rows = array(); foreach (self::configured_languages() as $code => $label) { $row = array('lang' => $code, 'label' => $label, 'status' => 'not_translated'); if (isset($by_lang[$code])) { $other = $by_lang[$code]; $row['postId'] = (int) $other->ID; $row['editUrl'] = get_edit_post_link($other->ID, 'raw'); $row['published'] = $other->post_status === 'publish'; if ((int) $other->ID === (int) $post_id) { $row['status'] = 'current'; } else { $source_id = (int) get_post_meta($other->ID, '_ai_translation_source', true); $source = ($source_id && $source_id !== (int) $other->ID) ? get_post($source_id) : null; $stored = get_post_meta($other->ID, '_aibui_source_hash', true); if ($source && $stored && $stored !== self::source_hash($source)) { $row['status'] = 'outdated'; } elseif ($source || $stored) { $row['status'] = 'up_to_date'; } else { // Original du groupe (vu depuis une traduction) $row['status'] = 'original'; } } } $rows[] = $row; } return $rows; } /** * Add "Translate with AI" action to row actions */ public function add_translate_action($actions, $post) { // Only show for published posts/pages if ($post->post_status !== 'publish' && $post->post_status !== 'draft') { return $actions; } // Check user capabilities if (!current_user_can('edit_post', $post->ID)) { return $actions; } $nonce = wp_create_nonce('aibui_translate_' . $post->ID); $existing = array_keys(self::group_translations($post->ID)); $actions['translate_ai'] = sprintf( '✨ Translate with AI', esc_attr($post->ID), esc_attr($nonce), esc_attr(self::post_language($post->ID)), esc_attr(implode(',', $existing)), self::translation_chars($post->ID) ); return $actions; } /** * Enqueue scripts and styles for translation feature */ public function enqueue_scripts($hook) { if ($hook !== 'edit.php') { return; } $screen = get_current_screen(); if (!$screen || !in_array($screen->post_type, array('post', 'page'), true)) { return; } // Enqueue CSS wp_enqueue_style( 'aibui-translation-style', plugin_dir_url(dirname(__FILE__)) . 'assets/css/translation.css', array(), AIBUI_VERSION ); // Enqueue JS wp_enqueue_script( 'aibui-translation-script', plugin_dir_url(dirname(__FILE__)) . 'assets/js/translation.js', array('jquery', 'aibui-costs'), AIBUI_VERSION, true ); // Localize script wp_localize_script('aibui-translation-script', 'aibuiTranslation', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('aibui_nonce'), 'languages' => self::configured_languages(), 'settingsUrl' => admin_url('admin.php?page=aibui-translation-settings'), )); } public function enqueue_editor_panel() { $screen = function_exists('get_current_screen') ? get_current_screen() : null; if (!$screen || $screen->base !== 'post' || !in_array($screen->post_type, array('post', 'page'), true)) { return; } wp_enqueue_script( 'aibui-translation-panel', plugin_dir_url(dirname(__FILE__)) . 'assets/js/translation-panel.js', array('wp-plugins', 'wp-element', 'wp-components', 'wp-data', 'wp-editor', 'aibui-costs'), AIBUI_VERSION, true ); wp_localize_script('aibui-translation-panel', 'aibuiTranslationPanel', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('aibui_nonce'), 'settingsUrl' => admin_url('admin.php?page=aibui-translation-settings'), )); } /** Module commun de traduction des headers / footers. */ public static function enqueue_parts_translation() { wp_enqueue_script( 'aibui-parts-translation', plugin_dir_url(dirname(__FILE__)) . 'assets/js/parts-translation.js', array('aibui-costs'), AIBUI_VERSION, true ); wp_localize_script('aibui-parts-translation', 'aibuiPartsTranslationVars', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('aibui_nonce'), 'settingsUrl' => admin_url('admin.php?page=aibui-translation-settings'), )); } public function enqueue_site_editor_scripts($hook) { if (strpos((string) $hook, 'aibui-headers-footers') !== false) { self::enqueue_parts_translation(); return; } if ($hook !== 'site-editor.php') { return; } self::enqueue_parts_translation(); wp_enqueue_script( 'aibui-pattern-translation', plugin_dir_url(dirname(__FILE__)) . 'assets/js/pattern-translation.js', array('wp-data', 'wp-notices', 'wp-edit-site', 'aibui-parts-translation'), AIBUI_VERSION, true ); } /** * Extract text from Gutenberg blocks recursively * Returns a mapped array: key => text */ private function extract_texts_from_blocks($blocks, $prefix = 'block') { $text_map = array(); $index = 0; foreach ($blocks as $block) { if (empty($block['blockName'])) { // Skip empty blocks continue; } $block_key = $prefix . '_' . $index; $block_name = $block['blockName']; // Extract text based on block type switch ($block_name) { case 'core/paragraph': if (!empty($block['innerHTML'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_p')); } break; case 'core/heading': if (!empty($block['innerHTML'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_h')); } break; case 'core/list': if (!empty($block['innerHTML']) && empty($block['innerBlocks'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_list')); } break; case 'core/list-item': if (!empty($block['innerHTML'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_li')); } break; case 'core/button': if (!empty($block['innerHTML'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_btn')); } break; case 'core/image': // Extract alt text and caption if (!empty($block['attrs']['alt'])) { $text_map[$block_key . '_alt'] = $block['attrs']['alt']; } if (!empty($block['innerHTML'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_caption')); } break; case 'core/quote': if (!empty($block['innerHTML'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_quote')); } break; case 'core/table': if (!empty($block['innerHTML'])) { $text_map = array_merge($text_map, $this->extract_text_nodes($block['innerHTML'], $block_key . '_table')); } break; case 'core/navigation': // If navigation has a ref, we need to extract from the referenced wp_navigation post if (!empty($block['attrs']['ref'])) { $nav_post = get_post($block['attrs']['ref']); if ($nav_post && $nav_post->post_type === 'wp_navigation') { $nav_blocks = parse_blocks($nav_post->post_content); $nav_map = $this->extract_texts_from_blocks($nav_blocks, $block_key . '_nav'); $text_map = array_merge($text_map, $nav_map); } } // Also process innerBlocks if present (inline navigation) break; case 'core/navigation-link': case 'core/navigation-submenu': // Extract the label from attrs if (!empty($block['attrs']['label'])) { $text_map[$block_key . '_navlabel'] = $block['attrs']['label']; } break; } // Recursively process inner blocks if (!empty($block['innerBlocks']) && is_array($block['innerBlocks'])) { $inner_map = $this->extract_texts_from_blocks($block['innerBlocks'], $block_key); $text_map = array_merge($text_map, $inner_map); } $index++; } return $text_map; } /** * Extract plain text from HTML, removing tags */ private function extract_text_from_html($html) { // Remove script and style tags $html = preg_replace('#(.*?)#is', '', $html); $html = preg_replace('#(.*?)#is', '', $html); // Decode HTML entities $html = html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8'); // Remove HTML tags but preserve line breaks for lists $text = strip_tags($html); // Clean up whitespace $text = preg_replace('/\s+/', ' ', $text); $text = trim($text); return $text; } /** * Extract text nodes preserving HTML structure */ private function extract_text_nodes($html, $key_prefix) { $result = array(); if (trim((string)$html) === '') { return $result; } $dom = new DOMDocument('1.0', 'UTF-8'); libxml_use_internal_errors(true); $dom->loadHTML('
' . $html . '
'); libxml_clear_errors(); $container = $dom->getElementsByTagName('div')->item(0); if (!$container) { return $result; } $index = 0; $this->traverse_text_nodes($container, function ($node) use (&$result, $key_prefix, &$index) { $text = $node->nodeValue; if (trim($text) === '') { return; } $result[$key_prefix . '_text' . $index] = $text; $index++; }); return $result; } /** * Replace text nodes with translated values */ private function replace_text_nodes($html, $key_prefix, $translated_map) { if (trim((string)$html) === '') { return $html; } $dom = new DOMDocument('1.0', 'UTF-8'); libxml_use_internal_errors(true); $dom->loadHTML('
' . $html . '
'); libxml_clear_errors(); $container = $dom->getElementsByTagName('div')->item(0); if (!$container) { return $html; } $index = 0; $this->traverse_text_nodes($container, function ($node) use ($key_prefix, $translated_map, &$index) { $text = $node->nodeValue; if (trim($text) === '') { return; } $key = $key_prefix . '_text' . $index; if (isset($translated_map[$key])) { $node->nodeValue = $translated_map[$key]; } $index++; }); $innerHTML = ''; foreach ($container->childNodes as $child) { $innerHTML .= $container->ownerDocument->saveHTML($child); } return $innerHTML; } /** * Traverse DOM text nodes */ private function traverse_text_nodes($node, $callback) { if ($node->nodeType === XML_TEXT_NODE) { $callback($node); } if ($node->hasChildNodes()) { foreach ($node->childNodes as $child) { $this->traverse_text_nodes($child, $callback); } } } /** * Reconstruct blocks with translated content */ private function reconstruct_blocks($original_blocks, $translated_map, $prefix = 'block') { $reconstructed = array(); $index = 0; foreach ($original_blocks as $block) { if (empty($block['blockName'])) { // Preserve empty blocks (spacers, etc.) $reconstructed[] = $block; continue; } $block_key = $prefix . '_' . $index; $block_name = $block['blockName']; $new_block = $block; // Replace text based on block type switch ($block_name) { case 'core/paragraph': if (!empty($block['innerHTML'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_p', $translated_map); $new_block['innerHTML'] = $updated_html; $new_block['innerContent'] = array($updated_html); } break; case 'core/heading': if (!empty($block['innerHTML'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_h', $translated_map); $new_block['innerHTML'] = $updated_html; $new_block['innerContent'] = array($updated_html); } break; case 'core/list': if (!empty($block['innerHTML']) && empty($block['innerBlocks'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_list', $translated_map); $new_block['innerHTML'] = $updated_html; $new_block['innerContent'] = array($updated_html); } break; case 'core/list-item': if (!empty($block['innerHTML'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_li', $translated_map); $new_block['innerHTML'] = $updated_html; $new_block['innerContent'] = array($updated_html); } break; case 'core/button': if (!empty($block['innerHTML'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_btn', $translated_map); $new_block['innerHTML'] = $updated_html; $new_block['innerContent'] = array($updated_html); } break; case 'core/image': if (isset($translated_map[$block_key . '_alt'])) { $new_block['attrs']['alt'] = sanitize_text_field($translated_map[$block_key . '_alt']); } if (!empty($block['innerHTML'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_caption', $translated_map); $new_block['innerHTML'] = $updated_html; if (isset($new_block['innerContent'])) { $new_block['innerContent'] = array($updated_html); } } break; case 'core/quote': if (!empty($block['innerHTML'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_quote', $translated_map); $new_block['innerHTML'] = $updated_html; $new_block['innerContent'] = array($updated_html); } break; case 'core/table': if (!empty($block['innerHTML'])) { $updated_html = $this->replace_text_nodes($block['innerHTML'], $block_key . '_table', $translated_map); $new_block['innerHTML'] = $updated_html; $new_block['innerContent'] = array($updated_html); } break; case 'core/navigation': // If navigation has a ref, duplicate the wp_navigation post with translated content if (!empty($block['attrs']['ref'])) { $new_nav_id = $this->duplicate_and_translate_navigation($block['attrs']['ref'], $translated_map, $block_key . '_nav'); if ($new_nav_id) { $new_block['attrs']['ref'] = $new_nav_id; } } break; case 'core/navigation-link': case 'core/navigation-submenu': // Replace the label in attrs if (isset($translated_map[$block_key . '_navlabel'])) { $new_block['attrs']['label'] = $translated_map[$block_key . '_navlabel']; } break; } // Recursively process inner blocks if (!empty($block['innerBlocks']) && is_array($block['innerBlocks'])) { $new_block['innerBlocks'] = $this->reconstruct_blocks($block['innerBlocks'], $translated_map, $block_key); } $reconstructed[] = $new_block; $index++; } return $reconstructed; } /** * Duplicate a wp_navigation post and translate its content */ private function duplicate_and_translate_navigation($nav_id, $translated_map, $prefix) { $nav_post = get_post($nav_id); if (!$nav_post || $nav_post->post_type !== 'wp_navigation') { return null; } // Parse the navigation blocks $nav_blocks = parse_blocks($nav_post->post_content); // Reconstruct with translated labels $translated_nav_blocks = $this->reconstruct_blocks($nav_blocks, $translated_map, $prefix); // Serialize back to block content $translated_nav_content = serialize_blocks($translated_nav_blocks); // Get target language from the current translation context $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'translated'; // Create a new wp_navigation post $new_nav_data = array( 'post_title' => $nav_post->post_title . ' (' . strtoupper($target_lang) . ')', 'post_content' => $translated_nav_content, 'post_status' => 'publish', 'post_type' => 'wp_navigation', 'post_author' => get_current_user_id(), ); $new_nav_id = wp_insert_post($new_nav_data); if (is_wp_error($new_nav_id)) { return null; } // Copy language meta update_post_meta($new_nav_id, '_ai_lang', $target_lang); update_post_meta($new_nav_id, '_ai_translation_source', $nav_id); // Link to same translation group $translation_group = get_post_meta($nav_id, '_ai_translation_group', true); if (empty($translation_group)) { $translation_group = 'nav_' . time() . '_' . wp_generate_password(8, false); update_post_meta($nav_id, '_ai_translation_group', $translation_group); } update_post_meta($new_nav_id, '_ai_translation_group', $translation_group); return $new_nav_id; } /** * Get meta description with fallback logic */ private function get_meta_description($post_id) { // Check _ai_builder_seo_desc first (as specified by user) $meta_desc = get_post_meta($post_id, '_ai_builder_seo_desc', true); if (!empty($meta_desc)) { return $meta_desc; } // Check plugin's own meta key $meta_desc = get_post_meta($post_id, 'aibui_meta_description', true); if (!empty($meta_desc)) { return $meta_desc; } // Check Yoast SEO meta $meta_desc = get_post_meta($post_id, '_yoast_wpseo_metadesc', true); if (!empty($meta_desc)) { return $meta_desc; } // Fallback to excerpt $post = get_post($post_id); return $post ? $post->post_excerpt : ''; } /** * Appel à l'API de traduction (requête d'origine ou réessai gratuit). * Renvoie la réponse décodée (title + content_map) ; en cas d'échec, * répond directement en JSON au navigateur. */ private function call_translate_api(array $api_data) { $jwt_token = get_option('aibui_jwt_token', ''); if (empty($jwt_token)) { wp_send_json_error(array('message' => 'Authentication required. Please sign in.')); } // Réessai gratuit : POST /retry/{generationId}, même format de réponse // que /translate-post. Sinon (requête d'origine ou réessai payant) : // la traduction est renvoyée telle quelle. $retry_generation_id = isset($_POST['retry_generation_id']) ? absint($_POST['retry_generation_id']) : 0; if ($retry_generation_id > 0) { $api_url = aibui_api_url('/ai-transform-page/retry/' . $retry_generation_id); $request = array( 'timeout' => 180, 'headers' => aibui_api_headers(array( 'Authorization' => 'Bearer ' . $jwt_token, )), ); } else { $api_url = aibui_api_url('/ai-transform-page/translate-post'); $request = array( 'timeout' => 180, // AI translation can take long for large pages 'headers' => aibui_api_headers(array( 'Authorization' => 'Bearer ' . $jwt_token, 'Content-Type' => 'application/json', )), 'body' => wp_json_encode($api_data), ); } $response = wp_remote_post($api_url, $request); if (is_wp_error($response)) { // Requête jamais arrivée à l'API : rien n'a été débité. wp_send_json_error(array( 'message' => 'API request failed: ' . $response->get_error_message(), 'transport_error' => true, )); } $response_code = wp_remote_retrieve_response_code($response); $decoded = json_decode(wp_remote_retrieve_body($response), true); $retry_info = $this->extract_retry_info($decoded, $response_code); if ($retry_generation_id > 0 && in_array($response_code, array(403, 404, 409), true)) { wp_send_json_error(array_merge($retry_info, array( 'message' => $this->free_retry_refusal_message(is_array($decoded) ? ($decoded['error'] ?? '') : ''), 'retry_refused' => true, 'retry' => array('freeRetryAvailable' => false), ))); } if ($response_code === 402) { $error_message = 'You do not have enough credits to translate this.'; if (is_array($decoded) && !empty($decoded['message'])) { $error_message .= ' ' . $decoded['message']; } wp_send_json_error(array_merge($retry_info, array( 'message' => $error_message, 'code' => 'not_enough_credits', ))); } if (is_array($decoded) && ($decoded['error'] ?? '') === 'content-too-large') { $max = isset($decoded['maxChars']) ? (int) $decoded['maxChars'] : 0; wp_send_json_error(array_merge($retry_info, array( 'message' => $max ? sprintf('This content is too long to translate in one go (%s characters maximum). Split it into several pages.', number_format_i18n($max)) : 'This content is too long to translate in one go. Split it into several pages.', 'code' => 'content_too_large', ))); } if ($response_code !== 200) { $message = 'Translation failed. Status: ' . $response_code; if (is_array($decoded) && !empty($decoded['error']) && is_string($decoded['error'])) { $message .= ' (' . $decoded['error'] . ')'; } wp_send_json_error(array_merge($retry_info, array('message' => $message))); } if (!is_array($decoded) || !isset($decoded['title']) || !isset($decoded['content_map']) || !is_array($decoded['content_map'])) { // ai-output-unusable : tokens consommés, l'API renvoie « retry ». wp_send_json_error(array_merge($retry_info, array( 'message' => 'The AI could not produce a usable translation this time.', ))); } // Crédits réellement débités (réponse du back), pour le message final. $decoded['_charged'] = isset($decoded['creditsCharged']) && is_numeric($decoded['creditsCharged']) ? (int) $decoded['creditsCharged'] : null; $decoded['_retry_info'] = $retry_info; $decoded['_jwt'] = $jwt_token; return $decoded; } /** « 20 credits used. » à partir de creditsCharged (absent sur un ancien back). */ private static function charged_note($charged) { if ($charged === null) { return ''; } return $charged === 0 ? ' No credits used.' : ' ' . sprintf(_n('%d credit used.', '%d credits used.', $charged, 'ai-builder'), $charged); } /** Langue cible demandée, limitée aux langues configurées. */ private function requested_target_lang($source_lang) { $target_lang = isset($_POST['target_lang']) ? sanitize_text_field(wp_unslash($_POST['target_lang'])) : ''; $configured = self::configured_languages(); if (!isset(self::SUPPORTED_LANGUAGES[$target_lang])) { wp_send_json_error(array('message' => 'Invalid target language')); } if (!isset($configured[$target_lang])) { wp_send_json_error(array( 'message' => sprintf('%s is not one of your site languages. Add it in AI Builder → Translations first.', self::SUPPORTED_LANGUAGES[$target_lang]), 'code' => 'language_not_configured', )); } if ($target_lang === $source_lang) { wp_send_json_error(array('message' => 'This content is already in ' . self::SUPPORTED_LANGUAGES[$target_lang] . '.')); } return $target_lang; } /** * AJAX : traduit une page ou un article. Si une traduction existe déjà * dans cette langue, elle est mise à jour (même page, même adresse) au * lieu de créer un doublon. */ public function handle_translation() { if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aibui_nonce')) { wp_send_json_error(array('message' => 'Security check failed')); } $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; if (!$post_id) { wp_send_json_error(array('message' => 'Invalid post ID')); } if (!current_user_can('edit_post', $post_id)) { wp_send_json_error(array('message' => 'Insufficient permissions')); } $original_post = get_post($post_id); if (!$original_post || !in_array($original_post->post_type, array('post', 'page'), true)) { wp_send_json_error(array('message' => 'Post not found')); } $source_lang = self::post_language($post_id); $target_lang = $this->requested_target_lang($source_lang); $target_lang_name = strtolower(self::SUPPORTED_LANGUAGES[$target_lang]); // Traduction existante dans cette langue : mise à jour $existing = self::group_translations($post_id); $existing_post = isset($existing[$target_lang]) ? $existing[$target_lang] : null; if ($existing_post && !current_user_can('edit_post', $existing_post->ID)) { wp_send_json_error(array('message' => 'Insufficient permissions')); } $blocks = parse_blocks($original_post->post_content); $translated_data = $this->call_translate_api(array( 'title' => $original_post->post_title, 'meta_desc' => $this->get_meta_description($post_id), 'content_map' => $this->extract_texts_from_blocks($blocks), 'target_lang' => $target_lang_name, )); $retry_info = $translated_data['_retry_info']; // Le lien _ai_lang de la source doit exister avant la reconstruction // (les menus dupliqués s'y réfèrent). if (!get_post_meta($post_id, '_ai_lang', true)) { update_post_meta($post_id, '_ai_lang', $source_lang); } $translated_content = serialize_blocks($this->reconstruct_blocks($blocks, $translated_data['content_map'])); if ($existing_post) { $new_post_id = wp_update_post(array( 'ID' => $existing_post->ID, 'post_title' => $translated_data['title'], 'post_content' => $translated_content, ), true); } else { $new_post_id = wp_insert_post(array( 'post_title' => $translated_data['title'], 'post_content' => $translated_content, 'post_status' => 'draft', 'post_type' => $original_post->post_type, 'post_author' => get_current_user_id(), ), true); } if (is_wp_error($new_post_id)) { // Traduction réussie mais impossible à enregistrer : signalée à // l'API, qui ouvre le réessai gratuit. $detail = $new_post_id->get_error_message(); wp_send_json_error(array_merge( $retry_info, $this->report_failure($translated_data['_jwt'], $retry_info['generationId'] ?? null, 'AIB-TRANSLATE-01', $detail), array('message' => 'Failed to save the translated page: ' . $detail) )); } // Meta description sur toutes les clés connues if (!empty($translated_data['meta_desc'])) { update_post_meta($new_post_id, '_ai_builder_seo_desc', $translated_data['meta_desc']); update_post_meta($new_post_id, '_yoast_wpseo_metadesc', $translated_data['meta_desc']); update_post_meta($new_post_id, 'aibui_meta_description', $translated_data['meta_desc']); update_post_meta($new_post_id, '_ai_translation_meta_desc', $translated_data['meta_desc']); } // CSS / JS de page : la traduction garde le même rendu foreach (array( 'ai_builder_page_css_content', 'ai_builder_block_css_content', 'ai_builder_css_content', 'ai_builder_page_js_content', 'ai_builder_block_js_content', 'ai_builder_js_content', ) as $meta_key) { $value = get_post_meta($post_id, $meta_key, true); if (!empty($value)) { update_post_meta($new_post_id, $meta_key, $value); } } update_post_meta($new_post_id, '_ai_lang', $target_lang); update_post_meta($new_post_id, '_ai_translation_source', $post_id); update_post_meta($new_post_id, '_aibui_source_hash', self::source_hash($original_post)); if (!get_post_meta($post_id, '_ai_translation_source', true)) { update_post_meta($post_id, '_ai_translation_source', $post_id); } $translation_group = get_post_meta($post_id, '_ai_translation_group', true); if (empty($translation_group)) { $translation_group = 'trans_' . time() . '_' . wp_generate_password(8, false); update_post_meta($post_id, '_ai_translation_group', $translation_group); } update_post_meta($new_post_id, '_ai_translation_group', $translation_group); wp_cache_flush_group('aibui_translations'); if (get_post_meta($post_id, '_aibui_created_by_ai', true) === '1') { update_post_meta($new_post_id, '_aibui_created_by_ai', '1'); } // Traduction de la page d'accueil : page d'accueil de sa langue $front_page_id = (int) get_option('page_on_front'); if (($front_page_id && $front_page_id === (int) $post_id) || get_post_meta($post_id, '_ai_is_homepage', true) === '1') { update_post_meta($new_post_id, '_ai_is_homepage', '1'); } $thumbnail_id = get_post_thumbnail_id($post_id); if ($thumbnail_id) { set_post_thumbnail($new_post_id, $thumbnail_id); } $label = self::SUPPORTED_LANGUAGES[$target_lang]; wp_send_json_success(array( 'message' => ($existing_post ? sprintf('%s translation updated.', $label) : sprintf('%s translation created as a draft.', $label)) . self::charged_note($translated_data['_charged']), 'creditsCharged' => $translated_data['_charged'], 'updated' => (bool) $existing_post, 'post_id' => (int) $new_post_id, 'edit_url' => get_edit_post_link($new_post_id, 'raw'), 'rows' => self::language_rows($post_id), )); } /** * AJAX : traduit un header / footer (template part) par dictionnaire. * Seuls les textes pas encore traduits sont envoyés à l'IA ; aucune copie * du template part n'est créée. */ public function handle_part_translation() { if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aibui_nonce')) { wp_send_json_error(array('message' => 'Security check failed')); } if (!current_user_can('edit_theme_options')) { wp_send_json_error(array('message' => 'Insufficient permissions')); } $part_id = isset($_POST['template_part_id']) ? sanitize_text_field(wp_unslash($_POST['template_part_id'])) : ''; $template = $part_id && strpos($part_id, '//') !== false ? get_block_template($part_id, 'wp_template_part') : null; if (!$template) { wp_send_json_error(array('message' => 'This header or footer could not be found.')); } $target_lang = $this->requested_target_lang(self::default_language()); $label = self::SUPPORTED_LANGUAGES[$target_lang]; $missing = AIBUI_Translation_Strings::missing_strings($part_id, $target_lang); $name = $template->title ? $template->title : $template->slug; if (!$missing) { wp_send_json_success(array( 'message' => sprintf('%s is already translated into %s.', $name, $label), 'status' => AIBUI_Translation_Strings::part_status($part_id, $target_lang), )); } $content_map = array(); foreach ($missing as $i => $text) { $content_map['s' . $i] = $text; } $translated_data = $this->call_translate_api(array( 'title' => $name, 'meta_desc' => '', 'content_map' => $content_map, 'target_lang' => strtolower($label), )); $pairs = array(); foreach ($content_map as $key => $source) { if (isset($translated_data['content_map'][$key]) && is_string($translated_data['content_map'][$key])) { $pairs[$source] = $translated_data['content_map'][$key]; } } if (!$pairs) { $retry_info = $translated_data['_retry_info']; wp_send_json_error(array_merge( $retry_info, $this->report_failure($translated_data['_jwt'], $retry_info['generationId'] ?? null, 'AIB-TRANSLATE-02', 'Empty content_map for template part'), array('message' => 'The AI could not produce a usable translation this time.') )); } AIBUI_Translation_Strings::add_to_dict($target_lang, $pairs); wp_send_json_success(array( 'message' => sprintf('%s translated into %s. Design changes now apply to every language automatically.', $name, $label) . self::charged_note($translated_data['_charged']), 'creditsCharged' => $translated_data['_charged'], 'status' => AIBUI_Translation_Strings::part_status($part_id, $target_lang), )); } /** Headers et footers du thème actif (sans les anciennes copies traduites). */ public static function site_parts() { $parts = array(); // Ceux affichés par le thème en premier (AIBUI_Theme_Parts). foreach (array('header' => 'Header', 'footer' => 'Footer') as $area => $area_label) { foreach (AIBUI_Theme_Parts::area_parts($area) as $entry) { $template = $entry['template']; $parts[] = array( 'used' => $entry['used'] > 0, 'id' => $template->id, 'area' => $area, 'areaLabel' => $area_label, 'title' => $template->title ? $template->title : $template->slug, 'editUrl' => admin_url('site-editor.php?postType=wp_template_part&postId=' . rawurlencode($template->id) . '&canvas=edit'), ); } } return $parts; } /** AJAX : état de traduction de tous les headers / footers. */ public function ajax_parts_status() { check_ajax_referer('aibui_nonce', 'nonce'); if (!current_user_can('edit_theme_options')) { wp_send_json_error(array('message' => 'Insufficient permissions'), 403); } $only = isset($_POST['template_part_id']) ? sanitize_text_field(wp_unslash($_POST['template_part_id'])) : ''; $default = self::default_language(); $targets = array_diff_key(self::configured_languages(), array($default => true)); $rows = array(); $parts = self::site_parts(); $areas_used = array(); foreach ($parts as $part) { if ($part['used']) { $areas_used[$part['area']] = true; } } foreach ($parts as $part) { if ($only && $part['id'] !== $only) { continue; } // Variante du thème jamais affichée : rien à traduire. if (!$only && !$part['used'] && !empty($areas_used[$part['area']])) { continue; } $strings = AIBUI_Translation_Strings::collect_part_strings($part['id']); // Sans texte (ex. variantes du thème avec seulement logo et menu // automatique) : rien à traduire, on n'encombre pas la liste. if (!$strings && !$only) { continue; } $part['languages'] = array(); foreach ($targets as $code => $label) { $part['languages'][] = array_merge( array('lang' => $code, 'label' => $label), AIBUI_Translation_Strings::part_status($part['id'], $code, $strings) ); } $rows[] = $part; } wp_send_json_success(array('parts' => $rows, 'defaultLang' => $default, 'languages' => $targets)); } /** AJAX : état des langues d'une page / d'un article (panneau éditeur). */ public function ajax_post_status() { check_ajax_referer('aibui_nonce', 'nonce'); $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0; if (!$post_id || !current_user_can('edit_post', $post_id)) { wp_send_json_error(array('message' => 'Insufficient permissions'), 403); } $lang = self::post_language($post_id); wp_send_json_success(array( 'lang' => $lang, 'langLabel' => self::SUPPORTED_LANGUAGES[$lang] ?? strtoupper($lang), 'rows' => self::language_rows($post_id), 'configured' => count(self::configured_languages()) > 1, 'chars' => self::translation_chars($post_id), )); } /** * AJAX : ajoute le bloc Language Switcher au header (après le menu s'il y * en a un) et active le sélecteur. Un header encore fourni par le thème * est d'abord enregistré en base. */ public function ajax_add_switcher_to_header() { check_ajax_referer('aibui_nonce', 'nonce'); if (!current_user_can('edit_theme_options')) { wp_send_json_error(array('message' => 'Insufficient permissions'), 403); } $header = null; foreach (self::site_parts() as $part) { if ($part['area'] === 'header') { $header = get_block_template($part['id'], 'wp_template_part'); break; } } if (!$header) { wp_send_json_error(array('message' => 'No header found. Create one in AI Builder → Headers & Footers first.')); } AIBUI_Translation_Settings::update(array('enable_switcher' => true)); if (strpos($header->content, 'wp:ai-builder/language-switcher') !== false) { wp_send_json_success(array('message' => 'The language switcher is already in your header.')); } $switcher = array( 'blockName' => 'ai-builder/language-switcher', 'attrs' => array(), 'innerBlocks' => array(), 'innerHTML' => '', 'innerContent' => array(), ); $blocks = parse_blocks($header->content); if (!self::insert_after_navigation($blocks, $switcher)) { $blocks[] = $switcher; } $content = serialize_blocks($blocks); if (!empty($header->wp_id)) { $result = wp_update_post(array('ID' => $header->wp_id, 'post_content' => $content), true); } else { $result = wp_insert_post(array( 'post_title' => $header->title ? $header->title : 'Header', 'post_name' => $header->slug, 'post_content' => $content, 'post_status' => 'publish', 'post_type' => 'wp_template_part', ), true); if (!is_wp_error($result)) { wp_set_object_terms($result, $header->theme, 'wp_theme'); wp_set_object_terms($result, 'header', 'wp_template_part_area'); } } if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message())); } wp_send_json_success(array('message' => 'The language switcher has been added to your header.')); } /** Insère $new juste après le premier bloc Navigation trouvé. */ private static function insert_after_navigation(array &$blocks, array $new) { foreach ($blocks as $i => &$block) { if (!empty($block['innerBlocks'])) { foreach ($block['innerBlocks'] as $j => $inner) { if (($inner['blockName'] ?? '') === 'core/navigation') { array_splice($block['innerBlocks'], $j + 1, 0, array($new)); // Emplacement du nouveau bloc dans innerContent $seen = -1; foreach ($block['innerContent'] as $k => $chunk) { if ($chunk === null && ++$seen === $j) { array_splice($block['innerContent'], $k + 1, 0, array(null)); break; } } return true; } } if (self::insert_after_navigation($block['innerBlocks'], $new)) { return true; } } } unset($block); return false; } /** * Champs de facturation/réessai d'une réponse de l'API, renvoyés au JS * (boutons « Retry for free », « Credits not charged »…). */ private function extract_retry_info($decoded, $status) { $info = array('status' => (int) $status); if (!is_array($decoded)) { return $info; } if (isset($decoded['generationId'])) { $info['generationId'] = (int) $decoded['generationId']; } if (isset($decoded['creditsLeft'])) { $info['creditsLeft'] = $decoded['creditsLeft']; } if (!empty($decoded['refunded'])) { $info['refunded'] = true; } if (isset($decoded['retry']) && is_array($decoded['retry'])) { $info['retry'] = array( 'freeRetryAvailable' => !empty($decoded['retry']['freeRetryAvailable']), 'freeRetriesRemaining' => isset($decoded['retry']['freeRetriesRemaining']) ? (int) $decoded['retry']['freeRetriesRemaining'] : null, 'freeRetriesLimit' => isset($decoded['retry']['freeRetriesLimit']) ? (int) $decoded['retry']['freeRetriesLimit'] : null, ); } if (!empty($decoded['error']) && is_string($decoded['error'])) { $info['error'] = $decoded['error']; } return $info; } private function free_retry_refusal_message($error) { switch ($error) { case 'no-free-retry-left': return 'You have used all your free retries for this month.'; case 'retry-expired': return 'The free retry for this translation has expired (it is available for 7 days).'; case 'already-retried': return 'This translation has already been retried for free.'; default: return 'A free retry is not available for this translation.'; } } /** * POST /ai-transform-page/report-failure : renvoie les champs « retry » * à fusionner dans la réponse JSON, ou un réessai payant par défaut. */ private function report_failure($jwt_token, $generation_id, $code, $detail) { $fallback = array('retry' => array('freeRetryAvailable' => false)); if (empty($generation_id)) { return $fallback; } $response = wp_remote_post(aibui_api_url('/ai-transform-page/report-failure'), array( 'timeout' => 15, 'headers' => aibui_api_headers(array( 'Authorization' => 'Bearer ' . $jwt_token, 'Content-Type' => 'application/json', )), 'body' => wp_json_encode(array( 'generationId' => (int) $generation_id, 'code' => substr(preg_replace('/[^a-zA-Z0-9_-]/', '', (string) $code), 0, 40), 'detail' => mb_substr((string) $detail, 0, 1000), )), )); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { return $fallback; } $decoded = json_decode(wp_remote_retrieve_body($response), true); if (!is_array($decoded) || empty($decoded['retry']) || !is_array($decoded['retry'])) { return $fallback; } $info = $this->extract_retry_info($decoded, 200); unset($info['status']); return $info; } }