self::MAX_PIXELS ) { return false; } if ( function_exists( 'wp_raise_memory_limit' ) ) { wp_raise_memory_limit( 'image' ); } $limit = function_exists( 'wp_convert_hr_to_bytes' ) ? wp_convert_hr_to_bytes( (string) ini_get( 'memory_limit' ) ) : -1; if ( $limit <= 0 ) { return true; } // About 5 bytes per pixel for a true-colour GD image, plus the file read into memory. $need = $pixels * 5 + (int) @filesize( $path ) + 8 * MB_IN_BYTES; // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return memory_get_usage( true ) + $need < $limit; } /** * A small copy of an attachment on disk to scan instead of the full file: the smallest * generated size with the same shape (never a cropped one) that is at least $min px. * * @param int $attachment_id Attachment. * @param string $path Full-size file. * @param int $min Shortest acceptable longest side. * @return string The sub-size file, or the full file when there is none. */ public static function small_file( $attachment_id, $path, $min = 200 ) { $meta = wp_get_attachment_metadata( $attachment_id ); if ( ! is_array( $meta ) || empty( $meta['sizes'] ) || empty( $meta['width'] ) || empty( $meta['height'] ) ) { return $path; } $ratio = $meta['width'] / $meta['height']; $best = ''; $edge = 0; foreach ( (array) $meta['sizes'] as $sub ) { if ( empty( $sub['file'] ) || empty( $sub['width'] ) || empty( $sub['height'] ) ) { continue; } $long = max( (int) $sub['width'], (int) $sub['height'] ); if ( $long < $min || abs( ( $sub['width'] / $sub['height'] ) - $ratio ) / $ratio > 0.02 ) { continue; } $file = path_join( dirname( $path ), wp_basename( $sub['file'] ) ); if ( ( ! $best || $long < $edge ) && file_exists( $file ) ) { $best = $file; $edge = $long; } } return $best ? $best : $path; } /** * Load an image into GD with alpha kept, downscaled so the longest side is at most $max. * * @param string $path Image file. * @param int $max Longest side. * @return array|null array( image, w, h, has_alpha ) or null when GD cannot read it. */ public static function load_small( $path, $max = 200 ) { if ( ! function_exists( 'imagecreatefromstring' ) || ! is_string( $path ) || '' === $path || ! file_exists( $path ) ) { return null; } if ( ! self::fits_in_memory( $path ) ) { return null; } $bytes = @file_get_contents( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $image = $bytes ? @imagecreatefromstring( $bytes ) : false; // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( ! $image ) { return null; } if ( ! imageistruecolor( $image ) ) { imagepalettetotruecolor( $image ); } $w = imagesx( $image ); $h = imagesy( $image ); $scale = max( $w, $h ) > $max ? $max / max( $w, $h ) : 1; if ( $scale < 1 ) { $small = imagecreatetruecolor( max( 1, (int) round( $w * $scale ) ), max( 1, (int) round( $h * $scale ) ) ); imagealphablending( $small, false ); imagesavealpha( $small, true ); imagefill( $small, 0, 0, imagecolorallocatealpha( $small, 0, 0, 0, 127 ) ); imagecopyresampled( $small, $image, 0, 0, 0, 0, imagesx( $small ), imagesy( $small ), $w, $h ); self::free( $image ); $image = $small; } $w = imagesx( $image ); $h = imagesy( $image ); $has_alpha = self::has_alpha_pixels( $image, $w, $h ); return array( $image, $w, $h, $has_alpha ); } /** * Whether any pixel is at least partly transparent (sampled on a grid). * * @param resource|\GdImage $image Image. * @param int $w Width. * @param int $h Height. * @return bool */ private static function has_alpha_pixels( $image, $w, $h ) { $step = max( 1, (int) floor( min( $w, $h ) / 40 ) ); for ( $y = 0; $y < $h; $y += $step ) { for ( $x = 0; $x < $w; $x += $step ) { if ( ( ( imagecolorat( $image, $x, $y ) >> 24 ) & 0x7F ) > 0 ) { return true; } } } return false; } /** * RGBA of a pixel. * * @param resource|\GdImage $image Image. * @param int $x X. * @param int $y Y. * @return int[] array( r, g, b, a ) with GD alpha 0 (opaque) to 127 (clear). */ private static function rgba( $image, $x, $y ) { $c = imagecolorat( $image, $x, $y ); return array( ( $c >> 16 ) & 0xFF, ( $c >> 8 ) & 0xFF, $c & 0xFF, ( $c >> 24 ) & 0x7F ); } /** * Median of a list of numbers. * * @param float[] $values Values. * @return float */ private static function median( array $values ) { if ( ! $values ) { return 0.0; } sort( $values ); $n = count( $values ); $m = (int) floor( $n / 2 ); return ( $n % 2 ) ? (float) $values[ $m ] : ( $values[ $m - 1 ] + $values[ $m ] ) / 2; } /** * Eight background samples: the four edge strips (5% of the short side, at least 2 px) * and the four 8% corner squares. Each gives the median RGBA, the RGB standard * deviation, and its pixels' alpha values. * * @param resource|\GdImage $image Image. * @param int $w Width. * @param int $h Height. * @return array[] Each: rgb (int[3]), alpha (int), std (float), alphas (int[]), kind (strip|corner). */ public static function edge_samples( $image, $w, $h ) { $strip = max( 2, (int) round( min( $w, $h ) * 0.05 ) ); $corner = max( 2, (int) round( min( $w, $h ) * 0.08 ) ); $boxes = array( array( 0, 0, $w, $strip, 'strip' ), array( 0, $h - $strip, $w, $strip, 'strip' ), array( 0, 0, $strip, $h, 'strip' ), array( $w - $strip, 0, $strip, $h, 'strip' ), array( 0, 0, $corner, $corner, 'corner' ), array( $w - $corner, 0, $corner, $corner, 'corner' ), array( 0, $h - $corner, $corner, $corner, 'corner' ), array( $w - $corner, $h - $corner, $corner, $corner, 'corner' ), ); $out = array(); foreach ( $boxes as $box ) { list( $x0, $y0, $bw, $bh, $kind ) = $box; $r = array(); $g = array(); $b = array(); $a = array(); for ( $y = max( 0, $y0 ); $y < min( $h, $y0 + $bh ); $y++ ) { for ( $x = max( 0, $x0 ); $x < min( $w, $x0 + $bw ); $x++ ) { $px = self::rgba( $image, $x, $y ); $r[] = $px[0]; $g[] = $px[1]; $b[] = $px[2]; $a[] = $px[3]; } } $n = max( 1, count( $r ) ); $std = 0.0; foreach ( array( $r, $g, $b ) as $channel ) { $mean = array_sum( $channel ) / $n; $var = 0.0; foreach ( $channel as $v ) { $var += ( $v - $mean ) * ( $v - $mean ); } $std = max( $std, sqrt( $var / $n ) ); } $out[] = array( 'rgb' => array( (int) round( self::median( $r ) ), (int) round( self::median( $g ) ), (int) round( self::median( $b ) ) ), 'alpha' => (int) round( self::median( $a ) ), 'std' => $std, 'alphas' => $a, 'kind' => $kind, ); } return $out; } /** * Name a background colour. * * @param int[] $rgb array( r, g, b ). * @return string white, light_grey, beige or other. */ public static function classify_rgb( array $rgb ) { list( $r, $g, $b ) = array_map( 'intval', $rgb ); $spread = max( $r, $g, $b ) - min( $r, $g, $b ); if ( $r >= 240 && $g >= 240 && $b >= 240 && $spread <= 10 ) { return 'white'; } if ( min( $r, $g, $b ) >= 200 && max( $r, $g, $b ) <= 239 && $spread <= 10 ) { return 'light_grey'; } if ( $r >= 215 && $r > $g && $g > $b && ( $r - $b ) >= 15 && ( $r - $b ) <= 60 && $b >= 170 ) { return 'beige'; } return 'other'; } /** * Distance between two colours. * * @param int[] $a RGB. * @param int[] $b RGB. * @return float */ public static function color_distance( array $a, array $b ) { return sqrt( pow( $a[0] - $b[0], 2 ) + pow( $a[1] - $b[1], 2 ) + pow( $a[2] - $b[2], 2 ) ); } /** * Hex string of an RGB triple. * * @param int[] $rgb RGB. * @return string #rrggbb */ public static function hex( array $rgb ) { return sprintf( '#%02x%02x%02x', $rgb[0], $rgb[1], $rgb[2] ); } /** * Read the background of an image file from its edges and corners. * * @param string $path Image file. * @return array|null background (white|light_grey|beige|other|transparent, or unknown with * too_large when the file is too big to decode), hex, confidence * (confident|check), transparent (bool), alpha_share (0..1); null when unreadable. */ public static function background_scan( $path ) { if ( is_string( $path ) && '' !== $path && file_exists( $path ) && ! self::fits_in_memory( $path ) ) { // Too big to decode safely: ask for a look instead of risking a fatal error. return array( 'background' => 'unknown', 'hex' => '', 'confidence' => 'check', 'transparent' => false, 'alpha_share' => 0, 'too_large' => true, ); } $loaded = self::load_small( $path, 200 ); if ( ! $loaded ) { return null; } list( $image, $w, $h, $has_alpha ) = $loaded; $samples = self::edge_samples( $image, $w, $h ); self::free( $image ); $clear = 0; $total = 0; foreach ( $samples as $s ) { foreach ( $s['alphas'] as $a ) { $total++; if ( $a >= 100 ) { $clear++; } } } $alpha_share = $total ? $clear / $total : 0.0; $transparent = $has_alpha && $alpha_share >= 0.5; $all_rgb = array( array(), array(), array() ); foreach ( $samples as $s ) { for ( $i = 0; $i < 3; $i++ ) { $all_rgb[ $i ][] = $s['rgb'][ $i ]; } } $median = array( (int) round( self::median( $all_rgb[0] ) ), (int) round( self::median( $all_rgb[1] ) ), (int) round( self::median( $all_rgb[2] ) ) ); if ( $transparent ) { return array( 'background' => 'transparent', 'hex' => '', 'confidence' => 'confident', 'transparent' => true, 'alpha_share' => round( $alpha_share, 3 ), ); } $classes = array(); foreach ( $samples as $s ) { $classes[] = self::classify_rgb( $s['rgb'] ); } $counts = array_count_values( $classes ); arsort( $counts ); $top = (string) key( $counts ); $agree = (int) current( $counts ); $max_std = 0.0; $max_dist = 0.0; foreach ( $samples as $i => $s ) { if ( 'strip' === $s['kind'] ) { $max_std = max( $max_std, $s['std'] ); } foreach ( $samples as $j => $t ) { if ( $j > $i ) { $max_dist = max( $max_dist, self::color_distance( $s['rgb'], $t['rgb'] ) ); } } } $confident = $agree >= 7 && $max_std <= 18 && $max_dist <= 24; return array( 'background' => $top, 'hex' => self::hex( $median ), 'confidence' => $confident ? 'confident' : 'check', 'transparent' => false, 'alpha_share' => round( $alpha_share, 3 ), ); } /** * Whether a model drew a fake transparency checkerboard instead of a real background. * * Reads one line inside each edge (about 3% in) of a copy at most 512 px wide: the * line must alternate between two light, unsaturated greys in steady steps, on at * least two edges, where the image has no real transparency. Only the edges are * read, so a chequered product in the middle of the frame is not judged. * * @param string $path Image file. * @return bool */ public static function looks_like_checkerboard( $path ) { $loaded = self::load_small( $path, 512 ); if ( ! $loaded ) { return false; } list( $image, $w, $h ) = $loaded; $depth = max( 1, (int) round( min( $w, $h ) * 0.03 ) ); $lines = array( array( 'h', $depth ), array( 'h', $h - 1 - $depth ), array( 'v', $depth ), array( 'v', $w - 1 - $depth ), ); $hits = 0; foreach ( $lines as $line ) { list( $dir, $at ) = $line; $lum = array(); $sat = 0.0; $alpha = 0; $len = 'h' === $dir ? $w : $h; for ( $i = 0; $i < $len; $i++ ) { $px = 'h' === $dir ? self::rgba( $image, $i, $at ) : self::rgba( $image, $at, $i ); $lum[] = 0.299 * $px[0] + 0.587 * $px[1] + 0.114 * $px[2]; $sat += max( $px[0], $px[1], $px[2] ) - min( $px[0], $px[1], $px[2] ); $alpha += ( $px[3] >= 100 ) ? 1 : 0; } if ( $alpha > $len * 0.2 || ( $sat / max( 1, $len ) ) >= 12 ) { continue; } if ( self::line_is_checker( $lum ) ) { $hits++; } } self::free( $image ); return $hits >= 2; } /** * Whether a luminance line alternates between two levels in steady steps. * * @param float[] $lum Luminance values. * @return bool */ private static function line_is_checker( array $lum ) { $n = count( $lum ); if ( $n < 12 ) { return false; } $mean = array_sum( $lum ) / $n; $low = array(); $high = array(); $level = array(); foreach ( $lum as $v ) { if ( $v >= $mean ) { $high[] = $v; $level[] = 1; } else { $low[] = $v; $level[] = 0; } } if ( ! $low || ! $high ) { return false; } $lo = self::median( $low ); $hi = self::median( $high ); if ( $lo <= 120 || $hi <= 120 || ( $hi - $lo ) < 15 || ( $hi - $lo ) > 90 ) { return false; } // Run lengths, ignoring the partial first and last runs. $runs = array(); $run = 1; for ( $i = 1; $i < $n; $i++ ) { if ( $level[ $i ] === $level[ $i - 1 ] ) { $run++; } else { $runs[] = $run; $run = 1; } } array_shift( $runs ); if ( count( $runs ) < 6 ) { return false; } $avg = array_sum( $runs ) / count( $runs ); if ( $avg < 2 || $avg > 64 ) { return false; } $var = 0.0; foreach ( $runs as $r ) { $var += ( $r - $avg ) * ( $r - $avg ); } $cv = sqrt( $var / count( $runs ) ) / $avg; return $cv < 0.35; } /** * Size, shape, format and background of an attachment. The background scan is kept on * the attachment until its file changes. * * @param int $attachment_id Attachment. * @return array|null width, height, ratio (w/h), format, scan; null when the file is missing. */ public static function facts( $attachment_id ) { $path = (string) get_attached_file( $attachment_id ); if ( '' === $path || ! file_exists( $path ) ) { return null; } $meta = wp_get_attachment_metadata( $attachment_id ); $width = is_array( $meta ) && ! empty( $meta['width'] ) ? (int) $meta['width'] : 0; $height = is_array( $meta ) && ! empty( $meta['height'] ) ? (int) $meta['height'] : 0; if ( ( ! $width || ! $height ) && function_exists( 'getimagesize' ) ) { $size = @getimagesize( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( $size ) { $width = (int) $size[0]; $height = (int) $size[1]; } } $mime = (string) get_post_mime_type( $attachment_id ); $map = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'image/gif' => 'gif', 'image/avif' => 'avif', 'image/svg+xml' => 'svg' ); $format = isset( $map[ $mime ] ) ? $map[ $mime ] : strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ); $sig = md5( $path . '|' . filesize( $path ) . '|' . filemtime( $path ) ); $kept = get_post_meta( $attachment_id, self::META_SCAN, true ); if ( is_array( $kept ) && isset( $kept['v'], $kept['sig'] ) && self::SCAN_VERSION === (int) $kept['v'] && $sig === $kept['sig'] && array_key_exists( 'r', $kept ) ) { $scan = $kept['r']; } else { // The signature follows the full file; a small copy of it is what gets decoded. $scan = 'svg' === $format ? null : self::background_scan( self::small_file( $attachment_id, $path ) ); if ( ! is_array( $scan ) || empty( $scan['too_large'] ) ) { update_post_meta( $attachment_id, self::META_SCAN, array( 'v' => self::SCAN_VERSION, 'sig' => $sig, 'r' => $scan ) ); } } return array( 'width' => $width, 'height' => $height, 'ratio' => $height ? round( $width / $height, 4 ) : 0, 'format' => $format, 'scan' => $scan, ); } }