|null */ private ?array $cache = null; /** * Returns the cached results, detecting them on first use. * * @return array */ public function all(): array { if ( null !== $this->cache ) { return $this->cache; } $stored = get_option( $this->option_name() ); if ( is_array( $stored ) && ( $stored['fingerprint'] ?? '' ) === $this->fingerprint() ) { $this->cache = $stored; return $stored; } return $this->refresh(); } /** * Rechecks when PHP, WordPress or the plugin changed. * * Only runs where a slower request is acceptable, never on a front-end page view. * * @return void */ public function maybe_refresh(): void { if ( ! is_admin() && ! wp_doing_cron() && ! ( defined( 'WP_CLI' ) && WP_CLI ) ) { return; } $this->all(); } /** * Runs detection and stores the results. * * @return array */ public function refresh(): array { /** * Filters which image extensions PixelKeep may use. * * @param array{imagick: bool, gd: bool} $extensions Detected extensions. */ $extensions = apply_filters( 'pixelkeep_available_extensions', array( 'imagick' => extension_loaded( 'imagick' ) && class_exists( 'Imagick' ), 'gd' => extension_loaded( 'gd' ) && function_exists( 'gd_info' ), ) ); $results = array( 'fingerprint' => $this->fingerprint(), 'checked_at' => time(), 'imagick' => $extensions['imagick'] ? $this->detect_imagick() : $this->missing_engine(), 'gd' => $extensions['gd'] ? $this->detect_gd() : $this->missing_engine(), 'functions' => array( 'exec' => $this->function_enabled( 'exec' ), 'proc_open' => $this->function_enabled( 'proc_open' ), ), 'binaries' => $this->detect_binaries(), ); update_option( $this->option_name(), $results, true ); $this->cache = $results; return $results; } /** * Whether Imagick passed a real JPEG or PNG encode. * * @return bool */ public function imagick_usable(): bool { $encode = $this->all()['imagick']['encode']; return $encode['jpeg'] || $encode['png']; } /** * Whether GD passed a real JPEG or PNG encode. * * @return bool */ public function gd_usable(): bool { $encode = $this->all()['gd']['encode']; return $encode['jpeg'] || $encode['png']; } /** * Whether any image engine works. * * @return bool */ public function has_engine(): bool { return $this->imagick_usable() || $this->gd_usable(); } /** * Whether Imagick can convert between ICC profiles on this server. * * @return bool */ public function can_convert_profiles(): bool { return ! empty( $this->all()['imagick']['color_management'] ); } /** * Whether a specific engine can encode a format. * * @param string $engine `imagick` or `gd`. * @param string $format Lowercase format name. * @return bool */ public function can_encode( string $engine, string $format ): bool { return (bool) ( $this->all()[ $engine ]['encode'][ $format ] ?? false ); } /** * Option name for the current SAPI family. * * @return string */ private function option_name(): string { return self::OPTION_PREFIX . ( 'cli' === PHP_SAPI ? 'cli' : 'web' ); } /** * Changes whenever a recheck is required. * * @return string */ private function fingerprint(): string { return implode( '|', array( PHP_VERSION, get_bloginfo( 'version' ), PIXELKEEP_VERSION, extension_loaded( 'imagick' ) ? (string) phpversion( 'imagick' ) : 'no-imagick', extension_loaded( 'gd' ) && function_exists( 'gd_info' ) ? 'gd' : 'no-gd', ) ); } /** * Result shape for an engine that is not installed. * * @return array */ private function missing_engine(): array { return array( 'available' => false, 'version' => '', 'formats' => array(), 'encode' => array_fill_keys( self::FORMATS, false ), ); } /** * Probes Imagick. * * @return array */ private function detect_imagick(): array { $result = $this->missing_engine(); try { $version = Imagick::getVersion(); $result['available'] = true; $result['version'] = (string) $version['versionString']; $result['formats'] = array_values( array_intersect( array_map( 'strtoupper', self::FORMATS ), Imagick::queryFormats() ) ); $result['has_metric'] = defined( 'Imagick::METRIC_STRUCTURAL_SIMILARITY_ERROR' ) || defined( 'Imagick::METRIC_ROOTMEANSQUAREDERROR' ); $result['color_management'] = $this->imagick_color_test(); foreach ( self::FORMATS as $format ) { $result['encode'][ $format ] = in_array( strtoupper( $format ), $result['formats'], true ) && $this->imagick_encode_test( $format ); } } catch ( Throwable $e ) { $result['available'] = false; } return $result; } /** * Tests whether Imagick can really apply ICC profiles. * * Without the LCMS library, profileImage() returns true and leaves the pixels unchanged, so * only comparing the pixels shows whether it worked. * * @return bool */ private function imagick_color_test(): bool { try { $image = new Imagick(); $image->newImage( 2, 2, '#20c020' ); $image->setImageFormat( 'PNG' ); $image->setImageProfile( 'icc', IccProfile::wide_gamut() ); $before = $image->getImagePixelColor( 0, 0 )->getColor(); $image->profileImage( 'icc', IccProfile::srgb() ); $after = $image->getImagePixelColor( 0, 0 )->getColor(); $image->clear(); return $before['r'] !== $after['r'] || $before['g'] !== $after['g'] || $before['b'] !== $after['b']; } catch ( Throwable $e ) { return false; } } /** * Writes a 1×1 image with Imagick and verifies the file. * * @param string $format Lowercase format name. * @return bool */ private function imagick_encode_test( string $format ): bool { $file = $this->temp_file( $format ); try { $image = new Imagick(); $image->newImage( 1, 1, 'white' ); $image->setImageFormat( strtoupper( $format ) ); $image->writeImage( $file ); $image->clear(); return $this->file_has_signature( $file, $format ); } catch ( Throwable $e ) { return false; } finally { wp_delete_file( $file ); } } /** * Probes GD. * * @return array */ private function detect_gd(): array { $result = $this->missing_engine(); $info = gd_info(); $result['available'] = true; $result['version'] = (string) ( $info['GD Version'] ?? '' ); $writers = array( 'jpeg' => 'imagejpeg', 'png' => 'imagepng', 'gif' => 'imagegif', 'webp' => 'imagewebp', 'avif' => 'imageavif', ); foreach ( $writers as $format => $writer ) { if ( function_exists( $writer ) ) { $result['formats'][] = strtoupper( $format ); $result['encode'][ $format ] = $this->gd_encode_test( $format, $writer ); } } return $result; } /** * Writes a 1×1 image with GD and verifies the file. * * @param string $format Lowercase format name. * @param callable $writer GD writer function. * @return bool */ private function gd_encode_test( string $format, callable $writer ): bool { $file = $this->temp_file( $format ); try { $image = imagecreatetruecolor( 1, 1 ); if ( false === $image ) { return false; } // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A build without the codec warns; failure is the expected signal. @$writer( $image, $file ); return $this->file_has_signature( $file, $format ); } catch ( Throwable $e ) { return false; } finally { wp_delete_file( $file ); } } /** * Builds a temp path with the right extension. Imagick picks its coder from the extension. * * @param string $format Lowercase format name. * @return string */ private function temp_file( string $format ): string { return trailingslashit( get_temp_dir() ) . 'pixelkeep-probe-' . wp_generate_password( 8, false, false ) . '.' . $format; } /** * Checks that a file exists and starts with the format's magic bytes. * * @param string $file File to read. * @param string $format Lowercase format name. * @return bool */ private function file_has_signature( string $file, string $format ): bool { clearstatcache( true, $file ); if ( ! is_file( $file ) || 0 === (int) filesize( $file ) ) { return false; } $head = (string) file_get_contents( $file, false, null, 0, 16 ); switch ( $format ) { case 'jpeg': return str_starts_with( $head, "\xFF\xD8\xFF" ); case 'png': return str_starts_with( $head, "\x89PNG" ); case 'gif': return str_starts_with( $head, 'GIF8' ); case 'webp': return str_starts_with( $head, 'RIFF' ) && 'WEBP' === substr( $head, 8, 4 ); case 'avif': return 'ftyp' === substr( $head, 4, 4 ); } return false; } /** * Checks that a function exists and is not listed in disable_functions. * * @param string $name Function name. * @return bool */ private function function_enabled( string $name ): bool { if ( ! function_exists( $name ) ) { return false; } $disabled = array_map( 'trim', explode( ',', (string) ini_get( 'disable_functions' ) ) ); return ! in_array( $name, $disabled, true ); } /** * Finds optional binaries without running a shell. * * @return array Binary name to path, or null when not found. */ private function detect_binaries(): array { $found = array_fill_keys( self::BINARIES, null ); if ( ! $this->function_enabled( 'proc_open' ) && ! $this->function_enabled( 'exec' ) ) { return $found; } /** * Filters the extra folders searched for local programs. * * @param string[] $dirs Folders. */ $extra = (array) apply_filters( 'pixelkeep_binary_dirs', array( '/usr/bin', '/usr/local/bin', '/opt/homebrew/bin' ) ); $dirs = array_unique( array_merge( $extra, explode( PATH_SEPARATOR, (string) getenv( 'PATH' ) ) ) ); foreach ( self::BINARIES as $binary ) { foreach ( $dirs as $dir ) { $candidate = rtrim( (string) $dir, '/' ) . '/' . $binary; // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- open_basedir makes these checks warn on some hosts. if ( '' !== $dir && @is_file( $candidate ) && @is_executable( $candidate ) && $this->binary_runs( $candidate, $binary ) ) { $found[ $binary ] = $candidate; break; } } } return $found; } /** * Runs a program's version command, because a file can be present and still fail to start. * * @param string $path Program path. * @param string $binary Program name. * @return bool */ private function binary_runs( string $path, string $binary ): bool { $result = BinaryRunner::execute( array( $path, 'cwebp' === $binary ? '-version' : '--version' ), 5 ); return 0 === $result['code']; } }