'image/webp' ) ) ? 'image/webp' : 'image/jpeg'; } /** * Image extensions every supported provider accepts as-is. * * @return array Lower-case extensions without the leading dot. */ function aatg_supported_image_extensions() { /** * Filter the image formats sent to the provider as-is. * * OpenAI, Claude and DeepSeek accept PNG, JPEG, GIF and WebP. In the default * "embed" delivery mode other raster formats (AVIF, HEIC, …) are converted to * JPEG when the server can read them; SVG and unreadable files are skipped. * * @param array $extensions Lower-case extensions without the leading dot. */ return apply_filters( 'aatg_supported_image_extensions', array( 'png', 'jpg', 'jpeg', 'gif', 'webp' ) ); } /** * MIME types matching aatg_supported_image_extensions(). * * @return array */ function aatg_supported_image_mime_types() { $mimes = array(); foreach ( aatg_supported_image_extensions() as $ext ) { $type = wp_check_filetype( 'file.' . $ext ); if ( $type['type'] ) { $mimes[] = $type['type']; } } return array_values( array_unique( $mimes ) ); } /** * Verify that an image URL or path uses a format providers accept as-is. * * @param string $image_url URL or path of the image about to be sent. * @param int $post_ID Attachment ID (for context). * @return true|WP_Error True when supported, WP_Error otherwise. */ function aatg_check_supported_image_format( $image_url, $post_ID = 0 ) { $path = wp_parse_url( $image_url, PHP_URL_PATH ); $ext = $path ? strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ) : ''; if ( in_array( $ext, aatg_supported_image_extensions(), true ) ) { return true; } return aatg_unsupported_format_error( $ext ); } /** * @param string $ext File extension without the dot. * @return WP_Error */ function aatg_unsupported_format_error( $ext ) { return new WP_Error( 'aatg_unsupported_format', sprintf( /* translators: %s = file extension, e.g. ".svg" */ __( 'Skipped: unsupported image format "%s". Supported formats are PNG, JPEG, GIF and WebP (others are converted when the server can).', 'ai-auto-alt-text-generator' ), $ext ? '.' . $ext : __( 'unknown', 'ai-auto-alt-text-generator' ) ) ); } /** * Absolute path of the attachment file for a registered size. * * Uses $metadata when given (during upload it is not saved yet), and falls back * to the attached (possibly "-scaled") original when the size doesn't exist. * * @param int $post_ID Attachment ID. * @param string $size Image size name, or 'full'. * @param array|null $metadata Attachment metadata, or null to load it. * @return string|WP_Error */ function aatg_get_image_file_for_size( $post_ID, $size, $metadata = null ) { $original = get_attached_file( $post_ID ); if ( ! $original || ! file_exists( $original ) ) { return new WP_Error( 'aatg_missing_image', __( 'No image file is available for this attachment.', 'ai-auto-alt-text-generator' ) ); } if ( null === $metadata ) { $metadata = wp_get_attachment_metadata( $post_ID ); } if ( 'full' !== $size && is_array( $metadata ) && ! empty( $metadata['sizes'][ $size ]['file'] ) ) { $candidate = path_join( dirname( $original ), wp_basename( $metadata['sizes'][ $size ]['file'] ) ); if ( file_exists( $candidate ) ) { return $candidate; } } return $original; } /** * Public URL of the attachment for a registered size. * * @param int $post_ID Attachment ID. * @param string $size Image size name, or 'full'. * @param array|null $metadata Attachment metadata, or null to load it. * @return string|WP_Error */ function aatg_get_image_url_for_size( $post_ID, $size, $metadata = null ) { $url = wp_get_attachment_url( $post_ID ); if ( ! $url ) { return new WP_Error( 'aatg_missing_image', __( 'No image URL is available for this attachment.', 'ai-auto-alt-text-generator' ) ); } if ( null === $metadata ) { $metadata = wp_get_attachment_metadata( $post_ID ); } if ( 'full' !== $size && is_array( $metadata ) && ! empty( $metadata['sizes'][ $size ]['file'] ) ) { $url = trailingslashit( dirname( $url ) ) . wp_basename( $metadata['sizes'][ $size ]['file'] ); } return $url; } /** * Prepare an attachment image for a provider request. * * Embed mode (default) reads the chosen size from disk and returns base64, * downscaling past AATG_MAX_IMAGE_EDGE / AATG_MAX_IMAGE_BYTES and converting * formats providers can't read. URL mode returns the public URL as in 1.x. * * @param int $post_ID Attachment ID. * @param array|null $metadata Attachment metadata (pass it during upload). * @return array|WP_Error array( 'type' => 'base64', 'mime', 'data', 'width', 'height' ) * or array( 'type' => 'url', 'url' ). */ function aatg_prepare_image( $post_ID, $metadata = null ) { $post_mime = (string) get_post_mime_type( $post_ID ); if ( 0 !== strpos( $post_mime, 'image/' ) ) { return new WP_Error( 'aatg_not_image', __( 'Attachment is not an image.', 'ai-auto-alt-text-generator' ) ); } $size = (string) get_option( 'aatg_image_size', 'large' ); if ( 'url' === get_option( 'aatg_image_delivery', 'embed' ) ) { $url = aatg_get_image_url_for_size( $post_ID, $size, $metadata ); if ( is_wp_error( $url ) ) { return $url; } $check = aatg_check_supported_image_format( $url, $post_ID ); if ( is_wp_error( $check ) ) { return $check; } return array( 'type' => 'url', 'url' => $url, ); } $file = aatg_get_image_file_for_size( $post_ID, $size, $metadata ); if ( is_wp_error( $file ) ) { return $file; } $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) ); $mime = wp_get_image_mime( $file ); $dims = $mime ? aatg_image_dimensions( $file ) : false; if ( ! $mime || ! $dims ) { return aatg_unsupported_format_error( $ext ); } $convert = ! in_array( $mime, aatg_supported_image_mime_types(), true ); $resize = max( $dims[0], $dims[1] ) > AATG_MAX_IMAGE_EDGE || filesize( $file ) > aatg_max_image_bytes(); if ( $convert || $resize ) { return aatg_reencode_image( $file, $convert ? aatg_compact_mime() : $mime ); } return array( 'type' => 'base64', 'mime' => $mime, 'data' => base64_encode( file_get_contents( $file ) ), // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents 'width' => (int) $dims[0], 'height' => (int) $dims[1], ); } /** * Downscale and/or convert an image and return it as base64, under the size cap. * * Order: cap the long edge at AATG_MAX_IMAGE_EDGE; save in the target format; * if still over aatg_max_image_bytes(), lower the quality (lossless PNG/GIF * switch to WebP, which keeps transparency); finally scale down step by step. * * @param string $file Source path. * @param string $target_mime Output MIME type. * @return array|WP_Error Same shape as aatg_prepare_image() base64 results. */ function aatg_reencode_image( $file, $target_mime ) { $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) ); $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) ) { return aatg_unsupported_format_error( $ext ); } $size = $editor->get_size(); if ( max( $size['width'], $size['height'] ) > AATG_MAX_IMAGE_EDGE ) { $resized = $editor->resize( AATG_MAX_IMAGE_EDGE, AATG_MAX_IMAGE_EDGE, false ); if ( is_wp_error( $resized ) ) { return $resized; } } $limit = aatg_max_image_bytes(); $lossy = in_array( $target_mime, array( 'image/jpeg', 'image/webp' ), true ) ? $target_mime : aatg_compact_mime(); $attempts = array( array( $target_mime, 82 ) ); if ( $lossy !== $target_mime ) { $attempts[] = array( $lossy, 82 ); } $attempts[] = array( $lossy, 70 ); $attempts[] = array( $lossy, 55 ); foreach ( $attempts as $attempt ) { $editor->set_quality( $attempt[1] ); $saved = aatg_save_editor_to_string( $editor, $attempt[0] ); if ( is_wp_error( $saved ) ) { return $saved; } if ( strlen( $saved['bytes'] ) <= $limit ) { return aatg_base64_image( $saved ); } } // Still too heavy (very detailed or noisy images): shrink until it fits. for ( $step = 0; $step < 6 && strlen( $saved['bytes'] ) > $limit; $step++ ) { $size = $editor->get_size(); $resized = $editor->resize( max( 1, (int) ( $size['width'] * 0.75 ) ), max( 1, (int) ( $size['height'] * 0.75 ) ), false ); if ( is_wp_error( $resized ) ) { break; } $saved = aatg_save_editor_to_string( $editor, $lossy ); if ( is_wp_error( $saved ) ) { return $saved; } } return aatg_base64_image( $saved ); } /** * @param array $saved From aatg_save_editor_to_string(). * @return array aatg_prepare_image() base64 shape. */ function aatg_base64_image( array $saved ) { return array( 'type' => 'base64', 'mime' => $saved['mime'], 'data' => base64_encode( $saved['bytes'] ), 'width' => (int) $saved['width'], 'height' => (int) $saved['height'], ); } /** * Save an image editor's current image to a temp file and read it back. * * @param WP_Image_Editor $editor Editor. * @param string $mime Output MIME type. * @return array|WP_Error array( 'bytes', 'mime', 'width', 'height' ). */ function aatg_save_editor_to_string( $editor, $mime ) { $ext = aatg_extension_for_mime( $mime ); $path = trailingslashit( get_temp_dir() ) . 'aatg-' . wp_generate_password( 12, false ) . '.' . $ext; $saved = $editor->save( $path, $mime ); if ( is_wp_error( $saved ) ) { return $saved; } $bytes = file_get_contents( $saved['path'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents wp_delete_file( $saved['path'] ); if ( false === $bytes || '' === $bytes ) { return new WP_Error( 'aatg_image_encode_failed', __( 'Could not prepare the image for sending.', 'ai-auto-alt-text-generator' ) ); } return array( 'bytes' => $bytes, 'mime' => $saved['mime-type'], 'width' => $saved['width'], 'height' => $saved['height'], ); } /** * Image dimensions (wp_getimagesize() on WordPress 5.7+, which also reads WebP/AVIF). * * @param string $file Path. * @return array|false */ function aatg_image_dimensions( $file ) { if ( function_exists( 'wp_getimagesize' ) ) { return wp_getimagesize( $file ); } return @getimagesize( $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } /** * File extension for an image MIME type. * * @param string $mime MIME type. * @return string */ function aatg_extension_for_mime( $mime ) { if ( function_exists( 'wp_get_default_extension_for_mime_type' ) ) { $ext = wp_get_default_extension_for_mime_type( $mime ); if ( $ext ) { return $ext; } } $map = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp', ); return isset( $map[ $mime ] ) ? $map[ $mime ] : 'jpg'; }