base64 = $base64; $this->mime_type = $mime_type; } /** * @throws AiImageException */ public static function from_attachment( int $attachment_id ): self { $path = (string) get_attached_file( $attachment_id ); if ( '' === $path || ! file_exists( $path ) ) { throw new AiImageException( __( 'The image file was not found on the server.', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $mime_type = (string) get_post_mime_type( $attachment_id ); if ( ! in_array( $mime_type, self::ALLOWED_MIME_TYPES, true ) ) { throw new AiImageException( __( 'This image format is not supported by AI analysis (allowed: JPEG, PNG, WebP).', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $contents = self::downscaled_contents( $path, $mime_type ); if ( strlen( $contents ) > self::MAX_BYTES ) { throw new AiImageException( __( 'The image is too large for AI analysis (even after downscaling).', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } return new self( base64_encode( $contents ), $mime_type ); } /** * @throws AiImageException */ private static function downscaled_contents( string $path, string $mime_type ): string { $editor = wp_get_image_editor( $path ); if ( ! is_wp_error( $editor ) ) { $size = $editor->get_size(); if ( max( (int) ( $size['width'] ?? 0 ), (int) ( $size['height'] ?? 0 ) ) > self::MAX_EDGE ) { $editor->resize( self::MAX_EDGE, self::MAX_EDGE, false ); $saved = $editor->save( wp_tempnam( 'acez-seo-vision' ), $mime_type ); if ( ! is_wp_error( $saved ) && isset( $saved['path'] ) && is_string( $saved['path'] ) ) { $contents = file_get_contents( $saved['path'] ); wp_delete_file( $saved['path'] ); if ( false !== $contents ) { return $contents; } } } } // No editor available or the image is already small enough — send the // original file (the MAX_BYTES cap above still protects the request). $contents = file_get_contents( $path ); if ( false === $contents ) { throw new AiImageException( __( 'Failed to read the image file.', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } return $contents; } }