in with tags (zero config, cache-safe). * - rewrite: HTML keeps original URLs; server rules serve variants per Accept header. * - swap: legacy mode — rewrites URLs in HTML to the variant (needs cache purge). * * @package ADee */ defined( 'ABSPATH' ) || exit; final class ADEE_Serve { /** * Per-request URL swap cache. * * @var array */ private $swap_cache = array(); /** * Constructor. Registers output filters. */ public function __construct() { add_filter( 'wp_get_attachment_image_src', array( $this, 'filter_image_src' ), 100, 3 ); add_filter( 'wp_get_attachment_url', array( $this, 'filter_url' ), 100, 2 ); add_filter( 'wp_calculate_image_srcset', array( $this, 'filter_srcset' ), 100, 5 ); add_filter( 'the_content', array( $this, 'filter_html' ), 999 ); add_filter( 'post_thumbnail_html', array( $this, 'filter_html' ), 999 ); add_filter( 'render_block', array( $this, 'filter_html' ), 999 ); } /** * Whether serving is enabled in the current request. * * @return bool */ public function enabled() { if ( ! ADEE_Plugin::get_setting( 'serve' ) ) { return false; } if ( is_feed() || wp_doing_cron() ) { return false; } if ( defined( 'WP_CLI' ) && WP_CLI ) { return false; } if ( is_admin() && ! wp_doing_ajax() && ! ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) { return false; } return true; } /** * Current serving mode. * * @return string picture|rewrite|swap */ public function mode() { $mode = ADEE_Plugin::get_setting( 'serve_mode' ); return in_array( $mode, array( 'picture', 'rewrite', 'swap' ), true ) ? $mode : 'picture'; } /** * Does the current browser accept a format via the Accept header? * * @param string $format avif|webp. * @return bool */ public function accepts( $format ) { $accept = isset( $_SERVER['HTTP_ACCEPT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) ) : ''; if ( ! $accept ) { return false; } return false !== stripos( $accept, 'image/' . $format ); } /** * Variant URL for an original image URL and format, when the file exists. * * @param string $url Original URL. * @param string $ext avif|webp. * @return string Variant URL or '' when no variant exists. */ public function variant_for( $url, $ext ) { if ( ! $url || ! preg_match( '/\.(jpe?g|png|gif)($|[?#])/i', $url ) ) { return ''; } $key = $ext . '|' . $url; if ( array_key_exists( $key, $this->swap_cache ) ) { return $this->swap_cache[ $key ]; } $this->swap_cache[ $key ] = ''; $upload = wp_get_upload_dir(); if ( empty( $upload['baseurl'] ) || 0 !== strpos( $url, $upload['baseurl'] ) ) { return ''; } // Split off query string / fragment. $path = $url; $suffix = ''; if ( preg_match( '/^([^?#]+)([?#].*)?$/', $url, $m ) ) { $path = $m[1]; $suffix = isset( $m[2] ) ? $m[2] : ''; } $basedir = rtrim( $upload['basedir'], '/' ); $rel = substr( $path, strlen( $upload['baseurl'] ) ); $fs = $basedir . $rel; $fs_new = preg_replace( '/\.(jpe?g|png|gif)$/i', '.' . $ext, $fs ); if ( $fs_new && file_exists( $fs_new ) ) { $new_url = preg_replace( '/\.(jpe?g|png|gif)$/i', '.' . $ext, $path ) . $suffix; $this->swap_cache[ $key ] = $new_url; return $new_url; } return ''; } /** * Swap an image URL to WebP/AVIF when a local variant exists (swap mode only). * * @param string $url Original URL. * @return string */ public function swap_url( $url ) { if ( ! $url ) { return $url; } $key = $url; if ( isset( $this->swap_cache[ $key ] ) ) { return $this->swap_cache[ $key ]; } $this->swap_cache[ $key ] = $url; // pessimistic default. if ( ! $this->enabled() || 'swap' !== $this->mode() ) { return $url; } $candidates = array(); if ( ADEE_Plugin::get_setting( 'prefer_avif' ) && $this->accepts( 'avif' ) ) { $candidates[] = 'avif'; } if ( $this->accepts( 'webp' ) ) { $candidates[] = 'webp'; } foreach ( $candidates as $ext ) { $new = $this->variant_for( $url, $ext ); if ( $new ) { $this->swap_cache[ $key ] = $new; return $new; } } return $url; } /** * Filter wp_get_attachment_url(). * * @param string $url URL. * @param int $attachment_id Attachment ID. * @return string */ public function filter_url( $url, $attachment_id ) { unset( $attachment_id ); return $this->swap_url( $url ); } /** * Filter wp_get_attachment_image_src(). * * @param array|false $image Image data. * @param int $attachment_id Attachment ID. * @param string|int $size Size. * @return array|false */ public function filter_image_src( $image, $attachment_id, $size ) { unset( $attachment_id, $size ); if ( is_array( $image ) && ! empty( $image[0] ) ) { $image[0] = $this->swap_url( $image[0] ); } return $image; } /** * Filter wp_calculate_image_srcset(). * * @param array $sources Srcset sources. * @param array $size_array Size array. * @param array $image_src Image src. * @param array $image_meta Image meta. * @param int $attachment_id Attachment ID. * @return array */ public function filter_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) { unset( $size_array, $image_src, $image_meta, $attachment_id ); if ( is_array( $sources ) ) { foreach ( $sources as $key => $source ) { if ( ! empty( $source['url'] ) ) { $sources[ $key ]['url'] = $this->swap_url( $source['url'] ); } } } return $sources; } /** * Rewrite src/srcset attributes (swap mode) or wrap (picture mode). * * @param string $html HTML markup. * @return string */ public function filter_html( $html ) { if ( ! $html || ! $this->enabled() ) { return $html; } $mode = $this->mode(); if ( 'picture' === $mode ) { return $this->picture_mode( $html ); } if ( 'swap' !== $mode ) { return $html; // rewrite mode: HTML stays untouched. } if ( false === stripos( $html, ' tags in with next-gen tags. * * @param string $html HTML markup. * @return string */ private function picture_mode( $html ) { if ( false === stripos( $html, ']*>/is', function ( $m ) use ( $self, $html ) { $tag = $m[0][0]; $offset = (int) $m[0][1]; // Skip images that already live inside a element. $before = substr( $html, 0, $offset ); $open = strrpos( $before, '' ); if ( false === $close || $close < $open ) { return $tag; } } return $self->build_picture( $tag ); }, $html, -1, $count, PREG_OFFSET_CAPTURE ); } /** * Build a wrapper for one tag. * * @param string $img Full tag. * @return string */ public function build_picture( $img ) { if ( ! preg_match( '/\ssrc\s*=\s*(["\'])(.*?)\1/is', $img, $sm ) ) { return $img; } $src = trim( $sm[2] ); if ( ! $src ) { return $img; } $srcset = ''; if ( preg_match( '/\ssrcset\s*=\s*(["\'])(.*?)\1/is', $img, $pm ) ) { $srcset = trim( $pm[2] ); } $sizes = ''; if ( preg_match( '/\ssizes\s*=\s*(["\'])(.*?)\1/is', $img, $zm ) ) { $sizes = trim( $zm[2] ); } $has_descriptors = ( $srcset && false !== strpos( $srcset, ' ' ) ); $order = ADEE_Plugin::get_setting( 'prefer_avif' ) ? array( 'avif', 'webp' ) : array( 'webp', 'avif' ); $sources = ''; foreach ( $order as $ext ) { $new_src = $this->variant_for( $src, $ext ); if ( ! $new_src ) { continue; } $srcset_out = $this->clean_attr( $new_src ); if ( $srcset ) { $parts = array(); foreach ( explode( ',', $srcset ) as $part ) { $part = trim( $part ); if ( '' === $part ) { continue; } $tokens = preg_split( '/\s+/', $part ); $u = $tokens[0]; $new_u = $this->variant_for( $u, $ext ); $tokens[0] = $new_u ? $new_u : $u; $parts[] = implode( ' ', $tokens ); } $srcset_out = $this->clean_attr( implode( ', ', $parts ) ); } $sources .= 'clean_attr( $sizes ) . '"'; } $sources .= '>'; } if ( '' === $sources ) { return $img; } return '' . $sources . $img . ''; } /** * Attribute-value safety: strip characters that could break out of quotes. * * @param string $value Raw value. * @return string */ private function clean_attr( $value ) { return str_replace( array( '"', "'", '\\', '<', '>' ), '', $value ); } /** * Callback for src/srcset attribute rewriting (swap mode). * * @param array $matches PCRE matches. * @return string */ private function attr_callback( $matches ) { $attr = strtolower( $matches[1] ); $quote = $matches[2]; $value = $matches[3]; if ( 'srcset' === $attr ) { $parts = explode( ',', $value ); foreach ( $parts as $i => $part ) { $tokens = preg_split( '/\s+/', trim( $part ) ); if ( ! empty( $tokens[0] ) ) { $tokens[0] = $this->swap_url( $tokens[0] ); } $parts[ $i ] = implode( ' ', $tokens ); } $value = implode( ', ', $parts ); } else { $value = $this->swap_url( $value ); } return $attr . '=' . $quote . $value . $quote; } }