*/ class AATG_Text_Generator_Admin { private static $instance = null; /** * The ID of this plugin. * Used on slug of plugin menu. * Used on Root Div ID for React too. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. */ public function __construct( $plugin_name, $version ) { $this->plugin_name = $plugin_name; $this->version = $version; add_action('init', array($this, 'register_ajax_handlers')); } public static function get_instance() { if (self::$instance === null) { self::$instance = new self( 'ai-alt-text-generator', '1.0.0', '1.0.0'); } return self::$instance; } /** * Add Admin Page Menu page. * * @since 1.0.0 */ public function add_admin_menu() { add_menu_page( esc_html__( 'AI Alt Generator', 'ai-alt-text-generator' ), esc_html__( 'AI Alt Generator', 'ai-alt-text-generator' ), 'manage_options', $this->plugin_name, array( $this, 'add_setting_root_div' ), plugin_dir_url( __FILE__ ) . 'images/alt-icon.png' // Add the icon path here ); } /** * Add Root Div For React. * * @since 1.0.0 */ public function add_setting_root_div() { echo '
'; } /** * Render a contextual "upgrade to Pro" card on the plugin's own settings * page. Shown only here (never elsewhere in wp-admin) and hidden when the * Pro add-on is active, per WordPress.org guideline 11. * * @since 2.3.2 */ public function render_pro_upsell() { // Only on this plugin's own settings page (guideline 11), and never to // existing Pro customers. $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; if ( ! $screen || 'toplevel_page_' . $this->plugin_name !== $screen->id ) { return; } if ( defined( 'AATG_PRO_VERSION' ) ) { return; } $url = 'https://store.lessbutmore.ai'; $features = array( __( 'WooCommerce product context for commerce-aware alt text', 'ai-alt-text-generator' ), __( 'Scheduled background scans — new images described automatically, forever', 'ai-alt-text-generator' ), __( 'Coverage analytics dashboard to track progress toward 100%', 'ai-alt-text-generator' ), ); ?>

PRO

plugin_name ); if ( ! ( isset( $screen->base ) && in_array( $screen->base, $admin_scripts_bases ) ) ) { return; } // Enqueue WordPress media scripts wp_enqueue_media(); wp_enqueue_style( 'at-grid', esc_url( AATG_TEXT_GENERATOR_URL . 'assets/library/at-grid/at-grid.min.css'), array(), $this->version ); $at_grid_css_var = " :root{ --at-container-sm: 540px; --at-container-md: 720px; --at-container-lg: 960px; --at-container-xl: 1140px; --at-gutter:15px; } "; wp_add_inline_style( 'at-grid', $at_grid_css_var ); /*Scripts dependency files*/ $deps_file = AATG_TEXT_GENERATOR_PATH . 'build/admin/settings.asset.php'; /*Fallback dependency array*/ $dependency = []; $version = $this->version; /*Set dependency and version*/ if ( file_exists( $deps_file ) ) { $deps_file = require( $deps_file ); $dependency = $deps_file['dependencies']; $version = $deps_file['version']; } $version = filemtime( AATG_TEXT_GENERATOR_PATH . 'build/admin/settings.js' ); wp_enqueue_script( $this->plugin_name, esc_url( AATG_TEXT_GENERATOR_URL . 'build/admin/settings.js' ), $dependency, $version, true ); $style_version = filemtime( AATG_TEXT_GENERATOR_PATH . 'build/admin/style-settings.css' ); wp_enqueue_style( $this->plugin_name, esc_url( AATG_TEXT_GENERATOR_URL . 'build/admin/style-settings.css' ), array('wp-components'), $style_version ); $localize = array( 'version' => $this->version, 'root_id' => $this->plugin_name, ); wp_set_script_translations( $this->plugin_name, $this->plugin_name ); wp_localize_script( $this->plugin_name, 'wpReactPluginBoilerplateBuild', $localize ); } public function add_bulk_action_option( $bulk_actions ) { $bulk_actions['generate_alt_text'] = esc_html__( 'Generate Alt Text', 'ai-alt-text-generator' ); return $bulk_actions; } public function enqueue_media_admin_scripts() { // only in media and post edit pages if ( ! ( 'post.php' === $GLOBALS['pagenow'] || 'post-new.php' === $GLOBALS['pagenow'] || 'upload.php' === $GLOBALS['pagenow'] ) ) { return; } wp_enqueue_script( 'ai-alt-text-generator-media', esc_url( plugin_dir_url( __FILE__ ) . 'js/media-button.js' ), array( 'jquery' ), time(), true ); wp_enqueue_script( 'alt-gen-gutenberg-blocks', AATG_TEXT_GENERATOR_URL . 'build/admin/blocks.js', // Adjust the path array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor'), $this->version ); $nonce = wp_create_nonce( 'alt_gen_ajax_nonce' ); wp_localize_script( 'ai-alt-text-generator-media', 'aiAltTextGenerator', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => $nonce ) ); } /** * Dismissible upsell shown on WooCommerce stores without Pro. Pro writes * product-aware alt text (name + attributes) — a strong fit for shops, which * are a core part of our ICP. */ public function show_woocommerce_upsell_notice() { if ( ! current_user_can( 'manage_options' ) ) { return; } if ( defined( 'AATG_PRO_VERSION' ) || ! class_exists( 'WooCommerce' ) ) { return; } if ( get_user_meta( get_current_user_id(), 'aatg_wc_upsell_dismissed', true ) ) { return; } // Only on commerce / plugin / dashboard screens to avoid nagging everywhere. $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; $relevant = $screen && ( false !== strpos( $screen->id, 'woocommerce' ) || false !== strpos( $screen->id, 'ai-alt-text' ) || 'product' === $screen->post_type || 'dashboard' === $screen->id || 'plugins' === $screen->id ); if ( ! $relevant ) { return; } $dismiss_url = wp_nonce_url( add_query_arg( 'aatg_dismiss_wc_upsell', '1' ), 'aatg_dismiss_wc_upsell' ); $pro_url = 'https://store.lessbutmore.ai/pricing?utm_source=plugin&utm_medium=wc_notice&utm_campaign=woocommerce'; ?>

id, 'ai-alt-text' ) || 'dashboard' === $screen->id || 'upload' === $screen->id || 'plugins' === $screen->id ); if ( ! $relevant ) { return; } $upgrade_url = aatg_managed_upgrade_url( 'out_of_credits', 'admin_notice' ); $snooze_url = wp_nonce_url( add_query_arg( 'aatg_snooze_credit_notice', '1' ), 'aatg_snooze_credit_notice' ); $paused_for = human_time_diff( (int) $state['since'], time() ); ?>

id, 'ai-alt-text' ) || 'dashboard' === $screen->id || 'upload' === $screen->id ); if ( ! $relevant ) { return; } $count = number_format_i18n( (int) get_option( 'aatg_generated_count', 0 ) ); $review_url = 'https://wordpress.org/support/plugin/ai-alt-text-generator/reviews/#new-post'; $dismiss_url = wp_nonce_url( add_query_arg( 'aatg_dismiss_review', '1' ), 'aatg_dismiss_review' ); ?>

' . esc_html( $count ) . '' ); ?>

0, 'with_alt' => 0, 'missing' => 0, 'percent' => 100 ); $pct = (int) $s['percent']; $bar = $pct >= 90 ? '#1e7a34' : ( $pct >= 50 ? '#bd8600' : '#b32d2e' ); $settings_url = admin_url( 'admin.php?page=' . $this->plugin_name ); ?>
%
0 ) : ?>

' . esc_html( number_format_i18n( $s['missing'] ) ) . '' ); ?>

✓

%s

', esc_html__('Alt text generation started for the selected images.', 'ai-alt-text-generator') ); return; } else { return; } printf( '

%s

', esc_html($text) ); } public function show_bulk_processing_notice() { if (!get_option('aatg_is_processing')) { return; } // Only users who can start or stop a run (the Bulk tab needs this too). if (!current_user_can('manage_options')) { return; } $total = (int) get_option('aatg_processing_total', 0); $current = (int) get_option('aatg_processing_current', 0); $progress = $total > 0 ? round(($current / $total) * 100) : 0; $paused = AATG_Text_Generator_Restpoint::is_paused(); $bulk_url = admin_url('admin.php?page=' . $this->plugin_name . '#/bulk-generate'); // The Bulk Generation tab drives the run and shows its own progress. $screen = function_exists('get_current_screen') ? get_current_screen() : null; if ($screen && false !== strpos((string) $screen->id, $this->plugin_name)) { return; } ?>

#toplevel_page_' . esc_attr( $this->plugin_name ) . ' a.menu-top img { opacity: 1; width: 28px; margin-top: -5px; } '; } // AJAX Handler Function public function generate_alt_text_ajax() { try { // Check nonce if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'alt_gen_ajax_nonce')) { wp_send_json_error('Security check failed.'); return; } if (!current_user_can('upload_files')) { wp_send_json_error('You do not have permission to generate alt text.', 403); return; } $attachment_id = null; if (!empty($_POST['post_id'])) { $attachment_id = absint($_POST['post_id']); } if (!$attachment_id || 'attachment' !== get_post_type($attachment_id)) { wp_send_json_error('Could not find a valid image ID in the request.'); return; } // The nonce is handed to every user who can open the editor, so it // proves nothing about which images they may change. if (!current_user_can('edit_post', $attachment_id)) { wp_send_json_error('You do not have permission to edit this image.', 403); return; } // Get the image URL from the attachment ID $image_url = wp_get_attachment_url($attachment_id); if (!$image_url) { wp_send_json_error('Could not find an image URL for ID: ' . $attachment_id); return; } // generate_alt_text_with_ai() flattens every failure to '', so the // reason comes from what the managed client records. Clear it first // so an older failure can't be reported for this one. delete_transient('aatg_managed_last_error'); // Generate alt text using AI provider $alt_text = $this->generate_alt_text_with_ai($image_url, array('attachment_id' => $attachment_id, 'source' => 'single')); if (empty($alt_text)) { // Out of credits used to read "The AI provider failed to // generate alt text.", which gives the user nothing to act on. $last = get_transient('aatg_managed_last_error'); wp_send_json_error( $last && function_exists('aatg_managed_error_message') ? aatg_managed_error_message($last) : __('The AI provider failed to generate alt text.', 'ai-alt-text-generator') ); return; } // Save the generated alt text (with add-on hooks). $alt_text = $this->save_generated_alt_text($attachment_id, $alt_text, array('source' => 'single')); wp_send_json_success($alt_text); } catch (Exception $e) { wp_send_json_error($e->getMessage()); } } public function handle_bulk_action($redirect_to, $doaction, $post_ids) { if ($doaction === 'generate_alt_text') { // Only touch images the current user is allowed to edit. if (is_array($post_ids)) { $post_ids = array_filter($post_ids, function ($id) { return current_user_can('edit_post', (int) $id); }); } if (empty($post_ids) || !is_array($post_ids)) { return add_query_arg('aatg_error', 'no_images_selected', $redirect_to); } // Don't stomp the counters of a run already started from the settings // screen — the two share aatg_processing_* state. if (get_option('aatg_is_processing', false)) { return add_query_arg('aatg_error', 'already_processing', $redirect_to); } // Keep the whole selection in the transient. The batch processor pages // through it with `offset`, so the list has to stay stable for the // duration of the run — shifting items off it would skip images. $post_ids = array_values(array_map('intval', $post_ids)); $total = count($post_ids); // Process the first image inline so the user gets instant feedback. $this->generate_alt_text_for_image_function($post_ids[0]); if ($total > 1) { set_transient('aatg_bulk_generation_ids', $post_ids, HOUR_IN_SECONDS); // process_media_batch() returns immediately unless this flag is // set, which is why the background half of a Media Library bulk // action never ran before 2.5.5. update_option('aatg_is_processing', true); update_option('aatg_processing_total', $total); update_option('aatg_processing_current', 1); update_option('aatg_processing_skipped', 0); update_option('aatg_processing_heartbeat', time(), false); wp_schedule_single_event(time() + 5, 'ai_process_media_batch', array(10)); } else { // Single image: already done inline, nothing to schedule. delete_transient('aatg_bulk_generation_ids'); update_option('aatg_is_processing', false); update_option('aatg_processing_total', 0); update_option('aatg_processing_current', 0); update_option('aatg_processing_skipped', 0); } // Add a query arg to notify the user $redirect_to = add_query_arg('aatg_message', 'bulk_started', $redirect_to); } return $redirect_to; } public function get_image_url_by_size($post_id, $size = 'thumbnail') { // Get the image attachment URL in the specified size $image = wp_get_attachment_image_src($post_id, $size); // Check if the image exists if ($image) { return $image[0]; // URL of the image } return false; // Return false if the image doesn't exist } public function generate_alt_text_for_image_function( $post_id ) { // Keep-worded alt text is left alone. Checked before generating so a // protected image costs no credit and no provider round-trip; the // aatg_alt_text filter would only have thrown the answer away. if ( aatg_is_alt_text_protected( $post_id ) ) { return; } // Get the smaller image URL (e.g., thumbnail) $image_url = $this->get_image_url_by_size($post_id, 'thumbnail'); // Generate alt text using the AI provider $alt_text = $this->generate_alt_text_with_ai( $image_url, array('attachment_id' => $post_id, 'source' => 'bulk') ); // Save the generated alt text (with add-on hooks). $this->save_generated_alt_text( $post_id, $alt_text, array('source' => 'bulk') ); } public function generate_alt_text_on_upload( $attachment_id ) { // Check if the attachment is an image if ( wp_attachment_is_image( $attachment_id ) ) { // Get the image URL $image_url = $this->get_image_url_by_size($attachment_id, 'thumbnail'); // Generate alt text using AI provider $alt_text = $this->generate_alt_text_with_ai( $image_url, array('attachment_id' => $attachment_id, 'source' => 'upload') ); // Save the generated alt text (with add-on hooks). $this->save_generated_alt_text( $attachment_id, $alt_text, array('source' => 'upload') ); } } /** * Persist a generated alt text value, applying add-on hooks. * * Centralises the "filter then save then notify" sequence so every generation * path exposes the same extension points to add-ons. * * @since 2.3.0 * * @param int $attachment_id Attachment ID. * @param string $alt_text Generated alt text. * @param array $context Request context (e.g. 'source'). * @return string The alt text that was saved (possibly filtered). */ public function save_generated_alt_text( $attachment_id, $alt_text, $context = array() ) { return aatg_save_generated_alt_text( $attachment_id, $alt_text, $context ); } public function generate_alt_text_with_ai($image_url, $context = array()) { try { // Get settings $options = get_option('aatg_text_generator_options'); $provider = $options['ai_provider'] ?? 'openai'; $api_key_field = $provider . '_key'; if (!aatg_managed_mode_active() && empty($options[$api_key_field])) { return ''; } // Prefer a sensibly-sized image for the attachment (higher quality // than a thumbnail, cheaper than the full-size original); fall back // to reading the provided URL. $image_base64 = ''; if ( ! empty( $context['attachment_id'] ) && function_exists( 'aatg_get_image_base64_for_attachment' ) ) { $image_base64 = aatg_get_image_base64_for_attachment( (int) $context['attachment_id'] ); } if ( '' === $image_base64 ) { $upload_dir = wp_upload_dir(); $image_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $image_url); if (!file_exists($image_path)) { return ''; } $image_data = file_get_contents($image_path); if ($image_data === false) { return ''; } $image_base64 = base64_encode($image_data); } // Get prompt and language from settings $prompt = $options['prompt'] ?? 'Create a SEO optimized alt text for this image. Don\'t include quotes and keep it informative and concise.'; $language = $options['language'] ?? 'english'; // Use the provider factory to generate alt text $result = AATG_Provider_Factory::generate_alt_text( $provider, $image_base64, $prompt, $language, $options[$api_key_field], $context ); if (!$result['success']) { return ''; } $alt_text = $result['alt_text']; return $alt_text; } catch (Exception $e) { return ''; } } // Keep the old method name for backward compatibility public function generate_alt_text_with_openai($image_url) { return $this->generate_alt_text_with_ai($image_url); } private function generate_alt_text_with_openai_batch( $images_data ) { // OpenAI API key from settings $openai_key = get_option( 'aatg_text_generator_options' )['openai_key']; // Prepare tasks $tasks = []; foreach ( $images_data as $index => $image_data ) { $sanitized_url = esc_url_raw( $image_data['image_url'] ); $image = file_get_contents( $sanitized_url ); if ( $image === false ) { // Handle error, perhaps log it or notify the admin continue; } $image_base64 = base64_encode( $image ); $task = [ 'custom_id' => 'task-' . $index, 'method' => 'POST', 'url' => '/v1/chat/completions', 'body' => [ 'model' => 'gpt-4o', 'temperature' => 0.2, 'messages' => [ [ 'role' => 'system', 'content' => 'Your goal is to generate a SEO optimized alt text for this image. Don\'t include quotes and keep it informative and concise.', ], [ 'role' => 'user', 'content' => [ [ 'type' => 'text', 'text' => 'Create a SEO optimized alt text for this image. Don\'t include quotes and keep it informative and concise.', ], [ 'type' => 'image_url', 'image_url' => [ 'url' => 'data:image/jpeg;base64,' . $image_base64, ], ], ], ], ], ], ]; $tasks[] = $task; } // Create JSONL file $file_name = 'batch_tasks_images.jsonl'; $file_path = wp_upload_dir()['basedir'] . '/' . $file_name; $file = fopen( $file_path, 'w' ); foreach ( $tasks as $task ) { fwrite( $file, json_encode( $task ) . "\n" ); } fclose( $file ); // Upload the JSONL file to OpenAI using curl $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.openai.com/v1/files"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $openai_key, ]); curl_setopt($ch, CURLOPT_POSTFIELDS, [ 'file' => new CURLFile($file_path, 'application/jsonl', $file_name), 'purpose' => 'batch', ]); $response = curl_exec($ch); if (curl_errno($ch)) { // Handle error return []; } curl_close($ch); $file_data = json_decode($response, true); $file_id = $file_data['id'] ?? ''; if ( empty( $file_id ) ) { // Handle error return []; } // Create the batch job $batch_url = 'https://api.openai.com/v1/batches'; $batch_response = wp_remote_post( $batch_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $openai_key, 'Content-Type' => 'application/json', ], 'body' => json_encode([ 'input_file_id' => $file_id, 'endpoint' => '/v1/chat/completions', 'completion_window' => '24h', ]), ]); if ( is_wp_error( $batch_response ) ) { // Handle error return []; } $batch_body = wp_remote_retrieve_body( $batch_response ); $batch_data = json_decode( $batch_body, true ); $batch_id = $batch_data['id'] ?? ''; if ( empty( $batch_id ) ) { // Handle error return []; } // Check batch status (implement a mechanism to check status periodically if needed) $status_url = 'https://api.openai.com/v1/batches/' . $batch_id; do { $status_response = wp_remote_get( $status_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $openai_key, ], ]); if ( is_wp_error( $status_response ) ) { // Handle error return []; } $status_body = wp_remote_retrieve_body( $status_response ); $status_data = json_decode( $status_body, true ); if ( $status_data['status'] === 'completed' ) { break; } // Wait before checking again sleep(60); } while ( $status_data['status'] !== 'completed' ); // Retrieve results $result_file_id = $status_data['output_file_id'] ?? ''; if ( empty( $result_file_id ) ) { // Handle error return []; } $result_url = 'https://api.openai.com/v1/files/' . $result_file_id . '/content'; $result_response = wp_remote_get( $result_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $openai_key, ], ]); if ( is_wp_error( $result_response ) ) { // Handle error return []; } $result_body = wp_remote_retrieve_body( $result_response ); $results = explode("\n", trim( $result_body )); // Process results $alt_texts = []; foreach ( $results as $result ) { $result_data = json_decode( $result, true ); $task_id = $result_data['custom_id'] ?? ''; $alt_text = $result_data['response']['body']['choices'][0]['message']['content'] ?? ''; if ( !empty( $task_id ) && !empty( $alt_text ) ) { $index = (int) str_replace('task-', '', $task_id); $alt_texts[] = [ 'post_id' => $images_data[$index]['post_id'], 'alt_text' => $alt_text, ]; } } return $alt_texts; } /** * Register settings. * Common callback function of rest_api_init and admin_init * Schema: http://json-schema.org/draft-04/schema# * * Add your own settings fields here * * @since 1.0.0 * * @param null. * @return void */ public function register_settings() { $defaults = aatg_text_generator_default_options(); register_setting( 'aatg_text_generator_settings_group', 'aatg_text_generator_options', array( 'type' => 'object', 'default' => $defaults, 'show_in_rest' => array( 'schema' => array( 'type' => 'object', 'properties' => array( /*===Settings===*/ /*Settings -> General*/ 'ai_provider' => array( 'type' => 'string', 'default' => $defaults['ai_provider'], 'sanitize_callback' => 'sanitize_text_field', ), 'openai_key' => array( 'type' => 'string', 'default' => $defaults['openai_key'], 'sanitize_callback' => 'sanitize_text_field', // Sanitize the API key ), 'anthropic_key' => array( 'type' => 'string', 'default' => $defaults['anthropic_key'], 'sanitize_callback' => 'sanitize_text_field', // Sanitize the API key ), 'on_upload_alt_text' => array( 'type' => 'boolean', 'default' => $defaults['on_upload_alt_text'] ), 'all_alt_text' => array( 'type' => 'boolean', 'default' => $defaults['all_alt_text'] ), 'set_title' => array( 'type' => 'boolean', 'default' => $defaults['set_title'] ), 'set_caption' => array( 'type' => 'boolean', 'default' => $defaults['set_caption'] ), 'set_description' => array( 'type' => 'boolean', 'default' => $defaults['set_description'] ), 'protected_alt_words' => array( 'type' => 'string', 'default' => $defaults['protected_alt_words'], 'sanitize_callback' => 'sanitize_text_field' ), 'prompt' => array( 'type' => 'string', 'default' => $defaults['prompt'] ), 'language' => array( 'type' => 'string', 'default' => $defaults['language'] ), ), ), ), ) ); } /** * Register the AJAX handlers */ public function register_ajax_handlers() { // generate_alt_text is registered once, in define_admin_hooks(). add_action('wp_ajax_aatg_processing_status', array($this, 'get_processing_status_ajax')); add_action('wp_ajax_aatg_process_next_batch', array($this, 'process_next_batch_ajax')); add_action('wp_ajax_aatg_stop_processing', array($this, 'stop_processing_ajax')); } public function get_processing_status_ajax() { if (!current_user_can('upload_files')) { wp_send_json_error('Permission denied', 403); } $status = [ 'is_processing' => (bool) get_option('aatg_is_processing', false), 'total_items' => (int) get_option('aatg_processing_total', 0), 'current_item' => (int) get_option('aatg_processing_current', 0), 'paused' => AATG_Text_Generator_Restpoint::is_paused(), ]; wp_send_json($status); } /** The admin notice's Stop button. Same reset as the Bulk tab's Stop. */ public function stop_processing_ajax() { check_ajax_referer('aatg_bulk_notice'); if (!current_user_can('manage_options')) { wp_send_json_error('Permission denied', 403); } $rest_point = new AATG_Text_Generator_Restpoint(); $rest_point->stop_processing(); wp_send_json_success(); } public function process_next_batch_ajax() { if (!current_user_can('upload_files')) { wp_send_json_error('Permission denied', 403); } // Manually run the next batch from the REST point logic $rest_point = new AATG_Text_Generator_Restpoint(); $rest_point->process_media_batch(10); // Process a batch of 10 // Return the latest status $this->get_processing_status_ajax(); } }