Combine.php 11.6 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
<?php
namespace WP_Rocket\Engine\Optimization\Minify\JS;

use WP_Rocket\Dependencies\Minify\JS as MinifyJS;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\AssetsLocalCache;
use WP_Rocket\Engine\Optimization\DeferJS\DeferJS;
use WP_Rocket\Engine\Optimization\Minify\ProcessorInterface;
use WP_Rocket\Logger\Logger;

/**
 * Combines JS files
 *
 * @since 3.1
 */
class Combine extends AbstractJSOptimization implements ProcessorInterface {
	/**
	 * Minifier instance
	 *
	 * @since 3.1
	 *
	 * @var MinifyJS
	 */
	private $minifier;

	/**
	 * Excluded defer JS pattern
	 *
	 * @since 3.8
	 *
	 * @var string
	 */
	private $excluded_defer_js;

	/**
	 * Scripts to combine
	 *
	 * @since 3.1
	 *
	 * @var array
	 */
	private $scripts = [];

	/**
	 * Inline scripts excluded from combined and moved after the combined file
	 *
	 * @since 3.1.4
	 *
	 * @var array
	 */
	private $move_after = [];

	/**
	 * Constructor
	 *
	 * @since 3.1
	 *
	 * @param Options_Data     $options     Plugin options instance.
	 * @param MinifyJS         $minifier    Minifier instance.
	 * @param AssetsLocalCache $local_cache Assets local cache instance.
	 * @param DeferJS          $defer_js    Defer JS instance.
	 */
	public function __construct( Options_Data $options, MinifyJS $minifier, AssetsLocalCache $local_cache, DeferJS $defer_js ) {
		parent::__construct( $options, $local_cache );

		$this->minifier          = $minifier;
		$this->excluded_defer_js = implode( '|', $defer_js->get_excluded() );
	}

	/**
	 * Minifies and combines JavaScripts into one
	 *
	 * @since 3.1
	 *
	 * @param string $html HTML content.
	 * @return string
	 */
	public function optimize( $html ) {
		Logger::info( 'JS COMBINE PROCESS STARTED.', [ 'js combine process' ] );

		$html_nocomments = $this->hide_comments( $html );
		$scripts         = $this->find( '<script.*<\/script>', $html_nocomments );

		if ( ! $scripts ) {
			Logger::debug( 'No `<script>` tags found.', [ 'js combine process' ] );
			return $html;
		}

		Logger::debug(
			'Found ' . count( $scripts ) . ' `<script>` tag(s).',
			[
				'js combine process',
				'tags' => $scripts,
			]
		);

		$combine_scripts = $this->parse( $scripts );

		if ( empty( $combine_scripts ) ) {
			Logger::debug( 'No `<script>` tags to optimize.', [ 'js combine process' ] );
			return $html;
		}

		Logger::debug(
			count( $combine_scripts ) . ' `<script>` tag(s) remaining.',
			[
				'js combine process',
				'tags' => $combine_scripts,
			]
		);

		$content = $this->get_content();

		if ( empty( $content ) ) {
			Logger::debug( 'No JS content.', [ 'js combine process' ] );
			return $html;
		}

		$minify_url = $this->combine( $content );

		if ( ! $minify_url ) {
			Logger::error( 'JS combine process failed.', [ 'js combine process' ] );
			return $html;
		}

		$move_after = '';

		if ( ! empty( $this->move_after ) ) {
			foreach ( $this->move_after as $script ) {
				$move_after .= $script;
				$html        = str_replace( $script, '', $html );
			}
		}

		// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
		$html = str_replace( '</body>', '<script src="' . esc_url( $minify_url ) . '" data-minify="1"></script>' . $move_after . '</body>', $html );

		foreach ( $combine_scripts as $script ) {
			$html = str_replace( $script[0], '', $html );
		}

		Logger::info(
			'Combined JS file successfully added.',
			[
				'js combine process',
				'url' => $minify_url,
			]
		);

		return $html;
	}

	/**
	 * Parses found nodes to keep only the ones to combine
	 *
	 * @since 3.1
	 *
	 * @param Array $scripts scripts corresponding to JS file or content.
	 * @return array
	 */
	protected function parse( $scripts ) {
		$excluded_externals = implode( '|', $this->get_excluded_external_file_path() );
		$scripts            = array_map(
			function( $script ) use ( $excluded_externals ) {
				preg_match( '/<script\s+([^>]+[\s\'"])?src\s*=\s*[\'"]\s*?(?<url>[^\'"]+\.js(?:\?[^\'"]*)?)\s*?[\'"]([^>]+)?\/?>/Umsi', $script[0], $matches );

				if ( isset( $matches['url'] ) ) {
					if ( $this->is_external_file( $matches['url'] ) ) {
						if ( preg_match( '#(' . $excluded_externals . ')#', $matches['url'] ) ) {
							Logger::debug(
								'Script is external.',
								[
									'js combine process',
									'tag' => $matches[0],
								]
							);
							return;
						}

						if ( $this->is_defer_excluded( $matches['url'] ) ) {
							return;
						}

						$this->scripts[] = [
							'type'    => 'url',
							'content' => $matches['url'],
						];

						return $script;
					}

					if ( $this->is_minify_excluded_file( $matches ) ) {
						Logger::debug(
							'Script is excluded.',
							[
								'js combine process',
								'tag' => $matches[0],
							]
						);
						return;
					}

					if ( $this->is_defer_excluded( $matches['url'] ) ) {
						return;
					}

					$file_path = $this->get_file_path( strtok( $matches['url'], '?' ) );

					if ( ! $file_path ) {
						return;
					}

					$this->scripts[] = [
						'type'    => 'file',
						'content' => $file_path,
					];
				} else {
					preg_match( '/<script\b(?<attrs>[^>]*)>(?:\/\*\s*<!\[CDATA\[\s*\*\/)?\s*(?<content>[\s\S]*?)\s*(?:\/\*\s*\]\]>\s*\*\/)?<\/script>/msi', $script[0], $matches_inline );

					$matches_inline = array_merge(
						[
							'attrs'   => '',
							'content' => '',
						],
						$matches_inline
					);

					if ( preg_last_error() === PREG_BACKTRACK_LIMIT_ERROR ) {
						Logger::debug(
							'PCRE regex execution Catastrophic Backtracking',
							[
								'inline JS backtracking error',
								'content' => $matches_inline['content'],
							]
						);
						return;
					}

					if ( strpos( $matches_inline['attrs'], 'type' ) !== false && ! preg_match( '/type\s*=\s*["\']?(?:text|application)\/(?:(?:x\-)?javascript|ecmascript)["\']?/i', $matches_inline['attrs'] ) ) {
						Logger::debug(
							'Inline script is not JS.',
							[
								'js combine process',
								'attributes' => $matches_inline['attrs'],
							]
						);
						return;
					}

					if ( false !== strpos( $matches_inline['attrs'], 'src=' ) ) {
						Logger::debug(
							'Inline script has a `src` attribute.',
							[
								'js combine process',
								'attributes' => $matches_inline['attrs'],
							]
						);
						return;
					}

					if ( in_array( $matches_inline['content'], $this->get_localized_scripts(), true ) ) {
						Logger::debug(
							'Inline script is a localize script',
							[
								'js combine process',
								'excluded_content' => $matches_inline['content'],
							]
						);
						return;
					}

					if ( $this->is_delayed_script( $matches_inline['attrs'] ) ) {
						return;
					}

					foreach ( $this->get_excluded_inline_content() as $excluded_content ) {
						if ( false !== strpos( $matches_inline['content'], $excluded_content ) ) {
							Logger::debug(
								'Inline script has excluded content.',
								[
									'js combine process',
									'excluded_content' => $excluded_content,
								]
							);
							return;
						}
					}

					foreach ( $this->get_move_after_inline_scripts() as $move_after_script ) {
						if ( false !== strpos( $matches_inline['content'], $move_after_script ) ) {
							$this->move_after[] = $script[0];
							return;
						}
					}

					$this->scripts[] = [
						'type'    => 'inline',
						'content' => $matches_inline['content'],
					];
				}

				return $script;
			},
			$scripts
		);

		return array_filter( $scripts );
	}

	/**
	 * Gets content for each script either from inline or from src
	 *
	 * @since 3.1
	 *
	 * @return string
	 */
	protected function get_content() {
		$content = '';

		foreach ( $this->scripts as $script ) {
			if ( 'file' === $script['type'] ) {
				$file_content = $this->get_file_content( $script['content'] );
				$content     .= $file_content;

				$this->add_to_minify( $file_content );
			} elseif ( 'url' === $script['type'] ) {
				$file_content = $this->local_cache->get_content( rocket_add_url_protocol( $script['content'] ) );
				$content     .= $file_content;

				$this->add_to_minify( $file_content );
			} elseif ( 'inline' === $script['type'] ) {
				$inline_js = rtrim( $script['content'], ";\n\t\r" ) . ';';
				$content  .= $inline_js;

				$this->add_to_minify( $inline_js );
			}
		}

		return $content;
	}

	/**
	 * Creates the minify URL if the minification is successful
	 *
	 * @since 2.11
	 *
	 * @param string $content Content to minify & combine.

	 * @return string|bool The minify URL if successful, false otherwise
	 */
	protected function combine( $content ) {
		if ( empty( $content ) ) {
			return false;
		}

		$filename      = md5( $content . $this->minify_key ) . '.js';
		$minified_file = $this->minify_base_path . $filename;
		if ( ! rocket_direct_filesystem()->is_readable( $minified_file ) ) {
			$minified_content = $this->minify();

			if ( ! $minified_content ) {
				return false;
			}

			$minify_filepath = $this->write_file( $minified_content, $minified_file );

			if ( ! $minify_filepath ) {
				return false;
			}
		}

		return $this->get_minify_url( $filename );
	}

	/**
	 * Minifies the content
	 *
	 * @since 2.11
	 *
	 * @return string|bool Minified content, false if empty
	 */
	protected function minify() {
		$minified_content = $this->minifier->minify();

		if ( empty( $minified_content ) ) {
			return false;
		}

		return $minified_content;
	}

	/**
	 * Adds content to the minifier
	 *
	 * @since  3.1
	 *
	 * @param string $content Content to minify/combine.
	 * @return void
	 */
	protected function add_to_minify( $content ) {
		$this->minifier->add( $content );
	}

	/**
	 * Patterns in content excluded from being combined
	 *
	 * @since  3.1
	 *
	 * @return array
	 */
	protected function get_excluded_inline_content() {
		$excluded_inline = $this->options->get( 'exclude_inline_js', [] );

		/**
		 * Filters inline JS excluded from being combined
		 *
		 * @since 3.1
		 *
		 * @param array $pattern Patterns to match.
		 */
		return apply_filters( 'rocket_excluded_inline_js_content', $excluded_inline );
	}

	/**
	 * Patterns of inline JS to move after the combined JS file
	 *
	 * @since 3.1.4
	 *
	 * @return array
	 */
	protected function get_move_after_inline_scripts() {
		/**
		 * Filters inline JS to move after the combined JS file
		 *
		 * @since 3.1.4
		 *
		 * @param array $move_after_scripts Patterns to match.
		 */
		return apply_filters( 'rocket_move_after_combine_js', [] );
	}

	/**
	 * Gets all localized scripts data to exclude them from combine.
	 *
	 * @since 3.1.3
	 *
	 * @return array
	 */
	protected function get_localized_scripts() {
		static $localized_scripts;

		if ( isset( $localized_scripts ) ) {
			return $localized_scripts;
		}

		$localized_scripts = [];

		foreach ( array_unique( wp_scripts()->queue ) as $item ) {
			$data = wp_scripts()->print_extra_script( $item, false );

			if ( empty( $data ) ) {
				continue;
			}

			$localized_scripts[] = $data;
		}

		return $localized_scripts;
	}

	/**
	 * Is this script a delayed script or not.
	 *
	 * @since 3.7
	 *
	 * @param string $script_attributes Attributes beside the opening of script tag.
	 *
	 * @return bool True if it's a delayed script and false if not.
	 */
	private function is_delayed_script( $script_attributes ) {
		return false !== strpos( $script_attributes, 'data-rocketlazyloadscript=' );
	}

	/**
	 * Checks if the current URL is excluded from defer JS
	 *
	 * @since 3.8
	 *
	 * @param string $url URL to check.
	 * @return boolean
	 */
	private function is_defer_excluded( string $url ) : bool {
		if (
			! empty( $this->excluded_defer_js )
			&&
			preg_match( '#(' . $this->excluded_defer_js . ')#i', $url )
		) {
			Logger::debug(
				'Script is excluded from defer JS.',
				[
					'js combine process',
					'url' => $url,
				]
			);
			return true;
		}

		return false;
	}
}