]*>.*?|'; /** * Builds the rewriter. * * @param Settings $settings Plugin settings. * @param PictureRewriter $picture Picture markup. */ public function __construct( private readonly Settings $settings, private readonly PictureRewriter $picture ) {} /** * Adds the hooks. * * @return void */ public function register(): void { // Late, so a page cache that buffers earlier stores the rewritten page. add_action( 'template_redirect', array( $this, 'start' ), PHP_INT_MAX - 10 ); } /** * Starts buffering the page when whole-page delivery applies. * * @return void */ public function start(): void { if ( ! $this->applies() ) { return; } ob_start( array( $this, 'filter_buffer' ) ); } /** * Whether whole-page delivery runs on this request. * * @return bool */ public function applies(): bool { return $this->settings->flag( 'delivery_full_page' ) && ! is_embed() && ! is_robots() && ! is_trackback() && $this->picture->is_allowed_here(); } /** * Output buffer callback. * * @param string $buffer Page output. * @return string */ public function filter_buffer( $buffer ) { if ( ! $this->is_html_response() ) { return $buffer; } try { return $this->process( $buffer ); } catch ( Throwable $error ) { return $buffer; } } /** * Wraps eligible images in an HTML document or fragment. * * @param string $html HTML. * @return string */ public function process( string $html ): string { if ( false === stripos( $html, ']*>)#is'; if ( false === preg_match_all( $pattern, $html, $matches ) ) { return $html; } $paths = array(); foreach ( array_filter( $matches[2] ) as $tag ) { $path = $this->upload_path( $this->attribute( $tag, 'src' ) ); if ( null !== $path ) { $paths[ $path ] = true; } } if ( array() === $paths ) { return $html; } $ids = $this->attachments_for( array_keys( $paths ) ); if ( array() === $ids ) { return $html; } $result = preg_replace_callback( $pattern, function ( array $found ) use ( $ids ): string { if ( empty( $found[2] ) ) { return $found[0]; } $path = $this->upload_path( $this->attribute( $found[2], 'src' ) ); return null !== $path && isset( $ids[ $path ] ) ? $this->picture->rewrite( $found[2], $ids[ $path ] ) : $found[0]; }, $html ); return is_string( $result ) ? $result : $html; } /** * Whether the response is HTML. Headers are not available on the command line, which counts as HTML. * * @return bool */ private function is_html_response(): bool { foreach ( headers_list() as $header ) { if ( 0 === stripos( $header, 'content-type:' ) ) { return false !== stripos( $header, 'text/html' ) || false !== stripos( $header, 'application/xhtml+xml' ); } } return true; } /** * Reads one attribute of an img tag. * * @param string $tag Tag. * @param string $name Attribute. * @return string */ private function attribute( string $tag, string $name ): string { $processor = new \WP_HTML_Tag_Processor( $tag ); if ( ! $processor->next_tag( array( 'tag_name' => 'img' ) ) ) { return ''; } $value = $processor->get_attribute( $name ); return is_string( $value ) ? $value : ''; } /** * Turns an image URL on this site's uploads into a path relative to the uploads folder. * * Only this site's host, or a URL without one, counts. A copy on another host may not exist. * * @param string $url Image URL. * @return string|null */ private function upload_path( string $url ): ?string { if ( '' === $url || str_starts_with( $url, 'data:' ) ) { return null; } $uploads = wp_get_upload_dir(); $base = wp_parse_url( (string) $uploads['baseurl'] ); $parts = wp_parse_url( html_entity_decode( $url, ENT_QUOTES ) ); if ( ! is_array( $base ) || ! is_array( $parts ) || empty( $parts['path'] ) ) { return null; } if ( isset( $parts['host'] ) && strtolower( (string) $parts['host'] ) !== strtolower( (string) ( $base['host'] ?? '' ) ) ) { return null; } $prefix = trailingslashit( (string) ( $base['path'] ?? '' ) ); $path = rawurldecode( (string) $parts['path'] ); if ( ! str_starts_with( $path, $prefix ) || str_contains( $path, '..' ) ) { return null; } return substr( $path, strlen( $prefix ) ); } /** * Finds the attachment behind each file, including its generated sizes. * * @param string[] $paths Paths relative to the uploads folder. * @return array Path to attachment ID. */ private function attachments_for( array $paths ): array { global $wpdb; // A size such as photo-300x200.jpg belongs to photo.jpg, or to photo-scaled.jpg. $candidates = array(); foreach ( $paths as $path ) { $main = (string) preg_replace( '/-\d+x\d+(\.[a-z0-9]+)$/i', '$1', $path ); foreach ( array_unique( array( $path, $main, (string) preg_replace( '/(\.[a-z0-9]+)$/i', '-scaled$1', $main ) ) ) as $candidate ) { $candidates[ $candidate ][] = $path; } } $found = array(); foreach ( array_chunk( array_keys( $candidates ), 200 ) as $chunk ) { $placeholders = implode( ',', array_fill( 0, count( $chunk ), '%s' ) ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Placeholders are generated above. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value IN ({$placeholders})", $chunk ), ARRAY_A ); foreach ( is_array( $rows ) ? $rows : array() as $row ) { foreach ( $candidates[ (string) $row['meta_value'] ] ?? array() as $path ) { // An exact match wins over a guess from the name. if ( ! isset( $found[ $path ] ) || $row['meta_value'] === $path ) { $found[ $path ] = (int) $row['post_id']; } } } } return $found; } }