$post_id, 'provider' => $credentials['provider'], 'model' => $model ) ); if ( 'google' === $credentials['provider'] ) { return self::call_google_image_api( $credentials['api_key'], $post_id, $timeout, $model, $error_context ); } if ( 'anthropic' === $credentials['provider'] ) { return new WP_Error( 'unsupported_provider_for_images', __( 'Anthropic does not support image generation. Please use OpenAI or Google credentials for image generation.', 'ai-content-generator-for-woocommerce' ) ); } return self::call_openai_image_api( $credentials['api_key'], $post_id, $timeout, $model, $error_context ); } /** * Calls OpenAI image generation API. * Uses gpt-image-2.5-sunburst by default. Compatible with other gpt-image-* variants. * * @param string $api_key * @param int $post_id * @param int $timeout * @param string $model * @param array $error_context See explain_provider_error(). * @return array{ image_urls: string[] }|WP_Error */ private static function call_openai_image_api( $api_key, $post_id, $timeout = 30, $model = 'gpt-image-2.5-sunburst', array $error_context = array() ) { $body = array( 'model' => $model, 'prompt' => self::generate_image_prompt( $post_id ), 'size' => '1024x1024', ); $response = wp_remote_post( 'https://api.openai.com/v1/images/generations', array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key, ), 'body' => wp_json_encode( $body ), 'timeout' => $timeout, ) ); if ( is_wp_error( $response ) ) { return self::provider_error( 'openai', $response, $error_context ); } $data = json_decode( wp_remote_retrieve_body( $response ), true ); //Handling logging b64 image $log_data = $data; if ( isset($log_data['data'][0]['b64_json']) ) { $base64 = $log_data['data'][0]['b64_json']; $log_data['data'][0]['b64_json'] = '[BASE64_IMAGE_REMOVED length=' . strlen($base64) . ']'; } self::log_debug( 'OpenAI image API response', array( 'data' => $log_data, 'model' => $model ) ); // Handle transport and API-level errors if ( self::is_failed_response( $response ) || isset( $data['error'] ) ) { return self::provider_error( 'openai', $response, $error_context ); } if ( empty( $data['data'] ) ) { return new WP_Error( 'api_error', 'No valid image data was returned by the API.' ); } $image_urls = array(); foreach ( $data['data'] as $item ) { $base64_data = ''; $mime_type = 'image/png'; // Default fallback // 1. Check if the API returned base64 directly in a dedicated key if ( ! empty( $item['b64_json'] ) ) { $base64_data = $item['b64_json']; } elseif ( ! empty( $item['b64'] ) ) { $base64_data = $item['b64']; } elseif ( ! empty( $item['base64'] ) ) { $base64_data = $item['base64']; } // 2. Check if the API returned a base64 Data URI inside the 'url' key elseif ( ! empty( $item['url'] ) ) { if ( preg_match( '/^data:image\/(\w+);base64,/', $item['url'], $matches ) ) { // Extract the raw base64 string and the mime type $base64_data = substr( $item['url'], strpos( $item['url'], ',' ) + 1 ); $mime_type = 'image/' . $matches[1]; } else { // It's a standard URL, add it directly and skip the base64 processing $image_urls[] = $item['url']; continue; } } // 3. If we successfully captured base64 data, process it if ( ! empty( $base64_data ) ) { // Double check for any lingering Data URI prefixes just in case if ( preg_match( '/^data:image\/(\w+);base64,/', $base64_data, $matches ) ) { $base64_data = substr( $base64_data, strpos( $base64_data, ',' ) + 1 ); $mime_type = 'image/' . $matches[1]; } $local_url = self::save_generated_image_to_uploads( $base64_data, $mime_type ); if ( ! is_wp_error( $local_url ) ) { $image_urls[] = $local_url; } } } if ( empty( $image_urls ) ) { return new WP_Error( 'api_error', 'Failed to process image data returned by the API.' ); } return array( 'image_urls' => $image_urls, ); } /** * Calls Gemini image generation and stores image bytes to media uploads. * * @param string $api_key * @param int $post_id * @param array $error_context See explain_provider_error(). * @return array{ image_urls: string[] }|WP_Error */ private static function call_google_image_api( $api_key, $post_id, $timeout = 30, $model = 'gemini-2.0-flash-preview-image-generation', array $error_context = array() ) { $response = wp_remote_post( 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . rawurlencode( $api_key ), //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration array( 'headers' => array( 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array( 'contents' => array( array( 'role' => 'user', 'parts' => array( array( 'text' => self::generate_image_prompt( $post_id ), ), ), ), ), 'generationConfig' => array( 'responseModalities' => array( 'TEXT', 'IMAGE' ), ), ) ), 'timeout' => $timeout, ) ); $data = is_wp_error( $response ) ? $response->get_error_message() : json_decode( wp_remote_retrieve_body( $response ), true ); self::log_debug( 'Gemini image API response', array( 'data' => $data ) ); if ( self::is_failed_response( $response ) ) { return self::provider_error( 'google', $response, $error_context ); } $parts = isset( $data['candidates'][0]['content']['parts'] ) && is_array( $data['candidates'][0]['content']['parts'] ) ? $data['candidates'][0]['content']['parts'] : array(); $image_urls = array(); foreach ( $parts as $part ) { if ( ! isset( $part['inlineData']['data'] ) || ! is_string( $part['inlineData']['data'] ) ) { continue; } $mime_type = isset( $part['inlineData']['mimeType'] ) && is_string( $part['inlineData']['mimeType'] ) ? $part['inlineData']['mimeType'] : 'image/png'; $image_url = self::save_generated_image_to_uploads( $part['inlineData']['data'], $mime_type ); if ( ! is_wp_error( $image_url ) ) { $image_urls[] = $image_url; } } if ( empty( $image_urls ) ) { $msg = isset( $data['error']['message'] ) ? $data['error']['message'] : 'No image data returned by Gemini.'; return new WP_Error( 'api_error', $msg ); } return array( 'image_urls' => $image_urls ); } /** * Whether image generation can run with the current provider settings. * * @return true|WP_Error */ public static function can_generate_images() { $credentials = self::get_provider_credentials( 'image_generation' ); if ( ! $credentials['api_key'] ) { return self::missing_provider_error( 'image_generation' ); } if ( 'anthropic' === $credentials['provider'] ) { return new WP_Error( 'unsupported_provider_for_images', __( 'Anthropic does not support image generation. Please use OpenAI or Google credentials for image generation.', 'ai-content-generator-for-woocommerce' ) ); } return true; } /** * Adds an image to the media library and sets it as the product's * featured image or appends it to the gallery. Alt text, title and * caption are set to the product name. * * Images this plugin saved to uploads are copied from disk; any other * URL is downloaded. * * @param int $product_id * @param string $image_url * @param bool $as_gallery True to append to the gallery instead of setting the featured image. * @return int|WP_Error Attachment ID. */ public static function attach_image_to_product( $product_id, $image_url, $as_gallery = false ) { $product = wc_get_product( absint( $product_id ) ); if ( ! $product ) { return new WP_Error( 'invalid_product', __( 'Invalid product ID.', 'ai-content-generator-for-woocommerce' ) ); } require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $product_id = $product->get_id(); $product_name = $product->get_name(); $local_path = self::get_local_upload_path( $image_url ); if ( $local_path ) { $tmp = wp_tempnam( $local_path ); if ( ! $tmp || ! copy( $local_path, $tmp ) ) { return new WP_Error( 'file_copy_error', __( 'Could not copy the generated image.', 'ai-content-generator-for-woocommerce' ) ); } } else { $tmp = download_url( $image_url ); if ( is_wp_error( $tmp ) ) { /* translators: %s: error message */ return new WP_Error( 'download_failed', sprintf( __( 'Failed to download image: %s', 'ai-content-generator-for-woocommerce' ), $tmp->get_error_message() ) ); } } $extension = strtolower( pathinfo( (string) wp_parse_url( $image_url, PHP_URL_PATH ), PATHINFO_EXTENSION ) ); if ( ! in_array( $extension, array( 'png', 'jpg', 'jpeg', 'webp' ), true ) ) { $extension = 'png'; } $file_array = array( 'name' => 'product-image-' . $product_id . '-' . time() . '.' . $extension, 'tmp_name' => $tmp, ); $attachment_data = array( 'post_title' => $product_name, 'post_content' => $product_name, 'post_excerpt' => $product_name, ); $attach_id = media_handle_sideload( $file_array, $product_id, '', $attachment_data ); if ( is_wp_error( $attach_id ) ) { wp_delete_file( $tmp ); return $attach_id; } update_post_meta( $attach_id, '_wp_attachment_image_alt', $product_name ); if ( $as_gallery ) { $gallery_ids = $product->get_gallery_image_ids(); $gallery_ids[] = $attach_id; $product->set_gallery_image_ids( array_unique( $gallery_ids ) ); } else { $product->set_image_id( $attach_id ); } $product->save(); return $attach_id; } /** * Makes sure a generated image is stored in uploads, so it can be shown * for review and attached later. Provider-hosted URLs can expire. * * @param string $image_url * @return string|WP_Error Uploads URL. */ public static function keep_generated_image( $image_url ) { if ( self::get_local_upload_path( $image_url ) ) { return $image_url; } require_once ABSPATH . 'wp-admin/includes/file.php'; $tmp = download_url( $image_url ); if ( is_wp_error( $tmp ) ) { /* translators: %s: error message */ return new WP_Error( 'download_failed', sprintf( __( 'Failed to download image: %s', 'ai-content-generator-for-woocommerce' ), $tmp->get_error_message() ) ); } $mime_type = wp_get_image_mime( $tmp ); $binary = file_get_contents( $tmp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- local temp file. wp_delete_file( $tmp ); if ( ! $mime_type || false === $binary ) { return new WP_Error( 'invalid_image_data', __( 'Could not decode generated image data.', 'ai-content-generator-for-woocommerce' ) ); } return self::save_generated_image_to_uploads( base64_encode( $binary ), $mime_type ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- matches the provider data format. } /** * Deletes generated image files from uploads once they have been copied * into the media library. Only files this plugin created are touched. * * @param string[] $image_urls * @return void */ public static function discard_generated_images( array $image_urls ) { foreach ( $image_urls as $url ) { $path = self::get_local_upload_path( $url ); if ( $path && 0 === strpos( wp_basename( $path ), 'wtofe-ai-generated-' ) ) { wp_delete_file( $path ); } } } /** * Maps an uploads URL to its file path. * * @param string $url * @return string Absolute path, or '' when the URL is not an existing file in uploads. */ private static function get_local_upload_path( $url ) { $upload_dir = wp_upload_dir(); $base_url = set_url_scheme( trailingslashit( $upload_dir['baseurl'] ) ); $url = set_url_scheme( (string) $url ); if ( 0 !== strpos( $url, $base_url ) ) { return ''; } $relative = substr( $url, strlen( $base_url ) ); if ( false !== strpos( $relative, '..' ) ) { return ''; } $path = trailingslashit( $upload_dir['basedir'] ) . $relative; return is_file( $path ) ? $path : ''; } /** * Persists base64 image data in uploads and returns a public URL. * * @param string $base64_data * @param string $mime_type * @return string|WP_Error */ private static function save_generated_image_to_uploads( $base64_data, $mime_type ) { $binary = base64_decode( $base64_data, true ); if ( false === $binary ) { return new WP_Error( 'invalid_image_data', __( 'Could not decode generated image data.', 'ai-content-generator-for-woocommerce' ) ); } $upload_dir = wp_upload_dir(); if ( ! empty( $upload_dir['error'] ) ) { return new WP_Error( 'upload_dir_error', $upload_dir['error'] ); } $extension = 'png'; if ( 'image/jpeg' === $mime_type ) { $extension = 'jpg'; } elseif ( 'image/webp' === $mime_type ) { $extension = 'webp'; } $filename = 'wtofe-ai-generated-' . wp_generate_uuid4() . '.' . $extension; $filepath = trailingslashit( $upload_dir['path'] ) . $filename; $written = file_put_contents( $filepath, $binary ); if ( false === $written ) { return new WP_Error( 'file_write_error', __( 'Could not save generated image file.', 'ai-content-generator-for-woocommerce' ) ); } return trailingslashit( $upload_dir['url'] ) . $filename; } }