PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.4.0
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.4.0
1.4.1 1.4.0 1.3.7 1.3.6 1.3.5 1.3.4 1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 All 35 releases
← All changes | includes/class-resource-hints-processor.php +829 -34 1.3.3 → 1.4.0 View file →
@@ -59,9 +59,9 @@
59 59
60 60 if ( ! empty( $opts['lcp_preload'] ) ) {
61 61 $count = max( 0, (int) ( $opts['lcp_image_count'] ?? 1 ) );
62 62 $exclusions = array_filter( array_map( 'strval', (array) ( $opts['lcp_exclusions'] ?? array() ) ) );
63 - [ $html, $preload ] = self::build_lcp_preload( $html, $count, $exclusions );
63 + [ $html, $preload ] = self::build_lcp_preload( $html, $count, $exclusions, (string) ( $opts['page_url'] ?? '' ) );
64 64 $hints .= $preload;
65 65 }
66 66
67 67 // The manual list runs AFTER the automatic pick so it can deduplicate
@@ -148,26 +148,37 @@
148 148 return $out;
149 149 }
150 150
151 151 /**
152 - * Strip core `loading="lazy"` and add `fetchpriority="high"` +
153 - * `decoding="async"` on every <img> whose tag matches one of the given
154 - * exclusion substrings. Mirrors what Lazy_Loader does for an excluded image
155 - * inside the_content, but page-wide so heroes outside it are covered too.
156 - * (FBS-83553 H2)
152 + * Strip core `loading="lazy"` and add `decoding="async"` on every <img>
153 + * whose tag matches one of the given exclusion substrings. Mirrors what
154 + * Lazy_Loader does for an excluded image inside the_content, but page-wide
155 + * so heroes outside it are covered too. (FBS-83553 H2)
157 156 *
157 + * Only the first visible match outside <footer>/<nav>/<aside> gets
158 + * `fetchpriority="high"`, and only when no image in the page holds it yet.
159 + * Every match used to get it, so a pattern naming the header and footer
160 + * logo, or a hero in a closed accordion, put several images at High. (#558)
161 + *
158 162 * @param string $html Full page HTML.
159 163 * @param string[] $exclusions Substring patterns identifying above-the-fold heroes.
160 164 */
161 165 private static function promote_excluded_images( string $html, array $exclusions ): string {
162 - return (string) preg_replace_callback(
163 - '#<img\b(?:"[^"]*"|\'[^\']*\'|[^>"\'])*>#i',
164 - static function ( array $m ) use ( $exclusions ) {
165 - $tag = $m[0];
166 + $img_re = '#<img\b(?:"[^"]*"|\'[^\']*\'|[^>"\'])*>#i';
167 + $claimed = (bool) preg_match( '#<img\b(?:"[^"]*"|\'[^\']*\'|[^>"\'])*?(?<![-\w])fetchpriority\s*=\s*["\']?high\b#i', $html );
168 + $skip = $claimed ? array() : array_merge( self::chrome_container_ranges( $html ), Lazy_Loader::hidden_ranges( $html ) );
169 +
170 + $result = preg_replace_callback(
171 + $img_re,
172 + static function ( array $m ) use ( $exclusions, &$claimed, $skip ) {
173 + [ $tag, $offset ] = $m[0];
166 174 foreach ( $exclusions as $needle ) {
167 175 if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
168 176 $tag = (string) preg_replace( '#\s*\bloading=(["\'])\s*lazy\s*\1#i', '', $tag );
169 - $tag = self::set_fetchpriority( $tag );
177 + if ( ! $claimed && ! self::offset_in_ranges( (int) $offset, $skip ) && ! Lazy_Loader::tag_is_hidden( $tag, 'img' ) ) {
178 + $tag = self::set_fetchpriority( $tag );
179 + $claimed = true;
180 + }
170 181 if ( ! preg_match( '#\bdecoding=#i', $tag ) ) {
171 182 $tag = (string) preg_replace( '#<img\b#i', '<img decoding="async"', $tag, 1 );
172 183 }
173 184 return $tag;
@@ -174,10 +185,15 @@
174 185 }
175 186 }
176 187 return $tag;
177 188 },
178 - $html
189 + $html,
190 + -1,
191 + $count,
192 + PREG_OFFSET_CAPTURE
179 193 );
194 +
195 + return is_string( $result ) ? $result : $html;
180 196 }
181 197
182 198 /**
183 199 * Build preconnect <link>s for detected font hosts + user hosts.
@@ -231,15 +247,57 @@
231 247 *
232 248 * @param string $html Page HTML.
233 249 * @param int $count How many top images to preload.
234 250 * @param string[] $exclusions Substring patterns that exempt an <img>.
251 + * @param string $page_url The page being served, for the candidate seam.
235 252 * @return array{0:string,1:string} [rewritten html, preload markup]
236 253 */
237 - private static function build_lcp_preload( string $html, int $count, array $exclusions ): array {
254 + private static function build_lcp_preload( string $html, int $count, array $exclusions, string $page_url = '' ): array {
238 255 if ( $count < 1 ) {
239 256 return array( $html, '' );
240 257 }
241 258
259 + /**
260 + * Supply the LCP preload candidate for this page instead of the
261 + * automatic pick.
262 + *
263 + * The automatic pick reads the served HTML, so it cannot see a hero set
264 + * as a background in an external stylesheet, and it skips an <img> that
265 + * WordPress core marked lazy. An extension that has measured the page in
266 + * a browser can answer instead. Return null to leave the automatic pick
267 + * in charge; return an array to replace it:
268 + *
269 + * - `url` (string) the image to preload; an empty string means the
270 + * page has no LCP image, so nothing is preloaded;
271 + * - `srcset` (string, optional) and `sizes` (string, optional), emitted
272 + * as `imagesrcset` / `imagesizes`;
273 + * - `kind` (string, optional) `img` or `background`, passed to the URL
274 + * filters below. An image no <img> on the page carries is a
275 + * background regardless;
276 + * - `media` (string, optional) a media query for the preload link.
277 + *
278 + * Or a list of up to three such arrays, each with its own `media`, when
279 + * phones and desktops paint different images: each device then preloads
280 + * its own. Any `media` (also on a single answer) sets the matched <img>s
281 + * to `loading="lazy"`, so a device never downloads the other one's hero.
282 + *
283 + * Anything else (an empty list, a URL that is not a string, a URL
284 + * esc_url() refuses, a relative URL such as `hero.png`, a `media` that
285 + * is not a string, over 200 characters or holding `<`, `>` or `"`) is
286 + * not understood, and the automatic pick runs.
287 + *
288 + * The `<img>` carrying that URL, if the page has one, gets
289 + * `fetchpriority="high"` and loses `loading="lazy"`. The URL filters
290 + * below (`xspeed_lcp_preload_url` and friends) still apply.
291 + *
292 + * @param array|null $candidate Null = no opinion.
293 + * @param string $page_url The page being served; empty outside a request.
294 + */
295 + $supplied = self::supplied_candidates( apply_filters( 'xspeed_lcp_preload_candidate', null, $page_url ) );
296 + if ( null !== $supplied ) {
297 + return self::build_supplied_preload( $html, $supplied );
298 + }
299 +
242 300 $preload = '';
243 301
244 302 // Snapshot of already-present preload markup, for idempotency: a second
245 303 // pass (e.g. cache-off ob_start over an already-processed body) must not
@@ -256,22 +314,21 @@
256 314 // one that matters, and the feature reported success either way. The
257 315 // marker list and size gate were heuristics layered on top of the
258 316 // wrong primitive rather than replacing it. (#96)
259 317 $candidates = array();
260 - $skip_ranges = self::chrome_container_ranges( $html );
318 + // Markup hidden on arrival (a closed <details>, `hidden`, inline
319 + // display:none) cannot paint as LCP either. Preloading the hero of a
320 + // closed accordion spent the page's one High fetch on it. (#558)
321 + $skip_ranges = array_merge( self::chrome_container_ranges( $html ), Lazy_Loader::hidden_ranges( $html ) );
322 + // <img> indexes that can't be the LCP however they are marked: chrome,
323 + // hidden, or a logo/icon. Only these give up a stray `high`. (#558)
324 + $ruled_out = array();
261 325 if ( preg_match_all( '#<img\b[^>]*>#i', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
262 326 foreach ( $matches[0] as $index => $match ) {
263 327 [ $tag, $offset ] = $match;
264 328
265 329 // Skip anything the user excluded.
266 - $excluded = false;
267 - foreach ( $exclusions as $needle ) {
268 - if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
269 - $excluded = true;
270 - break;
271 - }
272 - }
273 - if ( $excluded ) {
330 + if ( self::matches_any( $tag, $exclusions ) ) {
274 331 continue;
275 332 }
276 333
277 334 // An image inside <footer>/<nav>/<aside> is site chrome by
@@ -278,9 +335,10 @@
278 335 // construction — a footer brand strip or FAQ illustration can
279 336 // never be the LCP element, whatever size it declares. On the
280 337 // FBS-84576 repro these decoys outranked the real hero three
281 338 // times on one layout.
282 - if ( self::offset_in_ranges( $offset, $skip_ranges ) ) {
339 + if ( self::offset_in_ranges( $offset, $skip_ranges ) || Lazy_Loader::tag_is_hidden( $tag, 'img' ) ) {
340 + $ruled_out[ $index ] = true;
283 341 continue;
284 342 }
285 343
286 344 // An image the theme explicitly lazy-loads is never the
@@ -302,8 +360,9 @@
302 360
303 361 // Chrome markers / explicit opt-out / obviously-tiny images
304 362 // never compete. (FBS-83553 H1 "logo before hero".)
305 363 if ( self::looks_too_small( $tag ) ) {
364 + $ruled_out[ $index ] = true;
306 365 continue;
307 366 }
308 367
309 368 $candidates[] = array(
@@ -312,8 +371,9 @@
312 371 'srcset' => $srcset,
313 372 'sizes' => $sizes,
314 373 'score' => self::weighted_score( self::lcp_score( $tag, $srcset ), $tag, $index ),
315 374 'order' => $index,
375 + 'offset' => $offset,
316 376 );
317 377 }
318 378 }
319 379
@@ -328,9 +388,47 @@
328 388 foreach ( self::background_candidates( $html, $exclusions, $skip_ranges ) as $bg ) {
329 389 $candidates[] = $bg;
330 390 }
331 391
392 + // PASS 1c — <video poster="…">. A full-screen hero video paints its
393 + // poster first, and that first frame IS the LCP; measured on a live
394 + // page, a preloaded poster cut the LCP load delay from 1.5 s to 21 ms.
395 + foreach ( self::video_poster_candidates( $html, $exclusions, $skip_ranges ) as $vp ) {
396 + $candidates[] = $vp;
397 + }
398 +
399 + // PASS 1d — background rules in inline <style> blocks. Page builders
400 + // put the hero's background-image in generated per-post CSS printed
401 + // inline (Elementor's `.elementor-N .elementor-element-X` rules), not
402 + // in a style attribute — so PASS 1b never saw the element that
403 + // actually paints as LCP on five of seven measured sites. External
404 + // stylesheets stay out for the same reasons as before (#247): fetching
405 + // CSS from an output-buffer pass costs more than the preload saves.
406 + foreach ( self::style_block_candidates( $html, $exclusions, $skip_ranges ) as $sb ) {
407 + $candidates[] = $sb;
408 + }
409 +
410 + // A background video with no poster, ahead of every candidate, is the
411 + // hero. Nothing in its box is preloadable, and every image after it
412 + // sits lower on the page. Preloading the first of those spent the one
413 + // high-priority fetch on an image below the fold, ahead of the CSS.
414 + // Those images also give up a stray `high` from the lazy pass.
415 + $video_at = self::background_video_offset( $html, $skip_ranges );
416 + if ( null !== $video_at ) {
417 + foreach ( $candidates as $i => $c ) {
418 + if ( $c['offset'] > $video_at ) {
419 + if ( empty( $c['background'] ) ) {
420 + $ruled_out[ $c['order'] ] = true;
421 + }
422 + unset( $candidates[ $i ] );
423 + }
424 + }
425 + }
426 +
332 427 if ( empty( $candidates ) ) {
428 + if ( null !== $video_at ) {
429 + $html = self::demote_images( $html, $ruled_out );
430 + }
333 431 return array( $html, '' );
334 432 }
335 433
336 434 // Rank by score, biggest first. Document order breaks ties, so two
@@ -359,9 +457,9 @@
359 457 '#rel=["\']preload["\'][^>]*as=["\']image["\'][^>]*' . preg_quote( $w['src'], '#' ) . '#i',
360 458 $existing
361 459 );
362 460 if ( ! $already ) {
363 - $preload .= self::preload_link( $w['src'], $w['srcset'], $w['sizes'] );
461 + $preload .= self::preload_link( $w['src'], $w['srcset'], $w['sizes'], empty( $w['background'] ) ? 'img' : 'background' );
364 462 }
365 463 // Only <img> winners are promoted in PASS 2 — there is no
366 464 // fetchpriority/loading attribute to fix on a background element,
367 465 // and its `order` is offset past every <img> index precisely so it
@@ -374,14 +472,26 @@
374 472 // Rewrite only the winning tags. Counting occurrences rather than
375 473 // matching on tag text, because the same markup can legitimately
376 474 // appear more than once on a page and only the ranked instance should
377 475 // be promoted.
378 - $seen = -1;
379 - $html = preg_replace_callback(
476 + //
477 + // When an <img> wins, it is the page's one High image, so an image
478 + // that can't be the LCP (a logo, an icon, a hidden panel, chrome)
479 + // gives up any `high` it carries. That is usually the lazy pass handing
480 + // its slot to the first image in the_content. An image that merely scored
481 + // lower, or that the user kept out of the pick, keeps its hint: the
482 + // ranking can be wrong, and core or the theme may have named the real
483 + // hero. (#558)
484 + $demote = ! empty( $chosen ) || null !== $video_at ? $ruled_out : array();
485 + $seen = -1;
486 + $html = preg_replace_callback(
380 487 '#<img\b[^>]*>#i',
381 - static function ( array $m ) use ( &$seen, $chosen ) {
488 + static function ( array $m ) use ( &$seen, $chosen, $demote ) {
382 489 ++$seen;
383 490 if ( ! isset( $chosen[ $seen ] ) ) {
491 + if ( isset( $demote[ $seen ] ) && 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
492 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
493 + }
384 494 return $m[0];
385 495 }
386 496 // Add fetchpriority="high" AND remove any loading="lazy" the
387 497 // theme / WP core left on the LCP image. fetchpriority="high"
@@ -396,8 +506,56 @@
396 506 return array( (string) $html, $preload );
397 507 }
398 508
399 509 /**
510 + * Byte offset of the first visible background video with no poster, or
511 + * null when the page has none.
512 + *
513 + * @param string $html Full page HTML.
514 + * @param array<int,array{0:int,1:int}> $skip_ranges Chrome and hidden spans.
515 + */
516 + private static function background_video_offset( string $html, array $skip_ranges ): ?int {
517 + $body = stripos( $html, '<body' );
518 + if ( ! preg_match_all( '#<video\b[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE, false === $body ? 0 : $body ) ) {
519 + return null;
520 + }
521 + foreach ( $m[0] as [ $tag, $offset ] ) {
522 + if ( self::offset_in_ranges( $offset, $skip_ranges ) || Lazy_Loader::tag_is_hidden( $tag, 'video' ) ) {
523 + continue;
524 + }
525 + if ( Lazy_Loader::is_background_video_without_poster( $tag ) ) {
526 + return $offset;
527 + }
528 + }
529 + return null;
530 + }
531 +
532 + /**
533 + * Strip fetchpriority="high" from the <img> tags at the given indexes.
534 + *
535 + * @param string $html Page HTML.
536 + * @param array<int,bool> $indexes <img> indexes, in document order.
537 + */
538 + private static function demote_images( string $html, array $indexes ): string {
539 + if ( empty( $indexes ) ) {
540 + return $html;
541 + }
542 + $seen = -1;
543 + $out = preg_replace_callback(
544 + '#<img\b[^>]*>#i',
545 + static function ( array $m ) use ( &$seen, $indexes ) {
546 + ++$seen;
547 + if ( isset( $indexes[ $seen ] ) && 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
548 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
549 + }
550 + return $m[0];
551 + },
552 + $html
553 + );
554 + return null === $out ? $html : $out;
555 + }
556 +
557 + /**
400 558 * Collect CSS `background-image` heroes as LCP candidates.
401 559 *
402 560 * Only INLINE `style` attributes are read. A background declared in an
403 561 * external stylesheet is invisible here by design: resolving it would mean
@@ -469,8 +627,9 @@
469 627 'score' => (float) $area,
470 628 // Offset so a background never ties ahead of an <img> that
471 629 // appeared earlier in the document; ties still break on order.
472 630 'order' => 100000 + $index,
631 + 'offset' => $offset,
473 632 'background' => true,
474 633 );
475 634 }
476 635
@@ -477,8 +636,249 @@
477 636 return $found;
478 637 }
479 638
480 639 /**
640 + * Collect `<video poster="…">` first frames as LCP candidates.
641 + *
642 + * The poster is what the viewer sees until (and unless) the video plays —
643 + * on a background-video hero, delayed by the Lazy module, it is the ONLY
644 + * frame the initial paint has. Scored like a background: the element's
645 + * declared inline-style area, or the unknown-size floor, with the order
646 + * offset past every <img> so a poster never ties ahead of one.
647 + *
648 + * @param string $html Full page HTML.
649 + * @param string[] $exclusions Substring patterns the user excluded.
650 + * @param array<int,array{0:int,1:int}> $skip_ranges Byte ranges of chrome containers.
651 + * @return array<int,array{tag:string,src:string,srcset:string,sizes:string,score:float,order:int,background:bool}>
652 + */
653 + private static function video_poster_candidates( string $html, array $exclusions, array $skip_ranges ): array {
654 + if ( ! preg_match_all( '#<video\b[^>]*\bposter\s*=\s*(["\'])(.*?)\1[^>]*>#i', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
655 + return array();
656 + }
657 +
658 + $found = array();
659 + foreach ( $matches[0] as $index => $match ) {
660 + [ $tag, $offset ] = $match;
661 + $src = trim( html_entity_decode( $matches[2][ $index ][0], ENT_QUOTES ) );
662 + if ( '' === $src || 0 === stripos( $src, 'data:' ) ) {
663 + continue;
664 + }
665 + if ( self::offset_in_ranges( $offset, $skip_ranges ) ) {
666 + continue;
667 + }
668 + foreach ( $exclusions as $needle ) {
669 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
670 + continue 2;
671 + }
672 + }
673 + if ( self::looks_too_small( $tag ) ) {
674 + continue;
675 + }
676 +
677 + $area = self::style_area( self::attr( $tag, 'style' ) );
678 + if ( 0 === $area ) {
679 + $area = self::UNKNOWN_SIZE_SCORE;
680 + }
681 +
682 + $found[] = array(
683 + 'tag' => $tag,
684 + 'src' => $src,
685 + 'srcset' => '',
686 + 'sizes' => '',
687 + 'score' => (float) $area,
688 + 'order' => 100000 + $index,
689 + 'offset' => $offset,
690 + 'background' => true,
691 + );
692 + }
693 +
694 + return $found;
695 + }
696 +
697 + /**
698 + * How many <style>-block background rules are considered per page. The
699 + * scan is linear, but each rule costs one class-lookup pass over the
700 + * body, so a pathological page (thousands of generated rules) is capped
701 + * rather than trusted.
702 + */
703 + private const STYLE_RULE_BUDGET = 40;
704 +
705 + /**
706 + * Collect background-image rules from inline <style> blocks whose
707 + * selector matches an element in the body.
708 + *
709 + * The match is deliberately narrow: the rule's RIGHTMOST simple selector
710 + * must carry a class or id, and the first element in the body bearing it
711 + * (outside chrome containers) is taken as the painted element. Rules
712 + * inside @media (or any other at-rule block) are skipped — a desktop-only
713 + * background preloaded on mobile is a wasted high-priority fetch, and the
714 + * markup gives no viewport to resolve the query against.
715 + *
716 + * @param string $html Full page HTML.
717 + * @param string[] $exclusions Substring patterns the user excluded.
718 + * @param array<int,array{0:int,1:int}> $skip_ranges Byte ranges of chrome containers.
719 + * @return array<int,array{tag:string,src:string,srcset:string,sizes:string,score:float,order:int,background:bool}>
720 + */
721 + private static function style_block_candidates( string $html, array $exclusions, array $skip_ranges ): array {
722 + if ( ! preg_match_all( '#<style\b[^>]*>(.*?)</style\s*>#is', $html, $blocks ) ) {
723 + return array();
724 + }
725 +
726 + $found = array();
727 + $budget = self::STYLE_RULE_BUDGET;
728 + foreach ( $blocks[1] as $css ) {
729 + if ( $budget <= 0 ) {
730 + break;
731 + }
732 + $css = self::strip_at_rule_blocks( $css );
733 + if ( false === stripos( $css, 'url(' ) ) {
734 + continue;
735 + }
736 + // One flat rule at a time: selector list up to '{', body to '}'.
737 + if ( ! preg_match_all( '#(?:^|})\s*([^{}]{1,512})\{([^{}]*)\}#s', $css, $rules, PREG_SET_ORDER ) ) {
738 + continue;
739 + }
740 + foreach ( $rules as $rule ) {
741 + if ( $budget <= 0 ) {
742 + break 2;
743 + }
744 + if ( false === stripos( $rule[2], 'url(' ) ) {
745 + continue;
746 + }
747 + $src = self::background_url( $rule[2] );
748 + if ( '' === $src ) {
749 + continue;
750 + }
751 + --$budget;
752 + // First selector of the list, rightmost compound of it.
753 + $selector = trim( (string) strtok( $rule[1], ',' ) );
754 + $parts = preg_split( '#[\s>+~]+#', $selector );
755 + $last = (string) end( $parts );
756 + // The last class or id token of that compound. Pseudo-classes
757 + // (:hover, ::before) mean the background is not the initial
758 + // paint, so they disqualify the rule.
759 + if ( false !== strpos( $last, ':' ) ) {
760 + continue;
761 + }
762 + if ( ! preg_match( '#([.\#])([-\w]+)$#', $last, $tok ) ) {
763 + continue;
764 + }
765 + $el = '.' === $tok[1]
766 + ? self::first_element_with_class( $html, $tok[2], $skip_ranges )
767 + : self::first_element_with_id( $html, $tok[2], $skip_ranges );
768 + if ( null === $el ) {
769 + continue;
770 + }
771 + [ $tag, $offset ] = $el;
772 + foreach ( $exclusions as $needle ) {
773 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
774 + continue 2;
775 + }
776 + }
777 + if ( self::looks_too_small( $tag ) ) {
778 + continue;
779 + }
780 + $area = self::style_area( self::attr( $tag, 'style' ) );
781 + if ( 0 === $area ) {
782 + $area = self::UNKNOWN_SIZE_SCORE;
783 + }
784 + $found[] = array(
785 + 'tag' => $tag,
786 + 'src' => $src,
787 + 'srcset' => '',
788 + 'sizes' => '',
789 + 'score' => (float) $area,
790 + // Offset past the inline-style backgrounds: a rule-matched
791 + // background is one inference step less certain, so it must
792 + // never tie ahead of one read straight off the element.
793 + 'order' => 200000 + $offset,
794 + 'offset' => $offset,
795 + 'background' => true,
796 + );
797 + }
798 + }
799 +
800 + return $found;
801 + }
802 +
803 + /**
804 + * CSS with every at-rule BLOCK (@media, @supports, @container, …) removed,
805 + * by brace depth — a regex cannot pair nested braces. Flat at-rules
806 + * (@import, @charset) have no block and pass through harmlessly.
807 + */
808 + private static function strip_at_rule_blocks( string $css ): string {
809 + $out = '';
810 + $len = strlen( $css );
811 + $i = 0;
812 + while ( $i < $len ) {
813 + $at = strpos( $css, '@', $i );
814 + if ( false === $at ) {
815 + return $out . substr( $css, $i );
816 + }
817 + $brace = strpos( $css, '{', $at );
818 + $semi = strpos( $css, ';', $at );
819 + $out .= substr( $css, $i, $at - $i );
820 + if ( false === $brace || ( false !== $semi && $semi < $brace ) ) {
821 + // Flat at-rule — skip to its semicolon (or end).
822 + $i = false === $semi ? $len : $semi + 1;
823 + continue;
824 + }
825 + // Block at-rule — skip to its matching close brace.
826 + $depth = 1;
827 + $i = $brace + 1;
828 + while ( $i < $len && $depth > 0 ) {
829 + $c = $css[ $i ];
830 + if ( '{' === $c ) {
831 + ++$depth;
832 + } elseif ( '}' === $c ) {
833 + --$depth;
834 + }
835 + ++$i;
836 + }
837 + }
838 + return $out;
839 + }
840 +
841 + /**
842 + * The first element in the BODY carrying $class (outside chrome ranges),
843 + * as [tag, offset], or null. Body-only, so a head <meta> can never match
844 + * and a hit's offset is comparable with the chrome ranges.
845 + *
846 + * @return array{0:string,1:int}|null
847 + */
848 + private static function first_element_with_class( string $html, string $class, array $skip_ranges ): ?array {
849 + $body = stripos( $html, '<body' );
850 + $from = false === $body ? 0 : $body;
851 + if ( ! preg_match_all( '#<[a-z][^>]*\bclass\s*=\s*(["\'])[^"\']*(?<![-\w])' . preg_quote( $class, '#' ) . '(?![-\w])[^"\']*\1[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE, $from ) ) {
852 + return null;
853 + }
854 + foreach ( $m[0] as $match ) {
855 + if ( ! self::offset_in_ranges( $match[1], $skip_ranges ) ) {
856 + return array( $match[0], $match[1] );
857 + }
858 + }
859 + return null;
860 + }
861 +
862 + /**
863 + * The first element carrying id="$id" (outside chrome ranges), as
864 + * [tag, offset], or null.
865 + *
866 + * @return array{0:string,1:int}|null
867 + */
868 + private static function first_element_with_id( string $html, string $id, array $skip_ranges ): ?array {
869 + $body = stripos( $html, '<body' );
870 + $from = false === $body ? 0 : $body;
871 + if ( ! preg_match( '#<[a-z][^>]*\bid\s*=\s*(["\'])' . preg_quote( $id, '#' ) . '\1[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE, $from ) ) {
872 + return null;
873 + }
874 + if ( self::offset_in_ranges( $m[0][1], $skip_ranges ) ) {
875 + return null;
876 + }
877 + return array( $m[0][0], $m[0][1] );
878 + }
879 +
880 + /**
481 881 * Pull a real image URL out of a `background`/`background-image` declaration.
482 882 *
483 883 * Returns '' for anything with nothing to fetch: a gradient (which is a
484 884 * background-image but not a resource), a data: URI, or `none`.
@@ -669,12 +1069,29 @@
669 1069 }
670 1070 return $ranges;
671 1071 }
672 1072
1073 + /**
1074 + * Does a tag contain any of the given substring patterns?
1075 + *
1076 + * @param string[] $patterns
1077 + */
1078 + private static function matches_any( string $tag, array $patterns ): bool {
1079 + foreach ( $patterns as $needle ) {
1080 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
1081 + return true;
1082 + }
1083 + }
1084 + return false;
1085 + }
1086 +
673 1087 /** Does a byte offset fall inside any of the given [start, end] ranges? */
674 1088 private static function offset_in_ranges( int $offset, array $ranges ): bool {
675 1089 foreach ( $ranges as $range ) {
676 - if ( $offset > $range[0] && $offset < $range[1] ) {
1090 + // >= on the start: a closed <details> span from
1091 + // Lazy_Loader::hidden_ranges() opens right at the first image
1092 + // after its <summary>.
1093 + if ( $offset >= $range[0] && $offset < $range[1] ) {
677 1094 return true;
678 1095 }
679 1096 }
680 1097 return false;
@@ -731,9 +1148,9 @@
731 1148 * resource goes un-preloaded). By filtering the URL, a webp/avif layer can
732 1149 * redirect the preload to the format it will actually serve, WITHOUT Free
733 1150 * knowing that layer exists. (FBS-83553 H3)
734 1151 */
735 - private static function preload_link( string $src, string $srcset, string $sizes ): string {
1152 + private static function preload_link( string $src, string $srcset, string $sizes, string $kind = 'img', string $media = '' ): string {
736 1153 // Resolve the `type` from the ORIGINAL image URL (before rewriting), so a
737 1154 // negotiating layer can key off the source .jpg/.png — after rewriting,
738 1155 // the URL is already a .webp and the derivation would no-op.
739 1156 $original = $src;
@@ -744,20 +1161,28 @@
744 1161 * even though the markup is baked into a shared cache file.
745 1162 *
746 1163 * @param string $type Defaults to '' (no type attribute).
747 1164 * @param string $src The ORIGINAL (pre-rewrite) preload URL.
1165 + * @param string $kind `img` for an <img>, `background` for a CSS
1166 + * background or a video poster. Only an <img> can be
1167 + * wrapped in <picture>; a background is requested by
1168 + * the URL its stylesheet names.
748 1169 */
749 - $type = (string) apply_filters( 'xspeed_lcp_preload_type', '', $original );
1170 + $type = (string) apply_filters( 'xspeed_lcp_preload_type', '', $original, $kind );
750 1171 /**
751 1172 * Filter the LCP preload href. Return a modern-format sibling (webp/avif)
752 1173 * when one will actually be served for this image.
753 1174 *
754 - * @param string $src The original image URL chosen for preload.
1175 + * @param string $src The original image URL chosen for preload.
1176 + * @param string $kind `img` or `background`, as for xspeed_lcp_preload_type.
755 1177 */
756 - $src = (string) apply_filters( 'xspeed_lcp_preload_url', $src );
1178 + $src = (string) apply_filters( 'xspeed_lcp_preload_url', $src, $kind );
757 1179 if ( '' !== $srcset ) {
758 - /** @param string $srcset The original srcset chosen for preload. */
759 - $srcset = (string) apply_filters( 'xspeed_lcp_preload_srcset', $srcset );
1180 + /**
1181 + * @param string $srcset The original srcset chosen for preload.
1182 + * @param string $kind `img` or `background`.
1183 + */
1184 + $srcset = (string) apply_filters( 'xspeed_lcp_preload_srcset', $srcset, $kind );
760 1185 }
761 1186
762 1187 $attrs = sprintf( 'href="%s"', esc_url( $src ) );
763 1188
@@ -773,8 +1198,12 @@
773 1198 if ( '' !== $type ) {
774 1199 $attrs .= sprintf( ' type="%s"', esc_attr( $type ) );
775 1200 }
776 1201
1202 + if ( '' !== $media ) {
1203 + $attrs .= sprintf( ' media="%s"', esc_attr( $media ) );
1204 + }
1205 +
777 1206 return sprintf( '<link rel="preload" as="image" %s fetchpriority="high">' . "\n", $attrs );
778 1207 }
779 1208
780 1209 /**
@@ -879,9 +1308,226 @@
879 1308 }
880 1309 return (int) $w <= self::MIN_LCP_DIMENSION && (int) $h <= self::MIN_LCP_DIMENSION;
881 1310 }
882 1311
1312 + /** Most candidates one answer may carry (one per device class). */
1313 + private const MAX_SUPPLIED_CANDIDATES = 3;
1314 +
883 1315 /**
1316 + * The filter's answer as a list of well-formed candidates, or null when
1317 + * it is no answer or not one this understands (then the automatic pick
1318 + * runs). An empty list means "this page has no LCP image".
1319 + *
1320 + * @param mixed $answer What `xspeed_lcp_preload_candidate` returned.
1321 + * @return array<int,array{url:string,srcset:string,sizes:string,kind:string,media:string}>|null
1322 + */
1323 + private static function supplied_candidates( $answer ): ?array {
1324 + if ( ! is_array( $answer ) || empty( $answer ) ) {
1325 + return null;
1326 + }
1327 + $items = array_key_exists( 'url', $answer ) ? array( $answer ) : $answer;
1328 + if ( array_values( $items ) !== $items || count( $items ) > self::MAX_SUPPLIED_CANDIDATES ) {
1329 + return null;
1330 + }
1331 + $out = array();
1332 + foreach ( $items as $item ) {
1333 + if ( ! is_array( $item ) || ! array_key_exists( 'url', $item ) || ! is_string( $item['url'] ) ) {
1334 + return null;
1335 + }
1336 + $url = trim( $item['url'] );
1337 + if ( '' === $url ) {
1338 + // "No LCP image" only makes sense as the whole answer.
1339 + if ( 1 === count( $items ) ) {
1340 + return array();
1341 + }
1342 + return null;
1343 + }
1344 + // Absolute, protocol-relative or root-relative. A bare `hero.png`
1345 + // passed esc_url() as `http://hero.png`: a high-priority fetch to
1346 + // a host that does not exist.
1347 + if ( '' === esc_url( $url ) || ! preg_match( '#^(?:https?:)?/#i', $url ) ) {
1348 + return null;
1349 + }
1350 + // A media rule this cannot use rejects the answer. Dropping only
1351 + // the rule kept the preload and sent it to every device.
1352 + $media = $item['media'] ?? '';
1353 + if ( ! is_string( $media ) || strlen( $media ) > 200 || preg_match( '#[<>"]#', $media ) ) {
1354 + return null;
1355 + }
1356 + $text = static fn ( $v, int $max ): string => ( is_string( $v ) && strlen( $v ) <= $max ) ? trim( $v ) : '';
1357 + $out[] = array(
1358 + 'url' => $url,
1359 + 'srcset' => $text( $item['srcset'] ?? '', 4096 ),
1360 + 'sizes' => $text( $item['sizes'] ?? '', 512 ),
1361 + 'kind' => 'background' === ( $item['kind'] ?? '' ) ? 'background' : 'img',
1362 + 'media' => trim( $media ),
1363 + );
1364 + }
1365 + return $out;
1366 + }
1367 +
1368 + /**
1369 + * Preload what an extension supplied, and promote the <img> it names.
1370 + *
1371 + * The answer is measured, not guessed, so every other <img> gives up a
1372 + * stray `fetchpriority="high"`: two High images compete with the one
1373 + * that paints first.
1374 + *
1375 + * @param string $html Page HTML.
1376 + * @param array<int,array{url:string,srcset:string,sizes:string,kind:string,media:string}> $candidates From supplied_candidates().
1377 + * @return array{0:string,1:string} [rewritten html, preload markup]
1378 + */
1379 + private static function build_supplied_preload( string $html, array $candidates ): array {
1380 + // Scoped when any preload carries a media rule, even a single one:
1381 + // Pro sends one desktop-only candidate when the phone's LCP is text,
1382 + // and promoting that <img> made phones download a hero they hide.
1383 + $scoped = '' !== implode( '', array_column( $candidates, 'media' ) );
1384 + $skip = array_merge( self::chrome_container_ranges( $html ), Lazy_Loader::hidden_ranges( $html ) );
1385 +
1386 + // Which <img> index each candidate promotes: the first one, outside
1387 + // site chrome and hidden markup, whose src or one of whose srcset
1388 + // URLs IS the candidate. A substring match picked an earlier image
1389 + // whose srcset merely contained the name.
1390 + // Two candidates may claim the same <img>: a phone and a desktop size
1391 + // of one responsive image. The second one is still an <img>, not a
1392 + // background.
1393 + $promote = array();
1394 + $matched = array();
1395 + if ( preg_match_all( '#<img\b[^>]*>#i', $html, $imgs, PREG_OFFSET_CAPTURE ) ) {
1396 + foreach ( $candidates as $c => $candidate ) {
1397 + foreach ( $imgs[0] as $index => $match ) {
1398 + [ $tag, $offset ] = $match;
1399 + if ( self::offset_in_ranges( $offset, $skip ) || Lazy_Loader::tag_is_hidden( $tag, 'img' ) ) {
1400 + continue;
1401 + }
1402 + [ $src, $img_srcset, $img_sizes ] = self::effective_image_src( $tag );
1403 + if ( ! self::same_url( $src, $candidate['url'] ) && ! self::srcset_has( $img_srcset, $candidate['url'] ) ) {
1404 + continue;
1405 + }
1406 + $promote[ $index ] = true;
1407 + $matched[ $c ] = true;
1408 + // The <img> may already be served as a format sibling the
1409 + // answer did not name (`hero.png.webp` for `hero.png`: an
1410 + // image plugin swapped it for this browser). Preload what
1411 + // the <img> will fetch, or the page downloads both.
1412 + if ( self::format_original( $src ) !== $src ) {
1413 + $candidates[ $c ]['url'] = html_entity_decode( $src, ENT_QUOTES );
1414 + $candidates[ $c ]['srcset'] = html_entity_decode( $img_srcset, ENT_QUOTES );
1415 + $candidates[ $c ]['sizes'] = $img_sizes;
1416 + }
1417 + // An answer that names only the URL still gets the <img>'s
1418 + // responsive set: without it the preload fetches the full
1419 + // file and the browser then downloads the size it shows.
1420 + if ( '' === $candidates[ $c ]['srcset'] && '' !== $img_srcset ) {
1421 + $candidates[ $c ]['srcset'] = $img_srcset;
1422 + $candidates[ $c ]['sizes'] = $img_sizes;
1423 + }
1424 + break;
1425 + }
1426 + }
1427 + }
1428 +
1429 + $seen = -1;
1430 + $html = (string) preg_replace_callback(
1431 + '#<img\b[^>]*>#i',
1432 + static function ( array $m ) use ( &$seen, $promote, $scoped ) {
1433 + ++$seen;
1434 + if ( isset( $promote[ $seen ] ) ) {
1435 + // Scoped to a device: make the <img> lazy, so the device
1436 + // that hides it never downloads it. Keeping whatever
1437 + // `loading` it had was not enough: Lazy Load's default
1438 + // "load the first image straight away" had already made
1439 + // it eager. The device that shows it gets it from its own
1440 + // preload, which already fetched it early.
1441 + return $scoped ? self::force_lazy( self::set_fetchpriority( $m[0] ) ) : self::promote_lcp_img( $m[0] );
1442 + }
1443 + if ( 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
1444 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
1445 + }
1446 + return $m[0];
1447 + },
1448 + $html
1449 + );
1450 +
1451 + $preload = '';
1452 + foreach ( $candidates as $c => $candidate ) {
1453 + // Idempotency, as for the automatic pick: a second pass over an
1454 + // already-processed body must not emit the link twice. Compared
1455 + // with `&amp;` decoded, the way the markup spells a query.
1456 + $already = false;
1457 + if ( preg_match_all( '#<link\b[^>]*rel=["\']preload["\'][^>]*>#i', $html, $links ) ) {
1458 + foreach ( $links[0] as $link ) {
1459 + if ( false !== strpos( html_entity_decode( $link, ENT_QUOTES ), $candidate['url'] ) ) {
1460 + $already = true;
1461 + break;
1462 + }
1463 + }
1464 + }
1465 + if ( $already ) {
1466 + continue;
1467 + }
1468 + // An image the page shows through no <img> is a background,
1469 + // whatever the answer said: nothing here can wrap it in <picture>.
1470 + $kind = isset( $matched[ $c ] ) ? $candidate['kind'] : 'background';
1471 + $preload .= self::preload_link( $candidate['url'], $candidate['srcset'], $candidate['sizes'], $kind, $candidate['media'] );
1472 + }
1473 + return array( $html, $preload );
1474 + }
1475 +
1476 + /** Set `loading="lazy"` on an <img>, replacing any other loading value. */
1477 + private static function force_lazy( string $tag ): string {
1478 + $tag = (string) preg_replace( '#\s*(?<![-\w])loading\s*=\s*(["\']?)[a-z]*\1#i', '', $tag, 1 );
1479 + return (string) preg_replace( '#<img\b#i', '<img loading="lazy"', $tag, 1 );
1480 + }
1481 +
1482 + /** Two URLs name the same image: `&amp;` decoded, and a root-relative one compared by path. */
1483 + private static function same_url( string $a, string $b ): bool {
1484 + $a = html_entity_decode( $a, ENT_QUOTES );
1485 + $b = html_entity_decode( $b, ENT_QUOTES );
1486 + if ( '' === $a || '' === $b ) {
1487 + return false;
1488 + }
1489 + if ( $a === $b ) {
1490 + return true;
1491 + }
1492 + // A format sibling is the same image: `hero.png.webp` is `hero.png`.
1493 + $a = self::format_original( $a );
1494 + $b = self::format_original( $b );
1495 + if ( $a === $b ) {
1496 + return true;
1497 + }
1498 + $rel = static function ( string $u ): string {
1499 + if ( 0 === strpos( $u, '/' ) && 0 !== strpos( $u, '//' ) ) {
1500 + return $u;
1501 + }
1502 + $path = (string) wp_parse_url( $u, PHP_URL_PATH );
1503 + $query = (string) wp_parse_url( $u, PHP_URL_QUERY );
1504 + return $path . ( '' !== $query ? '?' . $query : '' );
1505 + };
1506 + return ( 0 === strpos( $a, '/' ) || 0 === strpos( $b, '/' ) ) && $rel( $a ) === $rel( $b );
1507 + }
1508 +
1509 + /**
1510 + * The original of a modern-format sibling that appends its extension,
1511 + * `hero.png.webp` → `hero.png`, the naming ShortPixel, Imagify and other
1512 + * image plugins use. Any other URL comes back unchanged.
1513 + */
1514 + private static function format_original( string $url ): string {
1515 + return (string) preg_replace( '#(\.(?:jpe?g|png))\.(?:webp|avif)(?=$|\?)#i', '$1', $url );
1516 + }
1517 +
1518 + /** Whether one of the URLs in a srcset IS $url (not merely contains it). */
1519 + private static function srcset_has( string $srcset, string $url ): bool {
1520 + foreach ( explode( ',', $srcset ) as $entry ) {
1521 + $candidate = strtok( trim( $entry ), " \t\n" );
1522 + if ( false !== $candidate && self::same_url( $candidate, $url ) ) {
1523 + return true;
1524 + }
1525 + }
1526 + return false;
1527 + }
1528 +
1529 + /**
884 1530 * Promote an <img> to the LCP element: force fetchpriority="high" and
885 1531 * strip any loading="lazy" so the browser loads it immediately. Both are
886 1532 * idempotent. `loading="lazy"` is REMOVED rather than flipped to "eager"
887 1533 * because eager is the default; a bare tag with fetchpriority="high" is
@@ -912,8 +1558,16 @@
912 1558 * before the first stylesheet so the preloads are discovered before the
913 1559 * render-blocking CSS. Falls back to after <head>, then prepend.
914 1560 */
915 1561 private static function inject_into_head( string $html, string $hints ): string {
1562 + // Only a supplied candidate's preload carries `media`. Every other
1563 + // page keeps exactly the placement it had before the seam existed.
1564 + if ( false !== strpos( $hints, ' media="' ) ) {
1565 + $pos = self::after_viewport_offset( $html );
1566 + if ( null !== $pos ) {
1567 + return substr( $html, 0, $pos ) . "\n" . $hints . substr( $html, $pos );
1568 + }
1569 + }
916 1570 // Before the first <link rel="stylesheet"> if there is one.
917 1571 if ( preg_match( '#<link\b[^>]*rel=["\']stylesheet["\'][^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE ) ) {
918 1572 $pos = $m[0][1];
919 1573 return substr( $html, 0, $pos ) . $hints . substr( $html, $pos );
@@ -924,6 +1578,147 @@
924 1578 return substr( $html, 0, $pos ) . "\n" . $hints . substr( $html, $pos );
925 1579 }
926 1580 // No head at all — prepend (degenerate documents).
927 1581 return $hints . $html;
1582 + }
1583 +
1584 + /**
1585 + * Where a media-scoped preload goes: before the first stylesheet, as
1586 + * usual, but never ahead of <meta name="viewport">. Null when the head
1587 + * could not be read, and the usual placement is used instead.
1588 + *
1589 + * A preload's `media` is evaluated when the parser reaches the link, and
1590 + * until the viewport meta is parsed a phone lays out at its default
1591 + * desktop width. A `(min-width: 768px)` preload placed earlier matched on
1592 + * phones too and fetched the desktop hero at high priority.
1593 + *
1594 + * Reads only the head, tag by tag, so a viewport meta or a stylesheet
1595 + * written inside a script string, a comment or an attribute value is
1596 + * never taken for a real one. That put the hints inside a script, which
1597 + * then threw a SyntaxError. A pattern over the whole page did the same
1598 + * job but could give up on a large inline block, and then searched the
1599 + * raw markup.
1600 + *
1601 + * @return int|null Byte offset in $html.
1602 + */
1603 + private static function after_viewport_offset( string $html ) {
1604 + $len = strlen( $html );
1605 + $i = 0;
1606 + $head_start = null;
1607 + $stylesheet = null;
1608 + $viewport = null;
1609 + while ( $i < $len ) {
1610 + $lt = strpos( $html, '<', $i );
1611 + if ( false === $lt ) {
1612 + break;
1613 + }
1614 + if ( 0 === substr_compare( $html, '<!--', $lt, 4 ) ) {
1615 + // `<!-->` and `<!--->` close at once, so look from the second dash.
1616 + $close = strpos( $html, '-->', $lt + 2 );
1617 + if ( false === $close ) {
1618 + return null;
1619 + }
1620 + $i = $close + 3;
1621 + continue;
1622 + }
1623 + if ( ! preg_match( '#\G<(/?)([a-z][a-z0-9-]*)#i', $html, $t, 0, $lt ) ) {
1624 + $i = $lt + 1;
1625 + continue;
1626 + }
1627 + $gt = self::tag_end( $html, $lt + strlen( $t[0] ) );
1628 + if ( null === $gt ) {
1629 + return null;
1630 + }
1631 + $name = strtolower( $t[2] );
1632 + $tag = substr( $html, $lt, $gt + 1 - $lt );
1633 + $i = $gt + 1;
1634 +
1635 + if ( '/' === $t[1] ) {
1636 + if ( 'head' === $name ) {
1637 + break;
1638 + }
1639 + continue;
1640 + }
1641 + if ( 'head' === $name ) {
1642 + $head_start = $i;
1643 + continue;
1644 + }
1645 + if ( 'body' === $name ) {
1646 + break;
1647 + }
1648 + if ( in_array( $name, array( 'script', 'style', 'noscript', 'template', 'title', 'textarea' ), true ) ) {
1649 + $close = stripos( $html, '</' . $name, $i );
1650 + if ( false === $close ) {
1651 + return null;
1652 + }
1653 + $i = $close;
1654 + continue;
1655 + }
1656 + if ( null === $head_start ) {
1657 + continue;
1658 + }
1659 + if ( 'link' !== $name && 'meta' !== $name ) {
1660 + continue;
1661 + }
1662 + $attrs = self::tag_attrs( $tag );
1663 + if ( null === $stylesheet && 'link' === $name && 'stylesheet' === strtolower( $attrs['rel'] ?? '' ) ) {
1664 + if ( null !== $viewport ) {
1665 + return $lt;
1666 + }
1667 + $stylesheet = $lt;
1668 + continue;
1669 + }
1670 + if ( null === $viewport && 'meta' === $name && 'viewport' === strtolower( $attrs['name'] ?? '' ) ) {
1671 + if ( null !== $stylesheet ) {
1672 + return $i;
1673 + }
1674 + $viewport = $i;
1675 + }
1676 + }
1677 + if ( null !== $stylesheet ) {
1678 + return $stylesheet;
1679 + }
1680 + return $viewport ?? $head_start;
1681 + }
1682 +
1683 + /**
1684 + * A tag's attributes, read in order so a quoted value is consumed whole:
1685 + * `content="name=viewport"` is a content attribute, not a name.
1686 + *
1687 + * @return array<string,string> Lowercase name => trimmed value; the first of a repeated name wins.
1688 + */
1689 + private static function tag_attrs( string $tag ): array {
1690 + $out = array();
1691 + preg_match_all( '#\s([^\s=/>"\']+)(?:\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+))?#', $tag, $m, PREG_SET_ORDER );
1692 + foreach ( $m as $a ) {
1693 + $key = strtolower( $a[1] );
1694 + if ( ! isset( $out[ $key ] ) ) {
1695 + $out[ $key ] = trim( trim( $a[2] ?? '', '"\'' ) );
1696 + }
1697 + }
1698 + return $out;
1699 + }
1700 +
1701 + /**
1702 + * Offset of the `>` that ends a tag whose attributes start at $from,
1703 + * stepping over quoted values so `content="a>b"` does not end it early.
1704 + *
1705 + * @return int|null
1706 + */
1707 + private static function tag_end( string $html, int $from ) {
1708 + $len = strlen( $html );
1709 + $quote = '';
1710 + for ( $j = $from; $j < $len; $j++ ) {
1711 + $c = $html[ $j ];
1712 + if ( '' !== $quote ) {
1713 + if ( $c === $quote ) {
1714 + $quote = '';
1715 + }
1716 + } elseif ( '"' === $c || "'" === $c ) {
1717 + $quote = $c;
1718 + } elseif ( '>' === $c ) {
1719 + return $j;
1720 + }
1721 + }
1722 + return null;
928 1723 }
929 1724 }