$fetcher_seams Test seams forwarded to the fetcher: validator, http, transportCheck. * @return array{data:string,mime_type:string,size:int} * * @throws \RuntimeException When the image cannot be fetched or encoded. */ public static function fetchAndEncode( string $image_url, int $timeout = 15, array $fetcher_seams = [] ): array { $image_url = trim( $image_url ); if ( '' === $image_url ) { throw new \RuntimeException( esc_html__( 'Image URL is empty.', 'ai-product-tools' ) ); } if ( self::isDataUri( $image_url ) ) { return self::parseDataUri( $image_url ); } $sanitized_url = (string) preg_replace_callback( '/[^!-~]/', static function ( array $match ): string { return rawurlencode( $match[0] ); }, $image_url ); $scheme = parse_url( $sanitized_url, PHP_URL_SCHEME ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- Avoids LSP false positives for WP shims while only reading the scheme. if ( ! in_array( $scheme, [ 'http', 'https' ], true ) ) { throw new \RuntimeException( esc_html__( 'Vision image URL must use http or https.', 'ai-product-tools' ) ); } $local_file = self::resolveLocalUploadFile( $image_url ); if ( '' !== $local_file ) { $body = file_get_contents( $local_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local upload read avoids unsafe loopback HTTP requests. if ( false === $body || '' === $body ) { throw new \RuntimeException( esc_html__( 'Empty image body.', 'ai-product-tools' ) ); } $size = strlen( $body ); self::assertSupportedSize( $size ); return [ 'data' => base64_encode( $body ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode 'mime_type' => self::detectImageMime( $body ), 'size' => $size, ]; } if ( ! filter_var( $sanitized_url, FILTER_VALIDATE_URL ) ) { throw new \RuntimeException( esc_html__( 'Vision image URL is not allowed.', 'ai-product-tools' ) ); } $fetch_timeout = (int) \apply_filters( 'aipt_vision_fetch_timeout', $timeout ); if ( $fetch_timeout <= 0 ) { $fetch_timeout = $timeout; } $result = self::buildFetcher( $fetcher_seams )->fetch( $sanitized_url, [ 'timeout' => $fetch_timeout, 'allowMissingContentType' => true, 'sslVerify' => (bool) \apply_filters( 'aipt_vision_sslverify', true ), ] ); if ( ! $result['ok'] ) { throw new \RuntimeException( esc_html( self::fetchFailureMessage( $result ) ) ); } $body = $result['body']; if ( '' === $body ) { throw new \RuntimeException( esc_html__( 'Empty image body.', 'ai-product-tools' ) ); } $size = strlen( $body ); self::assertSupportedSize( $size ); return [ 'data' => base64_encode( $body ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode 'mime_type' => self::detectImageMime( $body ), 'size' => $size, ]; } /** * Build the fetcher for remote images. * * Magic bytes decide the real type later, so octet-stream is accepted: some CDNs serve images that way. * * @param array $seams Test seams: validator, http, transportCheck. * @return SafeUrlFetcher */ private static function buildFetcher( array $seams ): SafeUrlFetcher { return new SafeUrlFetcher( [ 'image/jpeg', 'image/jpg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif', 'image/webp', 'application/octet-stream', 'binary/octet-stream' ], [], self::MAX_IMAGE_BYTES, $seams['validator'] ?? null, $seams['http'] ?? null, $seams['transportCheck'] ?? null ); } /** * Turn a failed fetch result into a user-safe message. * * @param array $result Failed SafeUrlFetcher result. * @return string */ private static function fetchFailureMessage( array $result ): string { $code = (string) ( $result['errorCode'] ?? '' ); if ( 'http_error' === $code ) { return sprintf( /* translators: %d: HTTP status code. */ __( 'HTTP %d fetching image.', 'ai-product-tools' ), absint( $result['httpStatus'] ?? 0 ) ); } if ( 'transport_unavailable' === $code ) { return __( 'Remote images cannot be read because PHP on this server cannot use cURL. Images served from this site\'s uploads folder still work.', 'ai-product-tools' ); } if ( 'too_large' === $code ) { return __( 'Image too large (>20MB).', 'ai-product-tools' ); } return sprintf( /* translators: %s: reason the image could not be fetched. */ __( 'Failed to fetch image: %s', 'ai-product-tools' ), (string) ( $result['errorMessage'] ?? '' ) ); } /** * Determine whether a value is a base64 data URI. * * @param string $image_url Image URL value. * @return bool */ private static function isDataUri( string $image_url ): bool { return 0 === strpos( $image_url, 'data:image/' ); } /** * Resolve WordPress upload URLs to local files when possible. * * @param string $image_url Trimmed image URL, raw UTF-8 or percent-encoded. * @return string Local file path, or empty string when the URL is not a local upload. */ private static function resolveLocalUploadFile( string $image_url ): string { $uploads = \wp_upload_dir(); if ( ! is_array( $uploads ) || ! empty( $uploads['error'] ) ) { return ''; } $base_url = isset( $uploads['baseurl'] ) ? rtrim( (string) $uploads['baseurl'], '/' ) : ''; $base_dir = isset( $uploads['basedir'] ) ? rtrim( str_replace( '\\', '/', (string) $uploads['basedir'] ), '/' ) : ''; if ( '' === $base_url || '' === $base_dir || 0 !== strpos( $image_url, $base_url . '/' ) ) { return ''; } $relative = ltrim( substr( $image_url, strlen( $base_url ) ), '/' ); $relative = str_replace( '\\', '/', rawurldecode( $relative ) ); if ( '' === $relative || false !== strpos( $relative, "\0" ) || preg_match( '#(^|/)\.\.(/|$)#', $relative ) ) { return ''; } $file = $base_dir . '/' . $relative; if ( 0 !== strpos( $file, $base_dir . '/' ) || ! is_file( $file ) || ! is_readable( $file ) ) { return ''; } return $file; } /** * Parse an image data URI into provider-ready fields. * * @param string $data_uri Data URI. * @return array{data:string,mime_type:string,size:int} * * @throws \RuntimeException When the data URI is invalid. */ private static function parseDataUri( string $data_uri ): array { if ( ! preg_match( '/^data:(image\/(?:jpeg|png|gif|webp));base64,([A-Za-z0-9+\/=\r\n]+)$/', $data_uri, $matches ) ) { throw new \RuntimeException( esc_html__( 'Invalid image data URI.', 'ai-product-tools' ) ); } $base64 = preg_replace( '/\s+/', '', $matches[2] ); if ( ! is_string( $base64 ) || '' === $base64 ) { throw new \RuntimeException( esc_html__( 'Invalid image data URI.', 'ai-product-tools' ) ); } $binary = base64_decode( $base64, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode if ( false === $binary || '' === $binary ) { throw new \RuntimeException( esc_html__( 'Invalid image data URI.', 'ai-product-tools' ) ); } $size = strlen( $binary ); self::assertSupportedSize( $size ); return [ 'data' => $base64, 'mime_type' => self::detectImageMime( $binary ), 'size' => $size, ]; } /** * Ensure the image fits provider upload limits. * * @param int $size Image size in bytes. * @return void * * @throws \RuntimeException When the image is too large. */ private static function assertSupportedSize( int $size ): void { if ( $size > self::MAX_IMAGE_BYTES ) { throw new \RuntimeException( esc_html__( 'Image too large (>20MB).', 'ai-product-tools' ) ); } } /** * Detect image MIME type from binary headers. * * @param string $binary Image binary data. * @return string * * @throws \RuntimeException When the image signature is unsupported. */ private static function detectImageMime( string $binary ): string { $header = substr( $binary, 0, 12 ); if ( 0 === strpos( $header, "\xFF\xD8\xFF" ) ) { return 'image/jpeg'; } if ( 0 === strpos( $header, "\x89PNG\r\n\x1A\n" ) ) { return 'image/png'; } if ( 0 === strpos( $header, 'GIF87a' ) || 0 === strpos( $header, 'GIF89a' ) ) { return 'image/gif'; } if ( 'RIFF' === substr( $header, 0, 4 ) && 'WEBP' === substr( $header, 8, 4 ) ) { return 'image/webp'; } throw new \RuntimeException( esc_html__( 'Unsupported image type.', 'ai-product-tools' ) ); } }