'العربية', 'BG' => 'Български', 'CS' => 'Čeština', 'DA' => 'Dansk', 'DE' => 'Deutsch', 'EL' => 'Ελληνικά', 'EN' => 'English', 'EN-GB' => 'English (UK)', 'EN-US' => 'English (US)', 'ES' => 'Español', 'ET' => 'Eesti', 'FI' => 'Suomi', 'FR' => 'Français', 'HU' => 'Magyar', 'ID' => 'Bahasa Indonesia', 'IT' => 'Italiano', 'JA' => '日本語', 'KO' => '한국어', 'LT' => 'Lietuvių', 'LV' => 'Latviešu', 'NB' => 'Norsk bokmål', 'NL' => 'Nederlands', 'PL' => 'Polski', 'PT-PT' => 'Português (Portugal)', 'PT-BR' => 'Português (Brasil)', 'RO' => 'Română', 'RU' => 'Русский', 'SK' => 'Slovenčina', 'SL' => 'Slovenščina', 'SV' => 'Svenska', 'TR' => 'Türkçe', 'UK' => 'Українська', 'ZH' => '中文', ]; public static function get_image_mime_types(): array { return self::$IMAGE_MIME_TYPES; } /*** Bootstrap ***/ public static function init(): void { // Assets add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_admin_assets']); // Admin menu add_action('admin_menu', [__CLASS__, 'register_admin_menus']); add_action('admin_head', [__CLASS__, 'rename_first_submenu_to_list']); // AJAX endpoints add_action('wp_ajax_aigude_save_language', [__CLASS__, 'ajax_save_language']); add_action('wp_ajax_aigude_list_ids', [__CLASS__, 'ajax_list_ids']); add_action('wp_ajax_aigude_generate', [__CLASS__, 'ajax_generate_single']); add_action('wp_ajax_aigude_apply', [__CLASS__, 'ajax_apply_alt']); add_action('wp_ajax_aigude_generate_bulk', [__CLASS__, 'ajax_generate_bulk']); add_action('wp_ajax_aigude_get_all_credits', [__CLASS__, 'ajax_get_all_credits']); // Per-user “skip existing” toggle + Media Modal filter add_action('wp_ajax_aigude_set_skip_mode', [__CLASS__, 'ajax_set_skip_mode']); add_filter('ajax_query_attachments_args', [__CLASS__, 'filter_media_modal_query']); // Enrich attachment payload add_filter('wp_prepare_attachment_for_js', [__CLASS__, 'add_original_filename'], 10, 3); // List page search: JOIN + WHERE + DISTINCT add_filter('posts_join', [__CLASS__, 'filter_posts_join'], 10, 2); add_filter('posts_search', [__CLASS__, 'filter_posts_search'], 10, 2); add_filter('posts_distinct', [__CLASS__, 'filter_posts_distinct'], 10, 2); } /*** Assets ***/ public static function enqueue_admin_assets(string $hook): void { wp_enqueue_style('dashicons'); wp_enqueue_script('jquery'); // Base CSS (version by filemtime if present) $base_css_path = plugin_dir_path(__FILE__) . 'assets/css/base.css'; wp_enqueue_style( 'ai-admin-style', plugin_dir_url(__FILE__) . 'assets/css/base.css', [], file_exists($base_css_path) ? filemtime($base_css_path) : null ); // Top-level list view if ($hook === 'toplevel_page_' . self::MENU_SLUG || $hook === self::MENU_SLUG . '_page_alttext-list') { $list_js_path = plugin_dir_path(__FILE__) . 'assets/js/list-actions.js'; wp_enqueue_script( 'ai-list-actions', plugin_dir_url(__FILE__) . 'assets/js/list-actions.js', ['jquery', 'wp-i18n'], file_exists($list_js_path) ? filemtime($list_js_path) : null, true ); wp_localize_script('ai-list-actions', 'aigudeToolsListData', [ 'perImageCredits' => self::PER_IMAGE_CREDITS, 'nonce' => wp_create_nonce(self::NONCE_ACTION), 'ajaxUrl' => admin_url('admin-ajax.php'), ]); // Load translations from GlotPress (wp.org), or when local use /languages wp_set_script_translations( 'ai-list-actions', 'aigude-tools', plugin_dir_path(__FILE__) . 'languages' ); return; } // Grid if ($hook === self::MENU_SLUG . '_page_aigude-tools-grid') { wp_enqueue_media(); $js_path = plugin_dir_path(__FILE__) . 'assets/js/grid-actions.js'; wp_enqueue_script( 'ai-grid-actions', plugin_dir_url(__FILE__) . 'assets/js/grid-actions.js', ['jquery', 'media-editor', 'media-views', 'wp-util', 'wp-i18n'], file_exists($js_path) ? filemtime($js_path) : null, true ); wp_localize_script('ai-grid-actions', 'aigudeToolsGridData', [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce(self::NONCE_ACTION), 'defaultSkip' => true, 'selectors' => [ 'prompt' => '#global-prompt', 'language' => '#ai_target_language', 'miniGrid' => '#media-selected-grid', 'generateBtn' => '#media-generate', 'selectBtn' => '#media-select', 'progressBar' => '#bulk-progress-bar', 'progressWrap' => '#bulk-progress', 'skipExisting' => '#skip-existing', ], 'perImageCredits' => self::PER_IMAGE_CREDITS, 'batchSize' => 1, 'selectAllMax' => 2000, 'urls' => [ 'library' => admin_url('upload.php'), 'edit' => admin_url('post.php'), ], 'openTarget' => 'library', ]); wp_set_script_translations( 'ai-grid-actions', 'aigude-tools', plugin_dir_path(__FILE__) . 'languages' ); return; } // Server if ($hook === self::MENU_SLUG . '_page_aigude-tools-settings') { $js_path = plugin_dir_path(__FILE__) . 'assets/js/server-actions.js'; wp_enqueue_script( 'ai-server-actions', plugin_dir_url(__FILE__) . 'assets/js/server-actions.js', ['jquery', 'wp-i18n'], file_exists($js_path) ? filemtime($js_path) : null, true ); wp_localize_script('ai-server-actions', 'aigudeServerData', [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce(self::NONCE_ACTION), ]); wp_set_script_translations( 'ai-server-actions', 'aigude-tools', plugin_dir_path(__FILE__) . 'languages' ); return; } } /*** Admin Menus ***/ public static function register_admin_menus(): void { add_menu_page( esc_html__('AiGude Tools', 'aigude-tools'), esc_html__('AiGude Tools', 'aigude-tools'), 'manage_options', self::MENU_SLUG, 'aigude_tools_render_list_page', 'dashicons-format-image', 99 ); add_submenu_page( self::MENU_SLUG, esc_html__('Grid view (Media Modal)', 'aigude-tools'), esc_html__('Grid view', 'aigude-tools'), 'manage_options', 'aigude-tools-grid', 'aigude_tools_render_grid_page' ); add_submenu_page( self::MENU_SLUG, esc_html__('Settings', 'aigude-tools'), esc_html__('Settings', 'aigude-tools'), 'manage_options', 'aigude-tools-settings', 'aigude_server_settings_page' // from includes/admin-settings.php ); add_submenu_page( self::MENU_SLUG, esc_html__('Prompts', 'aigude-tools'), esc_html__('Prompts', 'aigude-tools'), 'manage_options', 'aigude-tools-prompts', 'aigude_prompt_templates_page' // from includes/admin-prompts.php ); } public static function rename_first_submenu_to_list(): void { global $submenu; if (isset($submenu[self::MENU_SLUG][0])) { $submenu[self::MENU_SLUG][0][0] = esc_html__('List view', 'aigude-tools'); } } /*** AJAX: Language ***/ public static function ajax_save_language(): void { // Capability first if ( ! current_user_can( 'manage_options' ) ) { self::json_error( 'forbidden', 403 ); } // Verify nonce sent from JS (created with wp_create_nonce( self::NONCE_ACTION )) check_ajax_referer( self::NONCE_ACTION ); // Read POST safely $lang = isset( $_POST['lang'] ) ? sanitize_text_field( wp_unslash( $_POST['lang'] ) ) : ''; if ( $lang === '' ) { self::json_error( __( 'Invalid request', 'aigude-tools' ) ); } // Normalize and persist $norm = self::resolve_target_lang_code($lang); update_option( 'aigude_target_language', $norm ); // Track recents for target language per user self::push_recent_lang('target', $norm); self::json_ok( 'Language saved: ' . $norm ); } /*** AJAX: List IDs (for “select all across pages”) ***/ public static function ajax_list_ids(): void { if ( ! current_user_can( 'upload_files' ) ) { self::json_error( 'forbidden', 403 ); } check_ajax_referer( self::NONCE_ACTION ); $search = isset( $_POST['s'] ) ? sanitize_text_field( wp_unslash( $_POST['s'] ) ) : ''; $skipExisting = ! empty( $_POST['skipExisting'] ); $args = [ 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => self::$IMAGE_MIME_TYPES, 'fields' => 'ids', 'posts_per_page' => -1, 's' => $search, 'orderby' => 'date', 'order' => 'DESC', 'ai_tools_list' => 1, ]; if ( $skipExisting ) { $args['meta_query'] = [[ 'relation' => 'OR', ['key' => '_wp_attachment_image_alt', 'compare' => 'NOT EXISTS'], ['key' => '_wp_attachment_image_alt', 'value' => '', 'compare' => '='], ]]; } $ids = get_posts( $args ); self::json_ok([ 'ids' => array_map( 'intval', is_array( $ids ) ? $ids : [] ), 'count' => is_array( $ids ) ? count( $ids ) : 0, ]); } /*** AJAX: Generate (single) ***/ public static function ajax_generate_single(): void { if ( ! current_user_can( 'upload_files' ) ) { self::json_error( 'forbidden', 403 ); } check_ajax_referer( self::NONCE_ACTION ); $id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0; $prompt = isset( $_POST['prompt'] ) ? sanitize_textarea_field( wp_unslash( $_POST['prompt'] ) ) : ''; $prompt_lang = isset( $_POST['prompt_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['prompt_lang'] ) ) : 'auto'; $tpl_src_lang = isset( $_POST['tpl_src_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['tpl_src_lang'] ) ) : 'auto'; $langCode = isset( $_POST['lang'] ) ? sanitize_text_field( wp_unslash( $_POST['lang'] ) ) : get_option( 'aigude_target_language', 'default' ); if ( ! $id || $prompt === '' ) { self::json_error( __( 'Missing parameters.', 'aigude-tools' ) ); } [$api_key, $api_url] = self::get_active_server_credentials(self::API_URL_IMG2DESC); if (empty($api_key)) { self::json_error(['message' => __('API key missing!', 'aigude-tools')]); } //Strip out slashes before you expand placeholders $prompt = wp_unslash($prompt); // Build v2 prompt_spec JSON (DeepL codes; per-token lang and translatable) $prompt_spec = self::build_prompt_spec($prompt, $prompt_lang, $tpl_src_lang, $id); // LOG: inspect prompt_spec sent (single) if (self::debug_enabled()) { error_log('[AiGude Tools] prompt_spec(single) id=' . $id . ': ' . wp_json_encode($prompt_spec)); } $orig = get_attached_file($id); if (!$orig || !file_exists($orig)) { self::json_error(__('File not found.', 'aigude-tools')); } $file = self::resize_temp_image($orig) ?: $orig; $target_lang = self::resolve_target_lang_code($langCode); $url = add_query_arg([ 'target_lang' => $target_lang, 'api_version' => 2, ], $api_url); $resp = self::curl_upload($url, $api_key, $file, [ 'prompt_spec' => wp_json_encode($prompt_spec) ]); if (is_wp_error($resp)) { self::json_error($resp->get_error_message()); } $http = (int) wp_remote_retrieve_response_code($resp); $body = wp_remote_retrieve_body($resp); if ($http === 401 || $http === 403) { // Try to extract an API message (if any) $api_msg = ''; $decoded = json_decode($body, true); if (is_array($decoded)) { $api_msg = $decoded['message'] ?? $decoded['error'] ?? $decoded['detail'] ?? ''; } self::json_error([ 'message' => $api_msg !== '' ? $api_msg : __('Invalid or unauthorized API key.', 'aigude-tools'), 'code' => 'invalid_api_key', ], $http); } if ($http !== 200) { self::json_error([ /* translators: %d: the HTTP status code returned by the API. */ 'message' => sprintf(__('API returned HTTP %d', 'aigude-tools'), $http), 'code' => 'http_error', ], $http); } $data = json_decode($body, true); if (!is_array($data) || empty($data['success']) || empty($data['generated_text'])) { self::json_error(__('Invalid or incomplete API response.', 'aigude-tools')); } self::json_ok([ 'text' => $data['generated_text'], 'creditsUsed' => $data['credits_used'] ?? null, 'provider' => $data['provider'] ?? null, ]); } /*** AJAX: Apply alt ***/ public static function ajax_apply_alt(): void { if ( ! current_user_can( 'upload_files' ) ) { self::json_error( 'forbidden', 403 ); } check_ajax_referer( self::NONCE_ACTION ); $id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0; $alt = isset( $_POST['alt'] ) ? sanitize_text_field( wp_unslash( $_POST['alt'] ) ) : ''; if ( $id <= 0 ) { self::json_error( __( 'Missing ID', 'aigude-tools' ) ); } update_post_meta( $id, '_wp_attachment_image_alt', $alt ); update_post_meta( $id, '_aigude_alt_suggestion', $alt ); self::json_ok(); } /*** AJAX: Bulk generation (IDs chosen via Media Modal or List view) ***/ public static function ajax_generate_bulk(): void { if ( ! current_user_can( 'upload_files' ) ) { self::json_error( 'forbidden', 403 ); } check_ajax_referer( self::NONCE_ACTION ); // ids as array $ids = array_map( 'absint', (array) ( $_POST['ids'] ?? [] ) ); $prompt = isset( $_POST['prompt'] ) ? sanitize_textarea_field( wp_unslash( $_POST['prompt'] ) ) : ''; $skipExisting = ! empty( $_POST['skipExisting'] ); $langCode = isset( $_POST['lang'] ) ? sanitize_text_field( wp_unslash( $_POST['lang'] ) ) : 'default'; $targetLang = self::resolve_target_lang_code($langCode); // V2: server-side translation only; collect language hints $prompt_lang = isset( $_POST['prompt_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['prompt_lang'] ) ) : 'auto'; $tpl_src_lang = isset( $_POST['tpl_src_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['tpl_src_lang'] ) ) : 'auto'; if ( empty( $ids ) || $prompt === '' ) { self::json_error( __( 'Missing parameters.', 'aigude-tools' ) ); } [$apiKey, $apiUrl] = self::get_active_server_credentials(self::API_URL_IMG2DESC); if (empty($apiKey)) { self::json_error(['message' => __('API key missing!', 'aigude-tools')]); } //Strip out slashes before you expand placeholders $prompt = wp_unslash($prompt); // No client-side translation; use raw template $tpl_for_expansion = $prompt; $creditsTotal = 0; $results = []; foreach ($ids as $id) { // Build v2 prompt_spec JSON (DeepL codes; per-token lang and translatable) $prompt_spec = self::build_prompt_spec($tpl_for_expansion, $prompt_lang, $tpl_src_lang, $id); // LOG: inspect prompt_spec sent (bulk per id) if (self::debug_enabled()) { error_log('[AiGude Tools] prompt_spec(bulk) id=' . $id . ': ' . wp_json_encode($prompt_spec)); } if ($skipExisting) { $existing = (string) get_post_meta($id, '_wp_attachment_image_alt', true); if (trim($existing) !== '') { $results[$id] = [ 'status' => 'skipped', 'existing_alt' => $existing, ]; continue; } } $orig = get_attached_file($id); if (!$orig || !file_exists($orig)) { $results[$id] = ['status' => 'error', 'message' => 'File not found']; continue; } $file = self::resize_temp_image($orig) ?: $orig; // max ~1080p temp $url = add_query_arg([ 'target_lang' => $targetLang, 'api_version' => 2, ], $apiUrl); $resp = self::curl_upload($url, $apiKey, $file, [ 'prompt_spec' => wp_json_encode($prompt_spec) ]); if (is_wp_error($resp)) { $results[$id] = ['status' => 'error', 'message' => 'cURL: ' . $resp->get_error_message()]; continue; } $http = (int) wp_remote_retrieve_response_code($resp); $body = wp_remote_retrieve_body($resp); if ($http === 401 || $http === 403) { $api_msg = ''; $decoded = json_decode($body, true); if (is_array($decoded)) { $api_msg = $decoded['message'] ?? $decoded['error'] ?? $decoded['detail'] ?? ''; } // Fail fast for the whole bulk request self::json_error([ 'message' => $api_msg !== '' ? $api_msg : __('Invalid or unauthorized API key.', 'aigude-tools'), 'code' => 'invalid_api_key', ], $http); } if ($http !== 200) { self::json_error([ /* translators: %d: the HTTP status code returned by the API. */ 'message' => sprintf(__('API returned HTTP %d', 'aigude-tools'), $http), 'code' => 'http_error', ], $http); } $data = json_decode($body, true); if (!is_array($data) || empty($data['success']) || empty($data['generated_text'])) { self::json_error([ 'message' => __('Invalid or incomplete API response.', 'aigude-tools'), 'code' => 'bad_api_payload', ], 502); } $alt = sanitize_text_field($data['generated_text']); update_post_meta($id, '_wp_attachment_image_alt', $alt); update_post_meta($id, '_aigude_alt_suggestion', $alt); $credits = isset($data['credits_used']) ? (int) $data['credits_used'] : 0; $provider = $data['provider'] ?? null; $creditsTotal += $credits; $results[$id] = [ 'status' => 'ok', 'alt' => $alt, 'credits' => $credits, 'provider' => $provider, ]; } self::json_ok([ 'results' => $results, 'creditsUsed' => $creditsTotal, ]); } /*** AJAX: Credits (all servers) ***/ public static function ajax_get_all_credits(): void { if ( ! current_user_can( 'manage_options' ) ) { self::json_error( 'forbidden', 403 ); } check_ajax_referer( self::NONCE_ACTION ); $servers = get_option('aigude_alt_servers', []); $results = []; foreach ((array) $servers as $index => $srv) { if (!empty($srv['enabled']) && !empty($srv['api_key'])) { $response = wp_remote_get(self::API_URL_CREDITS, [ 'headers' => ['apikey' => $srv['api_key']], 'timeout' => 30, ]); if (!is_wp_error($response)) { $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); $results[$index] = $data['remaining_credits'] ?? __('Error', 'aigude-tools'); } else { $results[$index] = __('Error', 'aigude-tools'); } } else { $results[$index] = __('Disabled', 'aigude-tools'); } } self::json_ok($results); } /*** Skip-mode storage + Media Modal filter ***/ public static function ajax_set_skip_mode(): void { check_ajax_referer(self::NONCE_ACTION); if (!current_user_can('upload_files')) { self::json_error('forbidden', 403); } $mode = isset( $_POST['mode'] ) ? absint( $_POST['mode'] ) : 0; update_user_meta(get_current_user_id(), '_ai_skip_existing_mode', $mode); self::json_ok(); } public static function filter_media_modal_query(array $args): array { // Runs within core's ajax_query_attachments() which already checks a nonce. // Avoid reading superglobals to satisfy NonceVerification sniff. $mode = (int) get_user_meta(get_current_user_id(), '_ai_skip_existing_mode', true); if (!$mode) { return $args; } $args['post_mime_type'] = 'image'; $missing_alt_group = [ 'relation' => 'OR', ['key' => '_wp_attachment_image_alt', 'compare' => 'NOT EXISTS'], ['key' => '_wp_attachment_image_alt', 'value' => '', 'compare' => '='], ]; $existing = isset($args['meta_query']) && is_array($args['meta_query']) ? $args['meta_query'] : []; $existing[] = $missing_alt_group; $args['meta_query'] = $existing; return $args; } /*** Attachment enrichment ***/ public static function add_original_filename(array $response, WP_Post $attachment, array $meta): array { if (!empty($meta['original_image'])) { $response['originalFilename'] = $meta['original_image']; } return $response; } /*** List page search SQL extensions ***/ private static function is_list_query($q): bool { return $q instanceof WP_Query && $q->get('ai_tools_list'); } public static function filter_posts_join(string $join, $query): string { if (!self::is_list_query($query)) return $join; global $wpdb; $join .= " LEFT JOIN $wpdb->postmeta AS ai_m1 ON ($wpdb->posts.ID = ai_m1.post_id AND ai_m1.meta_key = '_wp_attachment_image_alt')"; $join .= " LEFT JOIN $wpdb->postmeta AS ai_m2 ON ($wpdb->posts.ID = ai_m2.post_id AND ai_m2.meta_key = '_wp_attached_file')"; return $join; } public static function filter_posts_search(string $search, $query): string { if ( ! self::is_list_query( $query ) ) { return $search; } // Read search term from the query object (no superglobals) $raw = (string) $query->get( 's' ); $raw = $raw !== '' ? sanitize_text_field( $raw ) : ''; if ( $raw === '' ) { return ''; } global $wpdb; $like = '%' . $wpdb->esc_like( $raw ) . '%'; $parts = []; $parts[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $like ); $parts[] = $wpdb->prepare( "$wpdb->posts.post_name LIKE %s", $like ); $parts[] = $wpdb->prepare( "ai_m1.meta_value LIKE %s", $like ); $parts[] = $wpdb->prepare( "ai_m2.meta_value LIKE %s", $like ); return ' AND ( ' . implode( ' OR ', $parts ) . ' ) '; } public static function filter_posts_distinct($distinct, $query) { if (self::is_list_query($query)) return 'DISTINCT'; return $distinct; } /*** Helpers ***/ public static function resolve_target_lang_code(string $code): string { // 'default' maps from site locale to a DeepL target code if ($code === 'default') { $code = self::map_wp_locale_to_deepl(get_locale()); } // accept legacy short codes like 'en', 'de', 'pt', etc. $norm = self::normalize_deepl_lang_code($code, 'target'); // Fallback to EN if unknown return $norm !== '' ? $norm : 'EN'; } /** Return a map of DeepL target language codes to localized labels. */ public static function get_deepl_languages(): array { // Return autonyms (do not pass through __(), to avoid mixed-language lists) return self::$DEEPL_LANGS; } /** Normalize arbitrary input to a DeepL code. Allows 'en', 'EN', 'en-us', 'pt_BR', etc. Returns '' if unknown. */ private static function normalize_deepl_lang_code(string $code, string $context = 'target'): string { if ($code === '') return ''; $c = strtoupper(str_replace('_', '-', trim($code))); if ($c === 'AUTO' || $c === 'DEFAULT') return $c === 'DEFAULT' ? self::map_wp_locale_to_deepl(get_locale()) : 'auto'; // Exact match first if (isset(self::$DEEPL_LANGS[$c])) return $c; // Map language-only shorthands $map = [ 'EN' => 'EN', 'EN-UK' => 'EN-GB', 'EN-GB' => 'EN-GB', 'EN-US' => 'EN-US', 'DE' => 'DE', 'FR' => 'FR', 'ES' => 'ES', 'IT' => 'IT', 'NL' => 'NL', 'PL' => 'PL', 'RU' => 'RU', 'JA' => 'JA', 'ZH' => 'ZH', 'BG' => 'BG', 'CS' => 'CS', 'DA' => 'DA', 'EL' => 'EL', 'ET' => 'ET', 'FI' => 'FI', 'HU' => 'HU', 'ID' => 'ID', 'KO' => 'KO', 'LT' => 'LT', 'LV' => 'LV', 'NB' => 'NB', 'RO' => 'RO', 'SK' => 'SK', 'SL' => 'SL', 'SV' => 'SV', 'TR' => 'TR', 'UK' => 'UK', 'AR' => 'AR', 'PT' => 'PT-PT', 'PT-PT' => 'PT-PT', 'PT-BR' => 'PT-BR', 'BR' => 'PT-BR', ]; if (isset($map[$c])) return $map[$c]; // Locale-like inputs // Portuguese if ($c === 'PT' || $c === 'PT-PT') return 'PT-PT'; if ($c === 'PT-BR' || $c === 'BR' || $c === 'PT-BRA') return 'PT-BR'; // English variants if ($c === 'EN-US' || $c === 'EN-GB' || $c === 'EN') return $c === 'EN' ? 'EN' : $c; // Norwegian if ($c === 'NO' || $c === 'NB-NO' || $c === 'NN-NO' || $c === 'NB') return 'NB'; // Chinese locales if (strpos($c, 'ZH') === 0) return 'ZH'; // Fallback: try two-letter language part $two = substr($c, 0, 2); $two_map = [ 'EN' => 'EN', 'DE' => 'DE', 'FR' => 'FR', 'ES' => 'ES', 'IT' => 'IT', 'NL' => 'NL', 'PL' => 'PL', 'RU' => 'RU', 'JA' => 'JA', 'ZH' => 'ZH', 'BG' => 'BG', 'CS' => 'CS', 'DA' => 'DA', 'EL' => 'EL', 'ET' => 'ET', 'FI' => 'FI', 'HU' => 'HU', 'ID' => 'ID', 'KO' => 'KO', 'LT' => 'LT', 'LV' => 'LV', 'RO' => 'RO', 'SK' => 'SK', 'SL' => 'SL', 'SV' => 'SV', 'TR' => 'TR', 'UK' => 'UK', 'AR' => 'AR' ]; return $two_map[$two] ?? ''; } /** Map WordPress locale (e.g., en_US) to a DeepL target code. */ private static function map_wp_locale_to_deepl(string $locale): string { $loc = strtolower(str_replace('_', '-', $locale)); // Portuguese if ($loc === 'pt-br') return 'PT-BR'; if ($loc === 'pt-pt') return 'PT-PT'; // English if ($loc === 'en-gb') return 'EN-GB'; if ($loc === 'en-us' || strpos($loc, 'en-') === 0) return 'EN-US'; // Norwegian Bokmål if ($loc === 'nb-no' || $loc === 'no' || $loc === 'nb') return 'NB'; // Chinese if (strpos($loc, 'zh') === 0) return 'ZH'; // Common 2-letter fallbacks $two = substr($loc, 0, 2); return self::normalize_deepl_lang_code($two, 'target') ?: 'EN'; } /** Get last used languages (max 5) for a given type: 'target' | 'prompt' | 'placeholder' */ public static function get_recent_langs(string $type): array { $key = 'ai_recent_langs_' . $type; $arr = get_user_meta(get_current_user_id(), $key, true); return is_array($arr) ? array_values(array_filter($arr, 'is_string')) : []; } /** Push one language code into the recent list for a type (dedup, keep 5). */ public static function push_recent_lang(string $type, string $code): void { $norm = self::normalize_deepl_lang_code($code, $type === 'target' ? 'target' : 'source'); if ($norm === '' || $norm === 'auto') return; $key = 'ai_recent_langs_' . $type; $arr = get_user_meta(get_current_user_id(), $key, true); $arr = is_array($arr) ? $arr : []; $arr = array_values(array_unique(array_merge([ $norm ], array_filter($arr, 'is_string')))); $arr = array_slice($arr, 0, 5); update_user_meta(get_current_user_id(), $key, $arr); } /** * Returns [api_key, api_url] */ private static function get_active_server_credentials(?string $fallbackUrl = null): array { $servers = get_option('aigude_alt_servers', []); $api_key = ''; if (is_array($servers)) { // 1) Prefer enabled + default foreach ($servers as $srv) { if (!empty($srv['enabled']) && !empty($srv['api_key']) && !empty($srv['is_default'])) { $api_key = $srv['api_key']; break; } } // 2) Fallback: first enabled with a key if ($api_key === '') { foreach ($servers as $srv) { if (!empty($srv['enabled']) && !empty($srv['api_key'])) { $api_key = $srv['api_key']; break; } } } } return [$api_key, $fallbackUrl ?? self::API_URL_IMG2DESC]; } /** * Resize to ~1080p / 75% quality into a temp file. Returns path or null. */ private static function resize_temp_image(string $orig): ?string { $editor = wp_get_image_editor($orig); if (is_wp_error($editor)) { return null; } $editor->resize(1920, 1080, false); $editor->set_quality(75); $tmp = wp_tempnam('', 'ai_'); if (!$tmp) return null; $saved = $editor->save($tmp); return (isset($saved['path']) && file_exists($saved['path'])) ? $saved['path'] : null; } /** * Upload file to API using WP HTTP API (no direct cURL). */ private static function curl_upload(string $url, string $api_key, string $file_path, array $fields = []) { if (!file_exists($file_path)) { return new WP_Error('file_missing', __('Temporary image file missing', 'aigude-tools')); } $boundary = wp_generate_password(24, false); $headers = [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, 'apikey' => $api_key, ]; $body = ''; // Extra fields (e.g., prompt_spec JSON) foreach ($fields as $name => $value) { $body .= "--$boundary\r\n"; $body .= "Content-Disposition: form-data; name=\"" . $name . "\"\r\n\r\n"; $body .= (string) $value . "\r\n"; } $body .= "--$boundary\r\n"; $body .= "Content-Disposition: form-data; name=\"image_file\"; filename=\"" . basename($file_path) . "\"\r\n"; $body .= "Content-Type: " . (wp_check_filetype($file_path)['type'] ?: 'application/octet-stream') . "\r\n\r\n"; $body .= file_get_contents($file_path) . "\r\n"; $body .= "--$boundary--\r\n"; return wp_remote_post($url, [ 'headers' => $headers, 'body' => $body, 'timeout' => 120, ]); } /** Determine whether debug logging is enabled for this plugin. */ public static function debug_enabled(): bool { // Standard WordPress flags $wp_debug = defined('WP_DEBUG') && WP_DEBUG; $script_debug = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG; // Environment variable (e.g., Docker compose WORDPRESS_DEBUG=1) $env = getenv('WORDPRESS_DEBUG'); $env_debug = is_string($env) ? filter_var($env, FILTER_VALIDATE_BOOLEAN) : false; return ($wp_debug || $script_debug || $env_debug) === true; } private static function json_ok($data = null, int $status = 200): void { wp_send_json_success($data, $status); } private static function json_error($data = null, int $status = 400): void { wp_send_json_error($data, $status); } // Build prompt_spec JSON payload for API v2 including prompt_lang and per-token lang + translatable (DeepL codes) private static function build_prompt_spec(string $prompt_template, string $prompt_lang, string $placeholder_lang, int $attachment_id): array { $tokens_map = self::get_attachment_tokens($attachment_id); $spec_tokens = []; // Parse placeholders used in the template so we only send what is needed. // Supports modifiers: %token|raw% or %token|q% $used = []; if ($prompt_template !== '') { if (preg_match_all('/%([a-z0-9_\-]+)(?:\|[^%]*)?%/i', $prompt_template, $m)) { foreach ($m[1] as $tok) { $k = strtolower($tok); $used[$k] = true; } } } // Normalize prompt/placeholder languages to DeepL codes or 'auto' $norm_prompt_lang = (strtolower($prompt_lang) === 'auto') ? 'auto' : self::normalize_deepl_lang_code($prompt_lang, 'source'); $norm_placeholder_lang = (strtolower($placeholder_lang) === 'auto') ? 'auto' : self::normalize_deepl_lang_code($placeholder_lang, 'source'); foreach ($tokens_map as $key => $value) { // Skip tokens not present in the template if (!isset($used[$key])) continue; if (in_array($key, ['current_alt','current-alt','caption','description'], true)) { $str = trim((string) $value); if ($str === '') continue; // skip empty textual tokens $spec_tokens[$key] = [ 'value' => $str, 'lang' => $norm_placeholder_lang ?: 'auto', 'translatable' => true, ]; } elseif (in_array($key, ['title'], true)) { // Send title as non-translatable text $str = trim((string) $value); if ($str === '') continue; // skip empty textual tokens $spec_tokens[$key] = [ 'value' => $str, 'lang' => $norm_placeholder_lang ?: 'auto', 'translatable' => false, ]; } elseif (in_array($key, ['filename','filename_no_ext'], true)) { $str = (string) $value; if ($str === '') continue; // extremely unlikely, but guard $spec_tokens[$key] = [ 'value' => $str, 'lang' => $norm_placeholder_lang ?: 'auto', 'translatable' => false, ]; } elseif (in_array($key, ['width','height'], true)) { $num = (int) $value; if ($num <= 0) continue; // skip non-positive dimensions $spec_tokens[$key] = [ 'value' => $num, 'lang' => 'auto', 'translatable' => false, ]; } } return [ 'prompt_template' => $prompt_template, 'prompt_lang' => $norm_prompt_lang ?: 'auto', 'tokens' => $spec_tokens, ]; } /** Build a map of placeholder => value for an attachment */ private static function get_attachment_tokens(int $id): array { $post = get_post($id); $alt = (string) get_post_meta($id, '_wp_attachment_image_alt', true); $file = (string) get_post_meta($id, '_wp_attached_file', true); // e.g. '2025/08/foo-2160-scaled.jpg' $meta = wp_get_attachment_metadata($id) ?: []; // Prefer the original image filename if WP created a "-scaled" derivative // $meta['original_image'] is like '2025/08/foo.jpg' $original_rel = is_array($meta) && !empty($meta['original_image']) ? (string) $meta['original_image'] : ''; $basename = $original_rel ? wp_basename($original_rel) : ($file ? wp_basename($file) : ''); // Clean filename for display/placeholders (remove trailing "-scaled" before extension) $basename_clean = $basename ? preg_replace('/-scaled(?=\.[^.]+$)/i', '', $basename) : ''; // Base without extension $no_ext = $basename_clean ? preg_replace('/\.[^.]+$/', '', $basename_clean) : ''; $mime = get_post_mime_type($id) ?: ''; $w = (int) ($meta['width'] ?? 0); $h = (int) ($meta['height'] ?? 0); return [ // Text placeholders (auto-quoted by your expander) 'filename' => $basename_clean, // e.g. 'foo.jpg' (no "-scaled") 'filename_no_ext' => $no_ext, // e.g. 'foo' (no size / scaled suffix) 'title' => is_object($post) ? (string) $post->post_title : '', 'current_alt' => $alt, 'current-alt' => $alt, 'caption' => is_object($post) ? (string) $post->post_excerpt : '', 'description' => is_object($post) ? (string) $post->post_content : '', // Other 'mime' => $mime, 'width' => $w, 'height' => $h, ]; } } // Kick off AIGUDE_Tools_Plugin::init();