This commit is contained in:
2026-10-06 18:51:23 -06:00
parent 8424dacd03
commit e2c26b7f21
4223 changed files with 737986 additions and 53 deletions
@@ -0,0 +1,93 @@
<?php
namespace WP_Rocket\Engine\Media\Emojis;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Event subscriber to control Emoji behavior.
*
* @since 3.7
*/
class EmojisSubscriber implements Subscriber_Interface {
/**
* The Options Data instance.
*
* @var Options_Data
*/
private $options;
/**
* EmojisSubscriber constructor.
*
* @param Options_Data $options An Options Data instance.
*/
public function __construct( Options_Data $options ) {
$this->options = $options;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.7
*
* @return array
*/
public static function get_subscribed_events() {
return [
'init' => 'disable_emoji',
];
}
/**
* Disable the emoji functionality to reduce then number of external HTTP requests.
*
* @since 3.7 Moved to new architecture.
* @since 2.7
*/
public function disable_emoji() {
if ( ! $this->can_disable_emoji() ) {
return;
}
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
add_filter( 'emoji_svg_url', '__return_false' );
}
/**
* Remove the tinymce emoji plugin.
*
* @since 3.8 deprecated
* @since 3.7 Moved to new architecture.
* @since 2.7
*
* @param array $plugins Plugins loaded for TinyMCE.
*
* @return array
*/
public function disable_emoji_tinymce( $plugins ) {
_deprecated_function( 'WP_Rocket\Engine\Media\Emojis\EmojisSubscriber::disable_emoji_tinymce', '3.8' );
if ( ! $this->can_disable_emoji() ) {
return $plugins;
}
if ( is_array( $plugins ) ) {
return array_diff( $plugins, [ 'wpemoji' ] );
}
return [];
}
/**
* Check for emoji option enabled & not bypassed.
*
* @since 3.7
*
* @return bool
*/
private function can_disable_emoji() {
return ! rocket_bypass() && (bool) $this->options->get( 'emoji', 0 );
}
}
@@ -0,0 +1,59 @@
<?php
namespace WP_Rocket\Engine\Media\ImageDimensions;
use WP_Rocket\Engine\Admin\Settings\Settings;
use WP_Rocket\Event_Management\Subscriber_Interface;
class AdminSubscriber implements Subscriber_Interface {
/**
* ImageDimensions instance
*
* @var ImageDimensions
*/
private $dimensions;
/**
* Instantiate the class
*
* @param ImageDimensions $dimensions ImageDimensions instance.
*/
public function __construct( ImageDimensions $dimensions ) {
$this->dimensions = $dimensions;
}
/**
* Returns an array of events this listens to
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_first_install_options' => [ 'add_option', 14 ],
'rocket_input_sanitize' => [ 'sanitize_option', 10, 2 ],
];
}
/**
* Add the images dimensions option to the WP Rocket options array
*
* @param array $options WP Rocket options array.
* @return array
*/
public function add_option( array $options ): array {
return $this->dimensions->add_option( $options );
}
/**
* Sanitizes the option value when saving from the settings page
*
* @since 3.8
*
* @param array $input Array of sanitized values after being submitted by the form.
* @param Settings $settings Settings class instance.
* @return array
*/
public function sanitize_option( array $input, Settings $settings ): array {
return $this->dimensions->sanitize_option_value( $input, $settings );
}
}
@@ -0,0 +1,589 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Media\ImageDimensions;
use SplFileInfo;
use WP_Filesystem_Direct;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Admin\Settings\Settings;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Logger\Logger;
class ImageDimensions {
use RegexTrait;
/**
* Options_Data instance
*
* @var Options_Data
*/
private $options;
/**
* Filesystem instance
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Frontend constructor.
*
* @param Options_Data $options Options_Data instance.
* @param WP_Filesystem_Direct $filesystem Filesystem instance.
*/
public function __construct( Options_Data $options, $filesystem = null ) {
$this->options = $options;
if ( null === $filesystem ) {
$filesystem = rocket_direct_filesystem();
}
$this->filesystem = $filesystem;
}
/**
* Adds the images dimensions option to WP Rocket options array
*
* @since 3.8
*
* @param array $options WP Rocket options array.
* @return array
*/
public function add_option( array $options ): array {
$options['image_dimensions'] = 0;
return $options;
}
/**
* Sanitizes the option value when saving from the settings page
*
* @since 3.8
*
* @param array $input Array of sanitized values after being submitted by the form.
* @param Settings $settings Settings class instance.
* @return array
*/
public function sanitize_option_value( array $input, Settings $settings ): array {
$input['image_dimensions'] = $settings->sanitize_checkbox( $input, 'image_dimensions' );
return $input;
}
/**
* Specify image dimensions and insert it into images.
*
* @param string $html Buffer Page HTML contents.
*
* @return string Buffer Page HTML contents after inserting dimentions into images.
*/
public function specify_image_dimensions( $html ) {
Logger::debug( 'Start Specify Image Dimensions.' );
if ( ! $this->can_specify_dimensions_images() ) {
Logger::debug( 'Specify Image Dimensions failed because option is not enabled from admin or by filter (rocket_specify_image_dimensions).' );
return $html;
}
// Get all images without width and height attributes.
$images_regex = '<img(?:[^>](?!height=[\'\"](?:\S+)[\'\"]))*+>|<img(?:[^>](?!width=[\'\"](?:\S+)[\'\"]))*+>';
/**
* Filters Specify image dimensions inside picture tags also.
*
* @since 3.8
*
* @param bool Do or not. Default is True, so it will skip all img tags that are inside picture tag.
*/
if ( apply_filters( 'rocket_specify_dimension_skip_pictures', true ) ) {
$images_regex = '<\s*picture[^>]*>.*<\s*\/\s*picture\s*>(*SKIP)(*FAIL)|' . $images_regex;
}
$clean_html = $this->hide_scripts( $html );
$clean_html = $this->hide_noscripts( $clean_html );
preg_match_all( "/{$images_regex}/Uis", $clean_html, $images_match );
if ( empty( $images_match ) ) {
Logger::debug( 'Specify Image Dimensions failed because there is no image without dimensions on this page.' );
return $html;
}
$replaces = [];
/**
* Filters Page images passed to specify dimensions.
*
* @since 3.8
*
* @param array Page images.
*/
$images = apply_filters( 'rocket_specify_dimension_images', $images_match[0] );
Logger::debug( 'Specify Image Dimensions found ( ' . count( $images ) . ' ).', $images );
foreach ( $images as $image ) {
$image_url = $this->can_specify_dimensions_one_image( $image );
if ( ! $image_url ) {
Logger::debug(
'Specify Image Dimensions failed because it has attribute (data-lazy-original or data-no-image-dimensions) or it\'s without src.',
[ 'image' => $image ]
);
continue;
}
$sizes = $this->get_image_sizes( $image_url );
if ( ! $sizes ) {
continue;
}
$width_height = $this->set_dimensions( $image, $sizes );
if ( ! $width_height ) {
continue;
}
// Replace image with new attributes, we will replace all images at once after the loop for optimizations.
$replaces[ $image ] = $this->assign_width_height( $image, $width_height );
}
if ( empty( $replaces ) ) {
return $html;
}
return str_replace( array_keys( $replaces ), $replaces, $html );
}
/**
* Determines if the file is external.
*
* @since 3.8
*
* @param string $url URL of the file.
* @return bool True if external, false otherwise.
*/
private function is_external_file( $url ) {
$file = get_rocket_parse_url( $url );
if ( ! empty( $file['query'] ) ) {
return true;
}
if ( empty( $file['path'] ) ) {
return true;
}
$parsed_site_url = wp_parse_url( site_url() );
if ( empty( $parsed_site_url['host'] ) ) {
return true;
}
/**
* Filters the allowed hosts for optimization
*
* @since 3.4
*
* @param array $hosts Allowed hosts.
* @param array $zones Zones to check available hosts.
*/
$hosts = (array) apply_filters( 'rocket_cdn_hosts', [], [ 'all' ] );
$hosts[] = $parsed_site_url['host'];
$langs = get_rocket_i18n_uri();
// Get host for all langs.
foreach ( $langs as $lang ) {
$url_host = wp_parse_url( $lang, PHP_URL_HOST );
if ( ! isset( $url_host ) ) {
continue;
}
$hosts[] = $url_host;
}
$hosts = array_unique( $hosts );
if ( empty( $hosts ) ) {
return true;
}
// URL has domain and domain is part of the internal domains.
if ( ! empty( $file['host'] ) ) {
foreach ( $hosts as $host ) {
if ( false !== strpos( $file['host'], $host ) ) {
return false;
}
}
return true;
}
return false;
}
/**
* Get local absolute path for image.
*
* @param string $url Image url.
*
* @return string Image absolute local path.
*/
private function get_local_path( $url ) {
$url = $this->normalize_url( $url );
$path = rocket_url_to_path( $url );
if ( $path ) {
return $path;
}
$relative_url = ltrim( wp_make_link_relative( $url ), '/' );
$ds = rocket_get_constant( 'DIRECTORY_SEPARATOR' );
$base_path = isset( $_SERVER['DOCUMENT_ROOT'] ) ? ( sanitize_text_field( wp_unslash( $_SERVER['DOCUMENT_ROOT'] ) ) . $ds ) : '';
return $base_path . str_replace( '/', $ds, $relative_url );
}
/**
* Check if we can specify dimensions for external images.
*
* @return bool Valid to be parsed or not.
*/
private function can_specify_dimensions_external_images() {
/**
* Enable/Disable specify image dimensions for external images.
*
* @since 3.8
*
* @param bool Specify image dimensions for external images or not.
*/
return ini_get( 'allow_url_fopen' ) && apply_filters( 'rocket_specify_image_dimensions_for_distant', false );
}
/**
* Sets the width and height dimensions string
*
* @param string $image Image HTML element.
* @param array $sizes Array of data created by getimagesize().
*
* @return string|false
*/
private function set_dimensions( string $image, array $sizes ) {
preg_match( '/<img.*\sheight=[\'\"]?(?<height>[^\'\"\s]+)[\'\"]?.*>/i', $image, $initial_height );
preg_match( '/<img.*\swidth=[\'\"]?(?<width>[^\'\"\s]+)[\'\"]?.*>/i', $image, $initial_width );
if (
empty( $initial_height['height'] )
&&
empty( $initial_width['width'] )
) {
return $sizes[3];
}
if ( ! empty( $initial_height['height'] ) ) {
if ( ! is_numeric( $initial_height['height'] ) ) {
Logger::debug(
'Specify Image Dimensions failed because specified height is not numeric.',
[ 'image' => $image ]
);
return false;
}
$ratio = $initial_height['height'] / $sizes[1];
return 'width="' . (int) round( $sizes[0] * $ratio ) . '" height="' . $initial_height['height'] . '"';
}
if ( ! empty( $initial_width['width'] ) ) {
if ( ! is_numeric( $initial_width['width'] ) ) {
Logger::debug(
'Specify Image Dimensions failed because specified width is not numeric.',
[ 'image' => $image ]
);
return false;
}
$ratio = $initial_width['width'] / $sizes[0];
return 'width="' . $initial_width['width'] . '" height="' . (int) round( $sizes[1] * $ratio ) . '"';
}
}
/**
* Assign width and height attributes to the img tag.
*
* @param string $image IMG tag.
* @param string $width_height Width/Height attributes in ready state like [height="100" width="100"].
*
* @return string IMG tag after adding attributes otherwise return the input img when error.
*/
private function assign_width_height( string $image, string $width_height ): string {
// Remove old width and height attributes if found.
$changed_image = preg_replace( '/\s(height|width)=(?:[\'"]?(?:[^\'\"\s]+)*[\'"]?)?/i', '', $image );
$changed_image = preg_replace( '/<\s*img/i', '<img ' . $width_height, $changed_image );
if ( null === $changed_image ) {
return $image;
}
return $changed_image;
}
/**
* Check if the image exists, internal or external image.
*
* @param string $image Image Url for external and Image absolute path for internal.
* @param bool $external If this image is external or not.
*
* @return bool If image exists or not.
*/
private function image_exists( string $image, $external = false ): bool {
if ( ! $image ) {
return false;
}
if ( ! $external ) {
return $this->filesystem->exists( $image );
}
$file_headers = get_headers( $image );
if ( ! $file_headers ) {
return false;
}
return false !== strstr( $file_headers[0], '200' );
}
/**
* Check if we can specify image dimensions for all images.
*
* @return bool Can we or not.
*/
private function can_specify_dimensions_images(): bool {
/**
* Filter images dimensions attributes process.
*
* @since 2.2
*
* @param bool Do the job or not.
*/
return apply_filters( 'rocket_specify_image_dimensions', false )
||
$this->options->get( 'image_dimensions', false );
}
/**
* Check if we can specify image dimensions for one image.
*
* @param string $image Full img tag.
*
* @return false|string false if we can't specify for this image otherwise get img src attribute.
*/
private function can_specify_dimensions_one_image( string $image ) {
// Don't touch lazy-load file (no conflict with Photon (Jetpack)).
if (
false !== strpos( $image, 'data-lazy-original' )
||
false !== strpos( $image, 'data-no-image-dimensions' )
||
! preg_match( '/\s+src\s*=\s*[\'"](?<url>[^\'"]+)/i', $image, $src_match )
) {
return false;
}
return $src_match['url'];
}
/**
* Get Image sizes.
*
* @param string $image_url Image url to get sizes for.
*
* @return array|false Get image sizes otherwise false.
*/
private function get_image_sizes( string $image_url ) {
if ( $this->is_external_file( $image_url ) ) {
$image_url = $this->normalize_url( $image_url );
if ( ! $this->can_specify_dimensions_external_images() ) {
Logger::debug(
'Specify Image Dimensions failed because you/server disabled specifying dimensions for external images.',
[ 'image_url' => $image_url ]
);
return false;
}
if ( ! $this->image_exists( $image_url, true ) ) {
Logger::debug(
'Specify Image Dimensions failed because external image not found.',
[ 'image_url' => $image_url ]
);
return false;
}
$sizes = $this->getimagesize( $image_url );
if ( ! $sizes ) {
Logger::debug(
'Specify Image Dimensions failed because image is not valid.',
[ 'image_url' => $image_url ]
);
return false;
}
return $sizes;
}
$local_path = $this->get_local_path( $image_url );
if ( ! $this->image_exists( $local_path, false ) ) {
Logger::debug(
'Specify Image Dimensions failed because internal image is not found.',
[ 'image_url' => $image_url ]
);
return false;
}
$sizes = $this->getimagesize( $local_path );
if ( ! $sizes ) {
Logger::debug(
'Specify Image Dimensions failed because image is not valid.',
[ 'image_url' => $image_url ]
);
return false;
}
return $sizes;
}
/**
* Gets image sizes for the given file
*
* @param string $filename File we want to retrieve information about.
*
* @return array|false
*/
private function getimagesize( string $filename ) {
$file = new SplFileInfo( strtok( $filename, '?' ) );
if ( 'svg' === $file->getExtension() ) {
return $this->svg_getimagesize( $filename );
}
return getimagesize( $filename );
}
/**
* Gets image sizes for the given SVG file
*
* Uses the width/height attributes if present, or fallback to viewBox attribute
*
* @param string $filename File we want to retrieve information about.
*
* @return array|false
*/
private function svg_getimagesize( string $filename ) {
$svgfile = simplexml_load_file( rawurlencode( $filename ), 'SimpleXMLElement', rocket_get_constant( 'LIBXML_NOERROR', 32 ) | rocket_get_constant( 'LIBXML_NOWARNING', 64 ) );
if ( ! $svgfile ) {
return false;
}
$width = $this->format_svg_value( (string) $svgfile->attributes()->width );
$height = $this->format_svg_value( (string) $svgfile->attributes()->height );
$size = [];
if (
! empty( $width )
&&
! empty( $height )
) {
$size[0] = $width;
$size[1] = $height;
$size[2] = 0;
$size[3] = 'width="' . absint( $width ) . '" height="' . absint( $height ) . '"';
return $size;
}
$view_box = preg_split( '/[\s,]+/', (string) $svgfile->attributes()->viewBox );
if ( ! empty( $view_box ) ) {
if (
! empty( $view_box[2] )
&&
! empty( $view_box[3] )
) {
$size[0] = $view_box[2];
$size[1] = $view_box[3];
$size[2] = 0;
$size[3] = 'width="' . absint( $size[0] ) . '" height="' . absint( $size[1] ) . '"';
return $size;
}
return false;
}
return false;
}
/**
* Formats the SVG width/height value in case of unusual units
*
* @since 3.10.8
*
* @param string $value The value of the SVG width/height attribute.
*
* @return string
*/
private function format_svg_value( string $value ): string {
// No unit, we can use the value directly.
if ( is_numeric( $value ) ) {
return $value;
}
if ( empty( $value ) ) {
return $value;
}
$px_pattern = '/([0-9]+)\s*px/i';
// If pixel unit, remove the unit and return the numeric value.
if ( preg_match( $px_pattern, $value ) ) {
return preg_replace( $px_pattern, '$1', $value );
}
// Return an empty string for other units.
return '';
}
/**
* Normalize relative url to full url.
*
* @param string $url Url to be normalized.
*
* @return string Normalized url.
*/
private function normalize_url( string $url ): string {
$url_host = wp_parse_url( $url, PHP_URL_HOST );
if ( empty( $url_host ) ) {
$relative_url = ltrim( wp_make_link_relative( $url ), '/' );
$site_url_components = wp_parse_url( site_url( '/' ) );
return $site_url_components['scheme'] . '://' . $site_url_components['host'] . '/' . $relative_url;
}
return $url;
}
}
@@ -0,0 +1,55 @@
<?php
namespace WP_Rocket\Engine\Media\ImageDimensions;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Images Subscriber
*
* @since 3.8
*/
class Subscriber implements Subscriber_Interface {
/**
* Images dimensions instance
*
* @var ImageDimensions
*/
private $dimensions;
/**
* Subscriber constructor.
*
* @param ImageDimensions $dimensions Images dimensions class that handles all business logic.
*/
public function __construct( ImageDimensions $dimensions ) {
$this->dimensions = $dimensions;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_buffer' => [ 'specify_image_dimensions', 17 ],
];
}
/**
* Update images that have no width/height with real dimentions.
*
* @param string $buffer Page HTML content.
*
* @return string Page HTML content after update.
*/
public function specify_image_dimensions( $buffer ) {
if ( rocket_bypass() ) {
return $buffer;
}
return $this->dimensions->specify_image_dimensions( $buffer );
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Media\Lazyload;
use WP_Rocket\Event_Management\Subscriber_Interface;
class AdminSubscriber implements Subscriber_Interface {
/**
* Returns an array of events this listens to
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_first_install_options' => [ 'add_option', 15 ],
'rocket_input_sanitize' => 'sanitize_exclude_lazyload',
'rocket_meta_boxes_fields' => [ 'add_meta_box', 7 ],
];
}
/**
* Adds the exclude lazyload option to WP Rocket options array
*
* @since 3.8
*
* @param array $options WP Rocket options array.
* @return array
*/
public function add_option( array $options ): array {
$options['exclude_lazyload'] = [];
return $options;
}
/**
* Sanitizes the exclude lazyload input when saving the option
*
* @since 3.8
*
* @param array $input Input array.
* @return array
*/
public function sanitize_exclude_lazyload( array $input ): array {
if ( empty( $input['exclude_lazyload'] ) ) {
$input['exclude_lazyload'] = [];
}
$input['exclude_lazyload'] = rocket_sanitize_textarea_field( 'exclude_lazyload', $input['exclude_lazyload'] );
return $input;
}
/**
* Add the field to the WP Rocket metabox on the post edit page.
*
* @param string[] $fields Metaboxes fields.
*
* @return string[]
*/
public function add_meta_box( array $fields ) {
$fields['lazyload'] = __( 'LazyLoad for images', 'rocket' );
$fields['lazyload_iframes'] = __( 'LazyLoad for iframes/videos', 'rocket' );
return $fields;
}
}
@@ -0,0 +1,36 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Admin;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
/**
* Service provider.
*/
class ServiceProvider extends AbstractServiceProvider {
/**
* The provided array is a way to let the container
* know that a service is provided by this service
* provider. Every service that is registered via
* this service provider must have an alias added
* to this array or it will be ignored.
*
* @var array
*/
protected $provides = [
'lazyload_css_admin_subscriber',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$this->getContainer()->share( 'lazyload_css_admin_subscriber', Subscriber::class )
->addArgument( $this->getContainer()->get( 'lazyload_css_cache' ) );
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Admin;
use WP_Rocket\Engine\Common\Cache\CacheInterface;
use WP_Rocket\Event_Management\Subscriber_Interface;
class Subscriber implements Subscriber_Interface {
/**
* Cache instance.
*
* @var CacheInterface
*/
protected $cache;
/**
* Instantiate class.
*
* @param CacheInterface $cache Cache instance.
*/
public function __construct( CacheInterface $cache ) {
$this->cache = $cache;
}
/**
* Returns an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_meta_boxes_fields' => [ 'add_meta_box', 8 ],
'admin_notices' => 'maybe_add_error_notice',
'rocket_safe_mode_reset_options' => 'add_option_safemode',
];
}
/**
* Add the field to the WP Rocket metabox on the post edit page.
*
* @param string[] $fields Metaboxes fields.
*
* @return string[]
*/
public function add_meta_box( array $fields ) {
$fields['lazyload_css_bg_img'] = __( 'LazyLoad CSS backgrounds', 'rocket' );
return $fields;
}
/**
* Maybe display the error notice.
*
* @return void
*/
public function maybe_add_error_notice() {
if ( ! current_user_can( 'rocket_manage_options' ) || $this->cache->is_accessible() ) {
return;
}
rocket_notice_html(
[
'status' => 'error',
'dismissible' => '',
'message' => rocket_notice_writing_permissions( $this->cache->get_root_path() ),
]
);
}
/**
* Add option to safe mode.
*
* @param string[] $options Safe mode options.
* @return string[]
*/
public function add_option_safemode( array $options ) {
$options['lazyload_css_bg_img'] = 0;
return $options;
}
}
@@ -0,0 +1,55 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Context;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Common\Cache\CacheInterface;
use WP_Rocket\Engine\Common\Context\AbstractContext;
use WP_Rocket\Engine\Media\Lazyload\CanLazyloadTrait;
class LazyloadCSSContext extends AbstractContext {
use CanLazyloadTrait;
/**
* Cache instance.
*
* @var CacheInterface
*/
protected $cache;
/**
* Instantiate the class.
*
* @param Options_Data $options WPR options.
* @param CacheInterface $cache Cache instance.
*/
public function __construct( Options_Data $options, CacheInterface $cache ) {
parent::__construct( $options );
$this->cache = $cache;
}
/**
* Determine if the action is allowed.
*
* @param array $data Data to pass to the context.
* @return bool
*/
public function is_allowed( array $data = [] ): bool {
$is_allowed = $this->run_common_checks(
[
'do_not_optimize' => false,
'bypass' => false,
'option' => 'lazyload_css_bg_img',
'password_protected' => false,
'post_excluded' => 'lazyload_css_bg_img',
'logged_in' => false,
]
);
if ( ! $is_allowed || ! $this->should_lazyload() ) {
return false;
}
return $this->cache->is_accessible();
}
}
@@ -0,0 +1,34 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Data;
class LazyloadCSSContentFactory {
/**
* Make LazyloadedContent instance.
*
* @param array $formatted_urls Formatted URls.
* @param string $content Content.
* @return LazyloadedContent
*/
public function make_lazyloaded_content( array $formatted_urls, string $content ): LazyloadedContent {
$lazyloaded_content = new LazyloadedContent();
$lazyloaded_content->set_urls( $formatted_urls );
$lazyloaded_content->set_content( $content );
return $lazyloaded_content;
}
/**
* Make ProtectedContent instance.
*
* @param array $protected_files Protected files.
* @param string $content Content.
* @return ProtectedContent
*/
public function make_protected_content( array $protected_files, string $content ): ProtectedContent {
$protected_content = new ProtectedContent();
$protected_content->set_content( $content );
$protected_content->set_protected_files_mapping( $protected_files );
return $protected_content;
}
}
@@ -0,0 +1,58 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Data;
class LazyloadedContent {
/**
* URls extracted from the content.
*
* @var array
*/
protected $urls = [];
/**
* Lazyloaded content.
*
* @var string
*/
protected $content = '';
/**
* Get URls extracted from the content.
*
* @return array
*/
public function get_urls(): array {
return $this->urls;
}
/**
* Set URls extracted from the content.
*
* @param array $urls URls extracted from the content.
* @return void
*/
public function set_urls( array $urls ): void {
$this->urls = $urls;
}
/**
* Get lazyloaded content.
*
* @return string
*/
public function get_content(): string {
return $this->content;
}
/**
* Set lazyloaded content.
*
* @param string $content Lazyloaded content.
* @return void
*/
public function set_content( string $content ): void {
$this->content = $content;
}
}
@@ -0,0 +1,58 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Data;
class ProtectedContent {
/**
* Protected content.
*
* @var string
*/
protected $content = '';
/**
* Mapping between protected files and their placeholder.
*
* @var array
*/
protected $protected_files_mapping = [];
/**
* Set protected content.
*
* @param string $content Protected content.
* @return void
*/
public function set_content( string $content ): void {
$this->content = $content;
}
/**
* Get protected content.
*
* @return string
*/
public function get_content(): string {
return $this->content;
}
/**
* Set mapping between protected files and their placeholder.
*
* @param array $protected_files_mapping Mapping between protected files and their placeholder.
* @return void
*/
public function set_protected_files_mapping( array $protected_files_mapping ): void {
$this->protected_files_mapping = $protected_files_mapping;
}
/**
* Get mapping between protected files and their placeholder.
*
* @return array
*/
public function get_protected_files_mapping(): array {
return $this->protected_files_mapping;
}
}
@@ -0,0 +1,64 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Front;
use WP_Filesystem_Direct;
use WP_Rocket\Engine\Optimization\CSSTrait;
class ContentFetcher {
use CSSTrait;
/**
* WordPress filesystem.
*
* @var WP_Filesystem_Direct
*/
protected $filesystem;
/**
* Instance.
*
* @param WP_Filesystem_Direct $filesystem WordPress filesystem.
*/
public function __construct( WP_Filesystem_Direct $filesystem = null ) {
$this->filesystem = $filesystem ?: rocket_direct_filesystem();
}
/**
* Fetch content from the resource.
*
* @param string $path Path from the resource.
* @param string $destination Destination path.
* @return false|string
*/
public function fetch( string $path, string $destination ) {
$content = $this->fetch_content( $path );
if ( ! $content ) {
return false;
}
$content = $this->move( $this->get_converter( $path, $destination ), $content, $path );
$this->set_cached_import( $path );
$content = $this->combine_imports( $content, $destination );
return $content;
}
/**
* Fetch the content from the file.
*
* @param string $path Path to fetch.
*
* @return false|string
*/
protected function fetch_content( string $path ) {
if ( ! wp_http_validate_url( $path ) ) {
return $this->filesystem->get_contents( $path );
}
return wp_remote_retrieve_body( wp_remote_get( $path ) );
}
}
@@ -0,0 +1,230 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Front;
use WP_Rocket\Engine\Optimization\RegexTrait;
class Extractor {
use RegexTrait;
/**
* Comment mapping.
*
* @var array
*/
protected $comments_mapping = [];
/**
* Extract background images from CSS.
*
* @param string $content CSS content.
* @return array
*/
public function extract( string $content ): array {
$this->comments_mapping = [];
$comment_regex = '#/\*[^*]*\*+([^/][^*]*\*+)*/#';
$content = preg_replace_callback(
$comment_regex,
function ( $matches ) {
$id = '/*' . uniqid( 'bg_css_comment' ) . '*/';
$this->comments_mapping[ $id ] = $matches[0];
return $id;
},
$content
);
$background_regex = '(?<selector>[ \-,:\w.()\n\r^>[*"\'=\]#]+)\s?{[^{}]*background\s*:(?<property>[^;}]*)[^}]*}';
$background_image_regex = '(?<selector>[ \-,:\w.()\n\r>^[*"\'=\]#]+)\s?{[^{}]*background-image\s*:(?<property>[^;}]*)[^}]*}';
/**
* Lazyload background property regex.
*
* @param string $regex Lazyload background property regex.
*/
$background_regex = $this->apply_string_filter( 'lazyload_css_extract_bg_property_regex', $background_regex );
/**
* Lazyload background property regex.
*
* @param string $regex Lazyload background property regex.
*/
$background_image_regex = $this->apply_string_filter( 'lazyload_css_extract_bg_img_property_regex', $background_image_regex );
$background_matches = $this->find( $background_regex, $content, 'mi' );
$background_image_matches = $this->find( $background_image_regex, $content, 'mi' );
$matches = array_merge( $background_matches, $background_image_matches );
if ( empty( $matches ) ) {
return [];
}
$results = [];
foreach ( $matches as $match ) {
if ( ! key_exists( 'property', $match ) || ! key_exists( 'selector', $match ) ) {
continue;
}
$property = $match['property'];
$selector = $match['selector'];
$property = trim( $property );
$selector = trim( $selector );
$urls = $this->extract_urls( $property );
$block = trim( $match[0] );
foreach ( $this->comments_mapping as $id => $comment ) {
$block = str_replace( $id, $comment, $block );
}
foreach ( $urls as $url ) {
$results[ $selector ][] = [
'selector' => $selector,
'url' => $url['url'],
'original' => $url['original'],
'block' => $block,
];
}
}
return $results;
}
/**
* Extract URLS from a CSS property.
*
* @param string $content Content from the CSS property.
* @return array
*/
protected function extract_urls( string $content ): array {
/**
* Lazyload URL regex.
*
* @param string $regex Lazyload URL regex.
*/
$regex = $this->apply_string_filter( 'lazyload_css_extract_url_regex', '(?<tag>url\([\'"]?(?<url>[^\)]*)[\'"]?\))' );
$matches = $this->find( $regex, $content, 'mi' );
$output = [];
/**
* Lazyload ignored URLs.
*
* @param string[] $urls Ignored URLs.
*/
$ignored_urls = (array) apply_filters( 'rocket_lazyload_css_ignored_urls', [] );
foreach ( $matches as $match ) {
$url = $match['url'] ?: '';
$url = str_replace( '"', '', $url );
$url = str_replace( "'", '', $url );
$url = trim( $url );
$url = $this->make_url_complete( $url );
if ( ! key_exists( 'tag', $match ) || ! key_exists( 'url', $match ) || ! $url || $this->is_url_ignored( $url, $ignored_urls ) ) {
continue;
}
if ( ! $this->is_url_external( $url ) && ! $this->is_relative( $url ) ) {
$url = $this->apply_string_filter( 'css_url', $url );
}
$url = "url('$url')";
$original_url = trim( $match['tag'], ' ,' );
$output[] = [
'url' => $url,
'original' => $original_url,
];
}
return $output;
}
/**
* Apply a string filter.
*
* @param string $name Name from the filter.
* @param string $value Value to pass to the filter that will be returned.
* @param array ...$args Additional values.
* @return string
*/
protected function apply_string_filter( string $name, string $value, ...$args ) {
$output = apply_filters( 'rocket_' . $name, $value, ...$args );
if ( ! is_string( $output ) ) {
return $value;
}
return $output;
}
/**
* Check if the URLs is ignored.
*
* @param string $url URL to check.
* @param array $ignored_urls List of ignored URLs.
*
* @return bool
*/
protected function is_url_ignored( string $url, array $ignored_urls ): bool {
foreach ( $ignored_urls as $ignored_url ) {
if ( strpos( $url, $ignored_url ) !== false ) {
return true;
}
}
return false;
}
/**
* Complete the URL if necessary.
*
* @param string $url URL to complete.
*
* @return string
*/
protected function make_url_complete( string $url ): string {
$host = wp_parse_url( $url, PHP_URL_HOST );
if ( $host || $this->is_relative( $url ) ) {
return $url;
}
return rocket_get_home_url() . '/' . trim( $url, '/ ' );
}
/**
* Check if the URL is external.
*
* @param string $url URL to check.
*
* @return bool
*/
protected function is_url_external( string $url ): bool {
$host = wp_parse_url( $url, PHP_URL_HOST );
if ( ! $host ) {
return false;
}
$home_host = wp_parse_url( rocket_get_home_url(), PHP_URL_HOST );
return $host !== $home_host;
}
/**
* Check if the URL is relative.
*
* @param string $url URL to check.
* @return bool
*/
protected function is_relative( string $url ): bool {
return preg_match( '/^\./', $url );
}
}
@@ -0,0 +1,23 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Front;
class FileResolver {
/**
* Resolves the name from the file from its URL.
*
* @param string $url URL from the file to resolve.
* @return string
*/
public function resolve( string $url ): string {
$path = rocket_url_to_path( strtok( $url, '?' ) );
if ( ! $path ) {
return '';
}
return $path;
}
}
@@ -0,0 +1,124 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Front;
class MappingFormatter {
/**
* Format data for the Mapping file.
*
* @param array $data Data to format.
* @return array
*/
public function format( array $data ): array {
$formatted_urls = [];
foreach ( $data as $datum ) {
$hash = $datum['hash'];
$selector = $datum['selector'];
$selector = $this->remove_pseudo_classes( $selector );
$url = $datum['url'];
$placeholder = "--wpr-bg-$hash";
$variable_placeholder = ':root{' . $placeholder . ': ' . $url . ';}';
$formatted_urls[] = [
'selector' => $selector,
'style' => $variable_placeholder,
'hash' => $hash,
];
}
return $formatted_urls;
}
/**
* Get pseudo elements to remove.
*
* @return string[]
*/
private function get_pseudo_elements_to_remove() {
$original_pseudo_elements = [
':before',
':after',
':first-line',
':first-letter',
':active',
':hover',
':focus',
':visited',
':focus-within',
':focus-visible',
];
/**
* Pseudo elements to remove from lazyload CSS selector.
*
* @param string[] Pseudo elements to remove.
*/
$pseudo_elements_to_remove = apply_filters( 'rocket_lazyload_css_ignored_pseudo_elements', $original_pseudo_elements );
if ( ! is_array( $original_pseudo_elements ) ) {
$pseudo_elements_to_remove = $original_pseudo_elements;
}
usort(
$pseudo_elements_to_remove,
static function ( $first, $second ) {
if ( strlen( $first ) === strlen( $second ) ) {
return 0;
}
return ( strlen( $first ) > strlen( $second ) ) ? -1 : 1;
}
);
return $pseudo_elements_to_remove;
}
/**
* Remove pseudo classes from the selector while mapping on each selector.
*
* @param string $selector Selector to clean.
* @return string
*/
public function remove_pseudo_classes_for_selector( string $selector ): string {
$selector = preg_replace( '/::[\w-]+/', '', $selector );
$pseudo_elements_to_remove = $this->get_pseudo_elements_to_remove();
foreach ( $pseudo_elements_to_remove as $element ) {
$selector = str_replace( $element, '', $selector );
}
if ( in_array( substr( $selector, -1 ), [ '&', '~', '+', '>' ], true ) ) {
$selector .= '*';
}
if ( ! $selector ) {
return 'body';
}
return $selector;
}
/**
* Remove pseudo classes from the selector.
*
* @param string $selector Selector to clean.
* @return string
*/
protected function remove_pseudo_classes( string $selector ): string {
$selectors = explode( ',', $selector );
$selectors = array_map( [ $this, 'remove_pseudo_classes_for_selector' ], $selectors );
$selectors = array_unique( $selectors );
$selector = implode( ',', $selectors );
if ( ! $selector ) {
return 'body';
}
return (string) $selector;
}
}
@@ -0,0 +1,71 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Front;
class RuleFormatter {
/**
* Format the CSS rule inside the CSS content.
*
* @param string $css CSS content.
* @param array $data Data to format.
* @return string
*/
public function format( string $css, array $data ): string {
if ( count( $data ) === 0 ) {
return $css;
}
$block = '';
$replaced_block = null;
$blocks = [];
foreach ( $data as $datum ) {
$added = false;
foreach ( $blocks as &$block ) {
if ( $block['block'] === $datum['block'] ) {
$block['items'] [] = $datum;
$added = true;
break;
}
}
if ( $added ) {
continue;
}
$blocks [] = [
'items' => [
$datum,
],
'block' => $datum['block'],
];
}
foreach ( $blocks as $block ) {
$replaced_block = null;
foreach ( $block['items'] as $datum ) {
if ( ! key_exists( 'selector', $datum ) || ! key_exists( 'original', $datum ) || ! key_exists( 'block', $datum ) || ! key_exists( 'hash', $datum ) ) {
return $css;
}
$original_block = $datum['block'];
$replaced_block = $replaced_block ?: $datum['block'];
$url = $datum['original'];
$hash = $datum['hash'];
$placeholder = "--wpr-bg-$hash";
$variable_placeholder = "var($placeholder)";
$replaced_block = str_replace( $url, $variable_placeholder, $replaced_block );
}
$css = str_replace( $original_block, $replaced_block, $css );
}
return $css;
}
}
@@ -0,0 +1,50 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS\Front;
class TagGenerator {
/**
* Generate tags from the mapping of lazyloaded images.
*
* @param array $mapping Lazyload images mapping.
* @param array $loaded Excluded images.
* @return string
*/
public function generate( array $mapping, array $loaded = [] ): string {
$mapping = array_filter(
$mapping,
function ( $mapping_item ) use ( $loaded ) {
foreach ( $loaded as $exclude_item ) {
if ( $exclude_item['style'] === $mapping_item['style'] ) {
return false; // Exclude matching elements.
}
}
return true; // Include non-matching elements.
}
);
$mapping = array_values( $mapping );
$loaded_content = '';
foreach ( $loaded as $item ) {
$loaded_content .= $item['style'];
}
$loaded_tag = "<style id=\"wpr-lazyload-bg\"></style><style id=\"wpr-lazyload-bg-exclusion\">$loaded_content</style>";
$nostyle_content = '';
foreach ( $mapping as $item ) {
$nostyle_content .= $item['style'];
}
$nostyle_tag = "<noscript>
<style id=\"wpr-lazyload-bg-nostyle\">$nostyle_content</style>
</noscript>";
$mapping_json = wp_json_encode( $mapping );
$loaded_json = wp_json_encode( $loaded );
$script_content = "const rocket_pairs = $mapping_json; const rocket_excluded_pairs = $loaded_json;";
$script_tag = "<script type=\"application/javascript\">$script_content</script>";
return "$loaded_tag\n$nostyle_tag\n$script_tag";
}
}
@@ -0,0 +1,73 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Common\Cache\FilesystemCache;
use WP_Rocket\Engine\Media\Lazyload\CSS\Context\LazyloadCSSContext;
use WP_Rocket\Engine\Media\Lazyload\CSS\Data\LazyloadCSSContentFactory;
use WP_Rocket\Engine\Media\Lazyload\CSS\Front\{ContentFetcher,
Extractor,
FileResolver,
MappingFormatter,
RuleFormatter,
TagGenerator};
/**
* Service provider.
*/
class ServiceProvider extends AbstractServiceProvider {
/**
* The provides array is a way to let the container
* know that a service is provided by this service
* provider. Every service that is registered via
* this service provider must have an alias added
* to this array or it will be ignored.
*
* @var array
*/
protected $provides = [
'lazyload_css_cache',
'lazyload_css_subscriber',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$this->getLeagueContainer()->add( 'lazyload_css_cache', FilesystemCache::class )
->addArgument( apply_filters( 'rocket_lazyload_css_cache_root', 'background-css/' . get_current_blog_id() ) );
$cache = $this->getContainer()->get( 'lazyload_css_cache' );
$this->getLeagueContainer()->add( 'lazyload_css_context', LazyloadCSSContext::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $cache );
$this->getLeagueContainer()->add( 'lazyload_css_fetcher', ContentFetcher::class );
$this->getLeagueContainer()->add( 'lazyload_css_extractor', Extractor::class );
$this->getLeagueContainer()->add( 'lazyload_css_file_resolver', FileResolver::class );
$this->getLeagueContainer()->add( 'lazyload_css_json_formatter', MappingFormatter::class );
$this->getLeagueContainer()->add( 'lazyload_css_rule_formatter', RuleFormatter::class );
$this->getLeagueContainer()->add( 'lazyload_css_tag_generator', TagGenerator::class );
$this->getLeagueContainer()->add( 'lazyload_css_factory', LazyloadCSSContentFactory::class );
$this->getLeagueContainer()->share( 'lazyload_css_subscriber', Subscriber::class )
->addArgument( $this->getContainer()->get( 'lazyload_css_extractor' ) )
->addArgument( $this->getContainer()->get( 'lazyload_css_rule_formatter' ) )
->addArgument( $this->getContainer()->get( 'lazyload_css_file_resolver' ) )
->addArgument( $cache )
->addArgument( $this->getContainer()->get( 'lazyload_css_json_formatter' ) )
->addArgument( $this->getContainer()->get( 'lazyload_css_tag_generator' ) )
->addArgument( $this->getContainer()->get( 'lazyload_css_fetcher' ) )
->addArgument( $this->getContainer()->get( 'lazyload_css_context' ) )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'lazyload_css_factory' ) );
}
}
@@ -0,0 +1,721 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload\CSS;
use WP_Filesystem_Direct;
use WP_Post;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Common\Context\ContextInterface;
use WP_Rocket\Engine\Media\Lazyload\CSS\Data\LazyloadedContent;
use WP_Rocket\Engine\Media\Lazyload\CSS\Data\LazyloadCSSContentFactory;
use WP_Rocket\Engine\Media\Lazyload\CSS\Data\ProtectedContent;
use WP_Rocket\Engine\Media\Lazyload\CSS\Front\{ContentFetcher,
Extractor,
FileResolver,
MappingFormatter,
RuleFormatter,
TagGenerator};
use WP_Rocket\Engine\Common\Cache\CacheInterface;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Logger\LoggerAware;
use WP_Rocket\Logger\LoggerAwareInterface;
class Subscriber implements Subscriber_Interface, LoggerAwareInterface {
use LoggerAware;
use RegexTrait;
/**
* Extract background images from CSS.
*
* @var Extractor
*/
protected $extractor;
/**
* Cache instance.
*
* @var CacheInterface
*/
protected $cache;
/**
* Format the CSS rule inside the CSS content.
*
* @var RuleFormatter
*/
protected $rule_formatter;
/**
* Resolves the name from the file from its URL.
*
* @var FileResolver
*/
protected $file_resolver;
/**
* Format data for the Mapping file.
*
* @var MappingFormatter
*/
protected $mapping_formatter;
/**
* Generate tags from the mapping of lazyloaded images.
*
* @var TagGenerator
*/
protected $tag_generator;
/**
* Fetch content.
*
* @var ContentFetcher
*/
protected $fetcher;
/**
* Context.
*
* @var ContextInterface
*/
protected $context;
/**
* WPR Options.
*
* @var Options_Data
*/
protected $options;
/**
* Make LazyloadedContent instance.
*
* @var LazyloadCSSContentFactory
*/
protected $lazyloaded_content_factory;
/**
* WordPress filesystem.
*
* @var WP_Filesystem_Direct
*/
protected $filesystem;
/**
* Instantiate class.
*
* @param Extractor $extractor Extract background images from CSS.
* @param RuleFormatter $rule_formatter Format the CSS rule inside the CSS content.
* @param FileResolver $file_resolver Resolves the name from the file from its URL.
* @param CacheInterface $cache Cache instance.
* @param MappingFormatter $mapping_formatter Format data for the Mapping file.
* @param TagGenerator $tag_generator Generate tags from the mapping of lazy loaded images.
* @param ContentFetcher $fetcher Fetch content.
* @param ContextInterface $context Context.
* @param Options_Data $options WPR Options.
* @param LazyloadCSSContentFactory $lazyloaded_content_factory Make LazyloadedContent instance.
* @param WP_Filesystem_Direct|null $filesystem WordPress filesystem.
*/
public function __construct( Extractor $extractor, RuleFormatter $rule_formatter, FileResolver $file_resolver, CacheInterface $cache, MappingFormatter $mapping_formatter, TagGenerator $tag_generator, ContentFetcher $fetcher, ContextInterface $context, Options_Data $options, LazyloadCSSContentFactory $lazyloaded_content_factory, WP_Filesystem_Direct $filesystem = null ) {
$this->extractor = $extractor;
$this->cache = $cache;
$this->rule_formatter = $rule_formatter;
$this->file_resolver = $file_resolver;
$this->mapping_formatter = $mapping_formatter;
$this->tag_generator = $tag_generator;
$this->context = $context;
$this->options = $options;
$this->fetcher = $fetcher;
$this->lazyloaded_content_factory = $lazyloaded_content_factory;
$this->filesystem = $filesystem ?: rocket_direct_filesystem();
}
/**
* Returns an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_generate_lazyloaded_css' => [
[ 'create_lazy_css_files', 18 ],
[ 'create_lazy_inline_css', 21 ],
[ 'add_lazy_tag', 24 ],
],
'rocket_buffer' => [ 'maybe_replace_css_images', 1002 ],
'after_rocket_clean_domain' => 'clear_generated_css',
'wp_enqueue_scripts' => 'insert_lazyload_script',
'rocket_css_image_lazyload_images_load' => [ 'exclude_rocket_lazyload_excluded_src', 10, 2 ],
'rocket_lazyload_css_ignored_urls' => 'remove_svg_from_lazyload_css',
];
}
/**
* Replace CSS images by the lazyloaded version.
*
* @param string $html page HTML.
* @return string
*/
public function maybe_replace_css_images( string $html ): string {
if ( ! $this->context->is_allowed() ) {
return $html;
}
$this->logger::debug(
'Starting lazyload',
$this->generate_log_context(
[
'data' => $html,
]
)
);
/**
* Generate lazyload CSS for the page.
*
* @param array $data Data passed to generate the lazyload CSS.
*/
$output = apply_filters(
'rocket_generate_lazyloaded_css',
[
'html' => $html,
]
);
if ( ! is_array( $output ) || ! key_exists( 'html', $output ) ) {
$this->logger::debug(
'Lazyload bailed out',
$this->generate_log_context(
[
'data' => $html,
]
)
);
return $html;
}
$this->logger::debug(
'Ending lazyload',
$this->generate_log_context(
[
'data' => $html,
]
)
);
return $output['html'];
}
/**
* Clear the lazyload CSS files.
*
* @return void
*/
public function clear_generated_css() {
$this->logger::debug(
'Clear lazy CSS',
$this->generate_log_context()
);
$this->cache->clear();
}
/**
* Insert the lazyload script.
*
* @return void
*/
public function insert_lazyload_script() {
if ( ! $this->context->is_allowed() ) {
return;
}
/**
* Filters the threshold at which lazyload is triggered
*
* @since 1.2
*
* @param int $threshold Threshold value.
*/
$threshold = (int) apply_filters( 'rocket_lazyload_threshold', 300 );
$script_path = rocket_get_constant( 'WP_ROCKET_ASSETS_JS_PATH' ) . 'lazyload-css.min.js';
if ( ! $this->filesystem->exists( $script_path ) ) {
return;
}
$content = $this->filesystem->get_contents( $script_path );
if ( ! $content ) {
return;
}
wp_register_script( 'rocket_lazyload_css', '', [], false, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NoExplicitVersion
wp_enqueue_script( 'rocket_lazyload_css' );
wp_add_inline_script( 'rocket_lazyload_css', $content, 'after' );
wp_localize_script(
'rocket_lazyload_css',
'rocket_lazyload_css_data',
[
'threshold' => $threshold,
]
);
}
/**
* Create the lazyload file for CSS files.
*
* @param array $data Data sent.
* @return array
*/
public function create_lazy_css_files( array $data ): array {
if ( ! key_exists( 'html', $data ) || ! key_exists( 'css_files', $data ) ) {
$this->logger::debug(
'Create lazy css files bailed out',
$this->generate_log_context(
[
'data' => $data,
]
)
);
return $data;
}
$html = $data['html'];
$html = $this->replace_html_comments( $html );
$mapping = [];
$css_files = array_unique( $data['css_files'] );
$protected_content = $this->protect_css_urls( $html, $css_files );
$html = $protected_content->get_content();
$css_files_mapping = $protected_content->get_protected_files_mapping();
foreach ( $css_files as $url ) {
if ( $this->is_excluded( $url ) ) {
$this->logger::debug(
"Excluded lazy css files $url",
$this->generate_log_context()
);
continue;
}
$url_key = $this->format_url( $url );
if ( ! $this->cache->has( $url_key ) ) {
$this->logger::debug(
"Generate lazy css files $url",
$this->generate_log_context()
);
$file_mapping = $this->generate_css_file( $url );
if ( empty( $file_mapping ) ) {
$this->logger::debug(
"Create lazy css files $url bailed out",
$this->generate_log_context()
);
continue;
}
$mapping = array_merge( $mapping, $file_mapping );
} else {
$this->logger::debug(
"Load lazy css files $url",
$this->generate_log_context()
);
$mapping = array_merge( $mapping, $this->load_existing_mapping( $url ) );
}
$cached_url = $this->generate_asset_url( $url );
$html = str_replace( $css_files_mapping[ $url ], $cached_url, $html );
}
foreach ( $css_files_mapping as $url => $placeholder ) {
$html = str_replace( $placeholder, $url, $html );
}
$html = $this->restore_html_comments( $html );
$data['html'] = $html;
if ( ! key_exists( 'lazyloaded_images', $data ) ) {
$data['lazyloaded_images'] = [];
}
$data['lazyloaded_images'] = array_merge( $data['lazyloaded_images'], $mapping );
$data['lazyloaded_images'] = array_unique( $data['lazyloaded_images'], SORT_REGULAR );
return $data;
}
/**
* Add the lazy tag to the current HTML.
*
* @param array $data Data sent.
* @return array
*/
public function add_lazy_tag( array $data ): array {
if ( ! key_exists( 'html', $data ) || ! key_exists( 'lazyloaded_images', $data ) ) {
$this->logger::debug(
'Add lazy tag bailed out',
$this->generate_log_context(
[
'data' => $data,
]
)
);
return $data;
}
$lazyload_images = $data['lazyloaded_images'];
/**
* Lazyload background CSS excluded urls.
*
* @param array $excluded Excluded URLs.
* @param array $urls List of Urls processed.
*/
$loaded = apply_filters( 'rocket_css_image_lazyload_images_load', [], $lazyload_images );
$tags = $this->tag_generator->generate( $lazyload_images, $loaded );
$this->logger::debug(
'Add lazy tag generated',
$this->generate_log_context(
[
'data' => $tags,
]
)
);
$data['html'] = str_replace( '</head>', "$tags</head>", $data['html'] );
return $data;
}
/**
* Generate lazy CSS for a file.
*
* @param string $url Url from the CSS.
* @return array
*/
protected function generate_css_file( string $url ) {
$path = $this->file_resolver->resolve( $url );
if ( ! $path ) {
$path = $url;
}
$content = $this->fetcher->fetch( $path, $this->cache->generate_path( $url ) );
if ( ! $content ) {
return [];
}
$output = $this->generate_content( $content );
if ( count( $output->get_urls() ) === 0 ) {
return [];
}
if ( ! $this->cache->set( $this->format_url( $url ), $output->get_content() ) ) {
return [];
}
$this->cache->set( $this->get_mapping_file_url( $url ), json_encode( $output->get_urls() ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
return $output->get_urls();
}
/**
* Generate lazy content for a certain content.
*
* @param string $content Content to generate lazy for.
* @return LazyloadedContent
*/
protected function generate_content( string $content ): LazyloadedContent {
$urls = $this->extractor->extract( $content );
$formatted_urls = [];
foreach ( $urls as $url_tags ) {
$url_tags = $this->add_hashes( $url_tags );
$content = $this->rule_formatter->format( $content, $url_tags );
$formatted_urls = array_merge( $formatted_urls, $this->mapping_formatter->format( $url_tags ) );
}
return $this->lazyloaded_content_factory->make_lazyloaded_content( $formatted_urls, $content );
}
/**
* Load existing mapping for a URL.
*
* @param string $url Url we load mapping for.
* @return array
*/
protected function load_existing_mapping( string $url ) {
$content = $this->cache->get( $this->get_mapping_file_url( $url ) );
$urls = json_decode( $content, true );
if ( ! $urls ) {
return [];
}
return $urls;
}
/**
* Create the lazyload file for inline CSS.
*
* @param array $data Data sent.
* @return array
*/
public function create_lazy_inline_css( array $data ): array {
if ( ! key_exists( 'html', $data ) || ! key_exists( 'css_inline', $data ) ) {
$this->logger::debug(
'Create lazy css inline bailed out',
$this->generate_log_context(
[
'data' => $data,
]
)
);
return $data;
}
$html = $data['html'];
if ( ! key_exists( 'lazyloaded_images', $data ) ) {
$data['lazyloaded_images'] = [];
}
foreach ( $data['css_inline'] as $content ) {
$output = $this->generate_content( $content );
$html = str_replace( $content, $output->get_content(), $html );
$data['lazyloaded_images'] = array_merge( $data['lazyloaded_images'], $output->get_urls() );
}
$data['html'] = $html;
return $data;
}
/**
* Format a URL.
*
* @param string $url URL to format.
* @return string
*/
protected function format_url( string $url ): string {
return strtok( $url, '?' );
}
/**
* Check of the string is excluded.
*
* @param string $string String to check.
* @return bool
*/
protected function is_excluded( string $string ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound
$values = [
$string,
];
$parsed_url_host = wp_parse_url( $string, PHP_URL_HOST );
if ( ! $parsed_url_host ) {
$values [] = rocket_get_home_url() . $string;
}
/**
* Filters the src used to prevent lazy load from being applied.
*
* @param array $excluded_src An array of excluded src.
*/
$excluded_values = apply_filters( 'rocket_lazyload_excluded_src', [] );
if ( ! is_array( $excluded_values ) ) {
$excluded_values = (array) $excluded_values;
}
if ( empty( $excluded_values ) ) {
return false;
}
foreach ( $values as $value ) {
foreach ( $excluded_values as $excluded_value ) {
if ( strpos( $value, $excluded_value ) !== false ) {
return true;
}
}
}
return false;
}
/**
* Is the feature activated.
*
* @return bool
*/
protected function is_activated(): bool {
return (bool) $this->options->get( 'lazyload_css_bg_img', false );
}
/**
* Add lazyload_excluded_src to excluded filters.
*
* @param array $excluded Excluded URLs.
* @param array $urls List of Urls processed.
* @return mixed
*/
public function exclude_rocket_lazyload_excluded_src( $excluded, $urls ) {
/**
* Filters the src used to prevent lazy load from being applied.
*
* @param array $excluded_src An array of excluded src.
*/
$excluded_values = apply_filters( 'rocket_lazyload_excluded_src', [] );
if ( ! is_array( $excluded_values ) ) {
$excluded_values = (array) $excluded_values;
}
if ( empty( $excluded_values ) ) {
return $excluded;
}
foreach ( $urls as $url ) {
foreach ( $excluded_values as $excluded_value ) {
if ( strpos( $url['selector'], $excluded_value ) !== false || strpos( $url['style'], $excluded_value ) !== false ) {
$excluded[] = $url;
break;
}
}
}
return $excluded;
}
/**
* Add hashes.
*
* @param array $tags Tags.
* @return array
*/
protected function add_hashes( array $tags ): array {
return array_map(
function ( $url_tag ) {
/**
* Lazyload CSS hash.
*
* @param string $hash Lazyload CSS hash.
*/
$url_tag['hash'] = apply_filters( 'rocket_lazyload_css_hash', wp_generate_uuid4(), $url_tag );
return $url_tag;
},
$tags
);
}
/**
* Return mapping file URL.
*
* @param string $url Resource URL.
* @return string
*/
protected function get_mapping_file_url( string $url ): string {
return $this->format_url( $url ) . '.json';
}
/**
* Add timestamp to URL.
*
* @param string $url Asset Url.
*
* @return string
*/
protected function generate_asset_url( string $url ): string {
$parsed_query = wp_parse_url( $url, PHP_URL_QUERY );
$queries = [];
if ( $parsed_query ) {
parse_str( $parsed_query, $queries );
}
$queries['wpr_t'] = current_time( 'timestamp' ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
$cached_url = $this->cache->generate_url( $this->format_url( $url ) );
$this->logger::debug(
"Generated url lazy css files $url",
$this->generate_log_context(
[
'data' => $cached_url,
]
)
);
return add_query_arg( $queries, $cached_url );
}
/**
* Generate the context for logs.
*
* @param array $data Data to pass to logs.
* @return array
*/
protected function generate_log_context( array $data = [] ): array {
return array_merge(
$data,
[
'type' => 'lazyload_css_bg_images',
]
);
}
/**
* Protect URL inside the content.
*
* @param string $content Content to protect.
* @param array $css_files CSS files from the content.
* @return ProtectedContent
*/
protected function protect_css_urls( string $content, array $css_files ): ProtectedContent {
usort(
$css_files,
function ( $url1, $url2 ) {
return strlen( $url1 ) < strlen( $url2 ) ? 1 : -1;
}
);
$css_files_mapping = [];
foreach ( $css_files as $url ) {
$placeholder = uniqid( 'url_bg_css_' );
$content = str_replace( $url, $placeholder, $content );
$css_files_mapping[ $url ] = $placeholder;
}
return $this->lazyloaded_content_factory->make_protected_content( $css_files_mapping, $content );
}
/**
* Exclude SVG from lazy loaded images.
*
* @param array $urls URLs to exclude.
* @return array
*/
public function remove_svg_from_lazyload_css( array $urls ): array {
$urls[] = 'data:image/svg+xml';
return $urls;
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Media\Lazyload;
trait CanLazyloadTrait {
/**
* Checks if lazyload should be applied
*
* @since 3.3
*
* @return bool
*/
protected function should_lazyload() {
if (
rocket_get_constant( 'REST_REQUEST', false )
||
rocket_get_constant( 'DONOTLAZYLOAD', false )
||
rocket_get_constant( 'DONOTROCKETOPTIMIZE', false )
||
rocket_get_constant( 'DONOTCACHEPAGE', false )
) {
return false;
}
if (
is_admin()
||
is_feed()
||
is_preview()
) {
return false;
}
if (
is_search()
&&
// This filter is documented in inc/classes/Buffer/class-tests.php.
! (bool) apply_filters( 'rocket_cache_search', false )
) {
return false;
}
// Exclude Page Builders editors.
$excluded_parameters = [
'fl_builder',
'et_fb',
'ct_builder',
];
foreach ( $excluded_parameters as $excluded ) {
if ( isset( $_GET[ $excluded ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return false;
}
}
return true;
}
}
@@ -0,0 +1,529 @@
<?php
namespace WP_Rocket\Engine\Media\Lazyload;
use WP_Rocket\Dependencies\Minify\JS;
use WP_Rocket\Dependencies\RocketLazyload\Assets;
use WP_Rocket\Dependencies\RocketLazyload\Image;
use WP_Rocket\Dependencies\RocketLazyload\Iframe;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Lazyload Subscriber
*
* @since 3.3
*/
class Subscriber implements Subscriber_Interface {
use RegexTrait;
use CanLazyloadTrait;
const SCRIPT_VERSION = '17.8.3';
/**
* Options_Data instance
*
* @var Options_Data
*/
private $options;
/**
* Assets instance
*
* @var Assets
*/
private $assets;
/**
* Image instance
*
* @var Image
*/
private $image;
/**
* Iframe instance
*
* @var Iframe
*/
private $iframe;
/**
* Constructor
*
* @since 3.3
*
* @param Options_Data $options Options_Data instance.
* @param Assets $assets Assets instance.
* @param Image $image Image instance.
* @param Iframe $iframe Iframe instance.
*/
public function __construct( Options_Data $options, Assets $assets, Image $image, Iframe $iframe ) {
$this->options = $options;
$this->assets = $assets;
$this->image = $image;
$this->iframe = $iframe;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.3
*
* @return array
*/
public static function get_subscribed_events() {
return [
'wp_footer' => [
[ 'insert_lazyload_script', PHP_INT_MAX ],
[ 'insert_youtube_thumbnail_script', PHP_INT_MAX ],
],
'wp_head' => [ 'insert_nojs_style', PHP_INT_MAX ],
'wp_enqueue_scripts' => [ 'insert_youtube_thumbnail_style', PHP_INT_MAX ],
'rocket_buffer' => [ 'lazyload', 18 ],
'rocket_lazyload_html' => 'lazyload_responsive',
'init' => 'lazyload_smilies',
'wp' => 'deactivate_lazyload_on_specific_posts',
'wp_lazy_loading_enabled' => [ 'maybe_disable_core_lazyload', 10, 2 ],
'rocket_lazyload_excluded_attributes' => 'add_exclusions',
'rocket_lazyload_excluded_src' => 'add_exclusions',
'rocket_lazyload_iframe_excluded_patterns' => 'add_exclusions',
];
}
/**
* Inserts the lazyload script in the footer
*
* @since 3.3
*
* @return void
*/
public function insert_lazyload_script() {
if ( ! $this->can_lazyload_images() && ! $this->can_lazyload_iframes() ) {
return;
}
if ( ! $this->should_lazyload() ) {
return;
}
$script_args = [
'base_url' => rocket_get_constant( 'WP_ROCKET_ASSETS_JS_URL' ) . 'lazyload/',
'version' => self::SCRIPT_VERSION,
];
$this->add_inline_script();
$this->assets->insertLazyloadScript( $script_args );
}
/**
* Adds the inline lazyload script
*
* @since 3.6
*
* @return void
*/
private function add_inline_script() {
$inline_script = $this->assets->getInlineLazyloadScript( $this->set_inline_script_args() );
if ( ! rocket_get_constant( 'SCRIPT_DEBUG' ) ) {
$inline_script = $this->minify_script( $inline_script );
}
echo '<script>' . $inline_script . '</script>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Dynamic content is properly escaped in the view.
}
/**
* Sets the arguments array for the inline lazyload script
*
* @since 3.6
*
* @return array
*/
private function set_inline_script_args() {
/**
* Filters the threshold at which lazyload is triggered
*
* @since 1.2
*
* @param int $threshold Threshold value.
*/
$threshold = (int) apply_filters( 'rocket_lazyload_threshold', 300 );
$inline_args = [
'threshold' => $threshold,
];
/**
* Filters the use of native lazyload
*
* @since 3.4
*
* @param bool $use_native True to use native lazyload, false otherwise.
*/
if ( (bool) apply_filters( 'rocket_use_native_lazyload', false ) ) {
$inline_args['options']['use_native'] = true;
$inline_args['elements']['loading'] = '[loading=lazy]';
}
if ( $this->options->get( 'lazyload', 0 ) ) {
if ( ! $this->is_native_images() ) {
$inline_args['elements']['image'] = 'img[data-lazy-src]';
}
$inline_args['elements']['background_image'] = '.rocket-lazyload';
}
if ( (bool) $this->options->get( 'lazyload_iframes', 0 ) ) {
$inline_args['elements']['iframe'] = 'iframe[data-lazy-src]';
}
/**
* Filters the arguments array for the lazyload script options
*
* @since 3.3
*
* @param array $inline_args Arguments used for the lazyload script options.
*/
return (array) apply_filters( 'rocket_lazyload_script_args', $inline_args );
}
/**
* Minifies the inline script
*
* @since 3.6
*
* @param string $script Inline script to minify.
* @return string
*/
private function minify_script( $script ) {
$minify = new JS( $script );
return $minify->minify();
}
/**
* Inserts the Youtube thumbnail script in the footer
*
* @since 3.3
*
* @return void
*/
public function insert_youtube_thumbnail_script() {
if ( ! $this->options->get( 'lazyload_youtube' ) || ! $this->can_lazyload_iframes() ) {
return;
}
if ( ! $this->should_lazyload() ) {
return;
}
/**
* Filters the resolution of the YouTube thumbnail
*
* @since 1.4.8
* @deprecated 3.3
*
* @param string $thumbnail_resolution The resolution of the thumbnail. Accepted values: default, mqdefault, hqdefault, sddefault, maxresdefault
*/
$thumbnail_resolution = apply_filters_deprecated( 'rocket_youtube_thumbnail_resolution', [ 'hqdefault' ], '3.3', 'rocket_lazyload_youtube_thumbnail_resolution' );
/**
* Filters the resolution of the YouTube thumbnail
*
* @since 1.4.8
*
* @param string $thumbnail_resolution The resolution of the thumbnail. Accepted values: default, mqdefault, hqdefault, sddefault, maxresdefault
*/
$thumbnail_resolution = apply_filters( 'rocket_lazyload_youtube_thumbnail_resolution', $thumbnail_resolution );
/**
* Extension from the thumbnail from Youtube video.
*
* @param string $extension extension from the thumbnail from Youtube video.
* @returns string
*/
$extension = apply_filters( 'rocket_lazyload_youtube_thumbnail_extension', 'jpg' );
if ( ! is_string( $extension ) || ! in_array( $extension, [ 'jpg', 'webp' ], true ) ) {
$extension = 'jpg';
}
$this->assets->insertYoutubeThumbnailScript(
[
'resolution' => $thumbnail_resolution,
'lazy_image' => (bool) $this->options->get( 'lazyload' ),
'native' => $this->is_native_images(),
'extension' => $extension,
]
);
}
/**
* Inserts the no JS CSS compatibility in the header
*
* @since 3.3
*
* @return void
*/
public function insert_nojs_style() {
if ( ! $this->should_lazyload() ) {
return;
}
if ( ! $this->can_lazyload_images() && ! $this->can_lazyload_iframes() ) {
return;
}
if ( ! $this->options->get( 'lazyload' ) && ! $this->options->get( 'lazyload_iframes' ) ) {
return;
}
$this->assets->insertNoJSCSS();
}
/**
* Inserts the Youtube thumbnail CSS in the header
*
* @since 3.3
*
* @return void
*/
public function insert_youtube_thumbnail_style() {
if ( ! $this->options->get( 'lazyload_youtube' ) || ! $this->can_lazyload_iframes() ) {
return;
}
if ( ! $this->should_lazyload() ) {
return;
}
$this->assets->insertYoutubeThumbnailCSS(
[
'base_url' => WP_ROCKET_ASSETS_URL,
'responsive_embeds' => current_theme_supports( 'responsive-embeds' ),
]
);
}
/**
* Applies lazyload on the provided content
*
* @since 3.3
*
* @param string $html HTML content.
* @return string
*/
public function lazyload( $html ) {
if ( ! $this->should_lazyload() ) {
return $html;
}
$buffer = $this->hide_scripts( $html );
$buffer = $this->hide_noscripts( $buffer );
if ( $this->can_lazyload_iframes() ) {
$args = [
'youtube' => $this->options->get( 'lazyload_youtube' ),
];
$html = $this->iframe->lazyloadIframes( $html, $buffer, $args );
}
if ( $this->can_lazyload_images() ) {
if ( ! $this->is_native_images() ) {
$html = $this->image->lazyloadPictures( $html, $buffer );
$buffer = $this->hide_scripts( $html );
$buffer = $this->hide_noscripts( $buffer );
}
$html = $this->image->lazyloadImages( $html, $buffer, $this->is_native_images() );
/**
* Filters the application of lazyload on background images
*
* @since 3.3
*
* @param bool $lazyload True to apply, false otherwise.
*/
if ( apply_filters( 'rocket_lazyload_background_images', true ) ) {
$html = $this->image->lazyloadBackgroundImages( $html, $buffer );
}
}
return $html;
}
/**
* Applies lazyload on responsive images attributes srcset and sizes
*
* @since 3.3
*
* @param string $html Image HTML.
* @return string
*/
public function lazyload_responsive( $html ) {
if ( $this->is_native_images() ) {
return $html;
}
return $this->image->lazyloadResponsiveAttributes( $html );
}
/**
* Applies lazyload on WordPress smilies
*
* @since 3.3
*
* @return void
*/
public function lazyload_smilies() {
if ( ! $this->should_lazyload() ) {
return;
}
if ( ! $this->options->get( 'lazyload' ) ) {
return;
}
$filters = [
'the_content' => 10,
'the_excerpt' => 10,
'comment_text' => 20,
];
foreach ( $filters as $filter => $prio ) {
if ( ! has_filter( $filter ) ) {
continue;
}
remove_filter( $filter, 'convert_smilies', $prio );
add_filter( $filter, [ $this->image, 'convertSmilies' ], $prio );
}
}
/**
* Prevents lazyload if the option is unchecked on the WP Rocket options metabox for a post
*
* @since 3.3
*
* @return void
*/
public function deactivate_lazyload_on_specific_posts() {
if ( is_rocket_post_excluded_option( 'lazyload' ) ) {
add_filter( 'do_rocket_lazyload', '__return_false' );
}
if ( is_rocket_post_excluded_option( 'lazyload_iframes' ) ) {
add_filter( 'do_rocket_lazyload_iframes', '__return_false' );
}
}
/**
* Disable WP core lazyload if our images lazyload is active
*
* @since 3.5
*
* @param bool $value Current value for the enabling variable.
* @param string $tag_name The tag name.
*
* @return bool
*/
public function maybe_disable_core_lazyload( $value, $tag_name ) {
if ( false === $value ) {
return $value;
}
if ( 'img' === $tag_name ) {
return ! (bool) $this->can_lazyload_images();
}
if ( 'iframe' === $tag_name ) {
return ! (bool) $this->can_lazyload_iframes();
}
return $value;
}
/**
* Adds the exclusions from the options to the exclusions arrays
*
* @since 3.8
*
* @param array $exclusions Array of excluded patterns.
* @return array
*/
public function add_exclusions( array $exclusions ): array {
$exclude_lazyload = $this->options->get( 'exclude_lazyload', [] );
if ( empty( $exclude_lazyload ) ) {
return $exclusions;
}
return array_unique( array_merge( $exclusions, $exclude_lazyload ) );
}
/**
* Checks if we can lazyload images.
*
* @since 3.3
*
* @return boolean
*/
private function can_lazyload_images() {
if ( ! $this->options->get( 'lazyload', 0 ) ) {
return false;
}
/**
* Filters the lazyload application on images
*
* @since 2.0
*
* @param bool $do_rocket_lazyload True to apply lazyload, false otherwise.
*/
return apply_filters( 'do_rocket_lazyload', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
}
/**
* Checks if we can lazyload iframes
*
* @since 3.3
*
* @return boolean
*/
private function can_lazyload_iframes() {
if ( ! $this->options->get( 'lazyload_iframes', 0 ) ) {
return false;
}
/**
* Filters the lazyload application on iframes
*
* @since 2.0
*
* @param bool $do_rocket_lazyload_iframes True to apply lazyload, false otherwise.
*/
return apply_filters( 'do_rocket_lazyload_iframes', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
}
/**
* Checks if native lazyload is enabled for images
*
* @since 3.10.2
*
* @return bool
*/
private function is_native_images(): bool {
/**
* Filters the use of native lazyload for images
*
* @since 3.10.2
*
* @param bool $use_native True to use native lazyload for images, false otherwise.
*/
return (bool) apply_filters( 'rocket_use_native_lazyload_images', false );
}
}
@@ -0,0 +1,74 @@
<?php
namespace WP_Rocket\Engine\Media;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Dependencies\RocketLazyload\Assets;
use WP_Rocket\Dependencies\RocketLazyload\Iframe;
use WP_Rocket\Dependencies\RocketLazyload\Image;
use WP_Rocket\Engine\Media\Emojis\EmojisSubscriber;
use WP_Rocket\Engine\Media\ImageDimensions\AdminSubscriber as ImageDimensionsAdminSubscriber;
use WP_Rocket\Engine\Media\ImageDimensions\ImageDimensions;
use WP_Rocket\Engine\Media\ImageDimensions\Subscriber as ImageDimensionsSubscriber;
use WP_Rocket\Engine\Media\Lazyload\AdminSubscriber as LazyloadAdminSubscriber;
use WP_Rocket\Engine\Media\Lazyload\Subscriber;
/**
* Service provider for Media module
*
* @since 3.6
*/
class ServiceProvider extends AbstractServiceProvider {
/**
* The provides array is a way to let the container
* know that a service is provided by this service
* provider. Every service that is registered via
* this service provider must have an alias added
* to this array or it will be ignored.
*
* @var array
*/
protected $provides = [
'lazyload_assets',
'lazyload_image',
'lazyload_iframe',
'lazyload_subscriber',
'lazyload_admin_subscriber',
'emojis_subscriber',
'image_dimensions',
'image_dimensions_subscriber',
'image_dimensions_admin_subscriber',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$options = $this->getContainer()->get( 'options' );
$this->getContainer()->add( 'lazyload_assets', Assets::class );
$this->getContainer()->add( 'lazyload_image', Image::class );
$this->getContainer()->add( 'lazyload_iframe', Iframe::class );
$this->getContainer()->share( 'lazyload_subscriber', Subscriber::class )
->addArgument( $options )
->addArgument( $this->getContainer()->get( 'lazyload_assets' ) )
->addArgument( $this->getContainer()->get( 'lazyload_image' ) )
->addArgument( $this->getContainer()->get( 'lazyload_iframe' ) )
->addTag( 'lazyload_subscriber' );
$this->getContainer()->share( 'lazyload_admin_subscriber', LazyloadAdminSubscriber::class )
->addTag( 'admin_subscriber' );
$this->getContainer()->share( 'emojis_subscriber', EmojisSubscriber::class )
->addArgument( $options )
->addTag( 'front_subscriber' );
$this->getContainer()->add( 'image_dimensions', ImageDimensions::class )
->addArgument( $options );
$this->getContainer()->share( 'image_dimensions_subscriber', ImageDimensionsSubscriber::class )
->addArgument( $this->getContainer()->get( 'image_dimensions' ) )
->addTag( 'front_subscriber' );
$this->getContainer()->share( 'image_dimensions_admin_subscriber', ImageDimensionsAdminSubscriber::class )
->addArgument( $this->getContainer()->get( 'image_dimensions' ) )
->addTag( 'admin_subscriber' );
}
}