Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 59 additions & 17 deletions inc/lazyload_replacer.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer {
const IFRAME_PLACEHOLDER_STYLE = '<style type="text/css">' . self::IFRAME_PLACEHOLDER_CLASS . '</style>';

const SVG_PLACEHOLDER = 'data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20#width#%20#height#%22%20width%3D%22#width#%22%20height%3D%22#height#%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22#width#%22%20height%3D%22#height#%22%20fill%3D%22#fill#%22%2F%3E%3C%2Fsvg%3E';
/**
* What precedes a start tag attribute: whitespace or, as browsers allow, directly a quoted value.
*/
private const TAG_ATTRIBUTE_SEPARATOR = '(?:\s+|(?<=["\']))';
/**
* One start tag attribute with its separator.
*
* A quoted value is matched whole, so text inside it is never read as an attribute. An iframe whose
* attribute value starts with a backslash is not matched, so JSON-escaped iframe markup is left as written.
*/
private const TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s"\'>\\\\][^\s>]*))?';
/**
* If frame lazyload is present on page.
*
Expand Down Expand Up @@ -374,38 +385,29 @@ public function lazyload_video_replace( $content ) {
$video_tags = [];
$iframes = [];
$videos = [];
preg_match_all( '#(?:<noscript\s*>\s*)?<iframe(.*?)></iframe>(?:\s*</noscript\s*>)?#is', $content, $iframes );
// Only iframes with no fallback content; one with fallback text is left as written.
preg_match_all( '#(?:<noscript\s*>\s*)?<iframe(?>(?:' . self::TAG_ATTRIBUTE . ')*)\s*/?></iframe>(?:\s*</noscript\s*>)?#i', $content, $iframes );
preg_match_all( '#(?:<noscript\s*>\s*)?<video(.*?)>.*?</video>(?:\s*</noscript\s*>)?#is', $content, $videos );
$iframe_count = count( $iframes[0] );
$video_tags = array_merge( $iframes[0], $videos[0] );

$search = [];
$replace = [];

foreach ( $video_tags as $video_tag ) {
foreach ( $video_tags as $index => $video_tag ) {

if ( ! $this->should_lazyload_iframe( $video_tag ) ) {
continue;
}
if ( preg_match( "/ data-opt-src=['\"]/is", $video_tag ) ) {
continue;
}
$should_add_noscript = true;
$original_tag = $video_tag;
// replace the src and add the data-opt-src attribute
if ( strpos( $video_tag, 'iframe' ) !== false ) {
$video_tag = preg_replace( '/iframe(.*?)src=/is', 'iframe$1 src="about:blank" data-opt-src=', $video_tag );
} elseif ( strpos( $video_tag, 'video' ) !== false ) {
if ( strpos( $video_tag, 'source' ) !== false ) {
if ( strpos( $video_tag, 'preload' ) === false ) {
$video_tag = preg_replace( '/video(.*?)>/is', 'video$1 preload="metadata">', $video_tag, 1 );
$should_add_noscript = false;
} else {
continue;
}
} else {
$video_tag = preg_replace( '/video(.*?)src=/is', 'video$1 data-opt-src=', $video_tag );
}
$lazyloaded = $this->lazyload_media_element( $video_tag, $index < $iframe_count );
if ( null === $lazyloaded ) {
continue;
}
list( $video_tag, $should_add_noscript ) = $lazyloaded;
if ( $this->should_add_noscript( $video_tag ) && $should_add_noscript ) {
$video_tag .= '<noscript>' . $original_tag . '</noscript>';
}
Expand All @@ -419,6 +421,46 @@ public function lazyload_video_replace( $content ) {
return $content;
}

/**
* Move the src of a matched iframe or video to data-opt-src, or ask a sourced video to preload metadata only.
*
* @param string $element The iframe or video element.
* @param bool $is_iframe Whether the element was matched as an iframe.
*
* @return array{0: string, 1: bool}|null The element and whether it gets a noscript copy, or null to leave it untouched.
*/
private function lazyload_media_element( string $element, bool $is_iframe ): ?array {
if ( $is_iframe && strpos( $element, 'iframe' ) !== false ) {
return [ $this->replace_start_tag_src( $element, 'iframe', ' src="about:blank" data-opt-src' ), true ];
}
if ( $is_iframe || strpos( $element, 'video' ) === false ) {
return [ $element, true ];
}
if ( strpos( $element, 'source' ) === false ) {
return [ $this->replace_start_tag_src( $element, 'video', ' data-opt-src' ), true ];
}
if ( strpos( $element, 'preload' ) !== false ) {
return null;
}

return [ preg_replace( '#^((?:<noscript\s*>\s*)?<video(?>(?:' . self::TAG_ATTRIBUTE . ')*)\s*/?)>#i', '$1 preload="metadata">', $element, 1 ) ?? $element, false ];
}

/**
* Replace the name of the src attribute in the element's start tag.
*
* @param string $element Element markup, starting with its start tag.
* @param string $tag_name The element's tag name.
* @param string $replacement Markup written in place of the attribute name, before its `=`.
*
* @return string The element, unchanged when its start tag has no src attribute.
*/
private function replace_start_tag_src( string $element, string $tag_name, string $replacement ): string {
$pattern = '#^((?:<noscript\s*>\s*)?<' . $tag_name . '(?>(?:(?!\s*src\s*=)' . self::TAG_ATTRIBUTE . ')*)' . self::TAG_ATTRIBUTE_SEPARATOR . ')src(?=\s*=)#i';

return preg_replace( $pattern, '$1' . $replacement, $element, 1 ) ?? $element;
}

/**
* Check if the lazyload is allowed for this url.
*
Expand Down
52 changes: 52 additions & 0 deletions tests/test-lazyload.php
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,58 @@ public function test_lazyload_iframe_exclusion() {
$this->assertStringNotContainsString( '<noscript>', $replaced_content );
}

public function test_lazyload_iframe_leaves_content_after_fallback_text_unchanged() {
$form = '<iframe src="https://docs.google.com/forms/d/e/x/viewform?embedded=true" width="640" height="800">Loading…</iframe>';
$comment = '<p>One more thing, the <a href="#x" title="iframe src=x onfocus=alert(1) autofocus y=" rel="nofollow ugc">details</a> are here.</p>';
$map = '<iframe src="https://www.google.com/maps/embed?pb=1" width="600" height="220"></iframe>';

$replaced_content = Optml_Manager::instance()->replace_content( $form . $comment . $map );

$this->assertStringContainsString( $form . $comment, $replaced_content );
$this->assertStringContainsString( '<iframe src="about:blank" data-opt-src="https://www.google.com/maps/embed?pb=1" width="600" height="220"></iframe><noscript>' . $map . '</noscript>', $replaced_content );
}

public function test_lazyload_iframe_rewrites_only_its_src_attribute() {
$iframe = '<iframe title="Clip src=x onload=alert(1) y=" width="640" src="https://www.youtube.com/embed/x?feature=oembed"></iframe>';

$replaced_content = Optml_Manager::instance()->replace_content( $iframe );

$this->assertStringContainsString( '<iframe title="Clip src=x onload=alert(1) y=" width="640" src="about:blank" data-opt-src="https://www.youtube.com/embed/x?feature=oembed"></iframe><noscript>' . $iframe . '</noscript>', $replaced_content );
}

/**
* @dataProvider video_titles_with_src_text
*/
public function test_lazyload_video_rewrites_only_its_src_attribute( string $title ) {
$video = '<video controls title="' . $title . '" src="https://example.org/clip.mp4"></video>';

$replaced_content = Optml_Manager::instance()->replace_content( $video );

$this->assertStringContainsString( '<video controls title="' . $title . '" data-opt-src="https://example.org/clip.mp4"></video><noscript>' . $video . '</noscript>', $replaced_content );
}
Comment thread
pirate-bot marked this conversation as resolved.
Resolved

public function video_titles_with_src_text(): array {
return [
'iframe text' => [ 'iframe src=x onloadstart=alert(1) y=' ],
'video text' => [ 'video src=x onloadstart=alert(1) y=' ],
];
}

public function test_lazyload_video_with_source_preload_ignores_quoted_attribute_text() {
$replaced_content = Optml_Manager::instance()->replace_content( '<video title="a>b src=x" controls><source type="video/mp4" src="https://example.org/c.mp4"></video>' );

$this->assertStringContainsString( '<video title="a>b src=x" controls preload="metadata">', $replaced_content );
$this->assertStringNotContainsString( '<noscript>', $replaced_content );
}

public function test_lazyload_iframe_leaves_json_escaped_markup_unchanged() {
$iframe = '<iframe title="a src=x onload=alert(1) y=" src="https://www.youtube.com/embed/x"></iframe>';

$replaced_content = Optml_Manager::instance()->replace_content( json_encode( [ 'html' => $iframe ], JSON_UNESCAPED_SLASHES ) );

$this->assertSame( [ 'html' => $iframe ], json_decode( $replaced_content, true ) );
}

public function test_generic_placeholder() {
$settings = new Optml_Settings();

Expand Down
Loading