Subscriber.php 12.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
<?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;

	const SCRIPT_VERSION = '17.5';

	/**
	 * 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 );

		$this->assets->insertYoutubeThumbnailScript(
			[
				'resolution' => $thumbnail_resolution,
				'lazy_image' => (bool) $this->options->get( 'lazyload' ),
				'native'     => $this->is_native_images(),
			]
		);
	}

	/**
	 * 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' ),
			]
		);
	}

	/**
	 * Checks if lazyload should be applied
	 *
	 * @since 3.3
	 *
	 * @return bool
	 */
	private function should_lazyload() {
		if (
			rocket_get_constant( 'REST_REQUEST', false )
			||
			rocket_get_constant( 'DONOTLAZYLOAD', false )
			||
			rocket_get_constant( 'DONOTROCKETOPTIMIZE', 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;
	}

	/**
	 * 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 );
	}
}