add wp-rocket

This commit is contained in:
nguyen dung
2022-02-18 19:09:35 +07:00
parent 39b8cb3612
commit 3110d00ee7
927 changed files with 271703 additions and 2 deletions

View File

@@ -0,0 +1,148 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\CSS;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\AbstractOptimization;
use WP_Rocket\Engine\Optimization\AssetsLocalCache;
/**
* Abstract class for CSS Optimization
*
* @since 3.1
*/
abstract class AbstractCSSOptimization extends AbstractOptimization {
const FILE_TYPE = 'css';
/**
* Assets local cache instance
*
* @var AssetsLocalCache
*/
protected $local_cache;
/**
* Creates an instance of inheriting class.
*
* @since 3.1
*
* @param Options_Data $options Options instance.
* @param AssetsLocalCache $local_cache AssetsLocalCache instance.
*/
public function __construct( Options_Data $options, AssetsLocalCache $local_cache ) {
$this->options = $options;
$this->local_cache = $local_cache;
$this->minify_key = $this->options->get( 'minify_css_key', create_rocket_uniqid() );
$this->excluded_files = $this->get_excluded_files();
$this->init_base_path_and_url();
}
/**
* Get all files to exclude from minification/concatenation.
*
* @since 2.11
*
* @return string
*/
protected function get_excluded_files() {
$excluded_files = $this->options->get( 'exclude_css', [] );
/**
* Filters CSS files to exclude from minification/concatenation.
*
* @since 2.6
*
* @param array $excluded_files List of excluded CSS files.
*/
$excluded_files = (array) apply_filters( 'rocket_exclude_css', $excluded_files );
if ( empty( $excluded_files ) ) {
return '';
}
foreach ( $excluded_files as $i => $excluded_file ) {
$excluded_files[ $i ] = str_replace( '#', '\#', $excluded_file );
}
return implode( '|', $excluded_files );
}
/**
* Returns the CDN zones.
*
* @since 3.1
*
* @return array
*/
public function get_zones() {
return [ 'all', 'css_and_js', self::FILE_TYPE ];
}
/**
* Gets the minify URL
*
* @since 3.1
*
* @param string $filename Minified filename.
* @param string $original_url Original URL for this file. Optional.
*
* @return string
*/
protected function get_minify_url( $filename, $original_url = '' ) {
$minify_url = $this->minify_base_url . $filename;
/**
* Filters CSS file URL with CDN hostname
*
* @since 2.1
*
* @param string $minify_url Minified file URL.
* @param string $original_url Original URL for this file.
*/
return apply_filters( 'rocket_css_url', $minify_url, $original_url );
}
/**
* Determines if it is a file excluded from minification
*
* @since 2.11
*
* @param array $tag Tag corresponding to a CSS file.
*
* @return bool True if it is a file excluded, false otherwise
*/
protected function is_minify_excluded_file( array $tag ) {
if ( ! isset( $tag[0], $tag['url'] ) ) {
return true;
}
// File should not be minified.
if ( false !== strpos( $tag[0], 'data-minify=' ) || false !== strpos( $tag[0], 'data-no-minify=' ) ) {
return true;
}
if ( false !== strpos( $tag[0], 'media=' ) && ! preg_match( '/media=["\'](?:\s*|[^"\']*?\b(all|screen)\b[^"\']*?)["\']/i', $tag[0] ) ) {
return true;
}
if ( false !== strpos( $tag[0], 'only screen and' ) ) {
return true;
}
$file_path = wp_parse_url( $tag['url'], PHP_URL_PATH );
// File extension is not css.
if ( pathinfo( $file_path, PATHINFO_EXTENSION ) !== self::FILE_TYPE ) {
return true;
}
if ( ! empty( $this->excluded_files ) ) {
// File is excluded from minification/concatenation.
if ( preg_match( '#^(' . $this->excluded_files . ')$#', $file_path ) ) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\CSS;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Minify/Combine CSS Admin subscriber
*
* @since 3.5.4
*/
class AdminSubscriber implements Subscriber_Interface {
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.5.4
*
* @return array
*/
public static function get_subscribed_events() {
$slug = rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' );
return [
"update_option_{$slug}" => [ 'clean_minify', 10, 2 ],
"pre_update_option_{$slug}" => [ 'regenerate_minify_css_key', 10, 2 ],
];
}
/**
* Clean minify CSS files when options change.
*
* @since 3.5.4
*
* @param array $old An array of previous settings.
* @param array $new An array of submitted settings.
*/
public function clean_minify( $old, $new ) {
if ( ! is_array( $old ) || ! is_array( $new ) ) {
return;
}
if ( ! $this->maybe_minify_regenerate( $new, $old ) ) {
return;
}
// Purge all minify cache files.
rocket_clean_minify( 'css' );
}
/**
* Regenerate the minify key if CSS files have been modified.
*
* @since 3.5.4
*
* @param array $new An array of submitted settings.
* @param array $old An array of previous settings.
*
* @return array Updates 'minify_css_key' setting when regenerated; else, original submitted settings.
*/
public function regenerate_minify_css_key( $new, $old ) {
if ( ! is_array( $old ) || ! is_array( $new ) ) {
return $new;
}
if ( ! $this->maybe_minify_regenerate( $new, $old ) ) {
return $new;
}
$new['minify_css_key'] = create_rocket_uniqid();
return $new;
}
/**
* Checks minify CSS condition when options change.
*
* @since 3.5.4
*
* @param array $new An array of submitted settings.
* @param array $old An array of previous settings.
*
* @return bool true when should regenerate; else false.
*/
protected function maybe_minify_regenerate( array $new, array $old ) {
$settings_to_check = [
'minify_css',
'exclude_css',
'cdn',
];
foreach ( $settings_to_check as $setting ) {
if ( $this->did_setting_change( $setting, $new, $old ) ) {
return true;
}
}
return (
array_key_exists( 'cdn', $new )
&&
1 === (int) $new['cdn']
&&
$this->did_setting_change( 'cdn_cnames', $new, $old )
);
}
/**
* Checks if the given setting's value changed.
*
* @since 3.5.4
*
* @param string $setting The settings's value to check in the old and new values.
* @param array $new An array of submitted settings.
* @param array $old An array of previous settings.
*
* @return bool
*/
protected function did_setting_change( $setting, array $new, array $old ) {
return (
array_key_exists( $setting, $old )
&&
array_key_exists( $setting, $new )
&&
$old[ $setting ] !== $new[ $setting ]
);
}
}

View File

@@ -0,0 +1,322 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\CSS;
use WP_Rocket\Dependencies\Minify\CSS as MinifyCSS;
use WP_Rocket\Engine\Optimization\CSSTrait;
use WP_Rocket\Engine\Optimization\Minify\ProcessorInterface;
use WP_Rocket\Logger\Logger;
/**
* Minify & Combine CSS files
*
* @since 3.1
*/
class Combine extends AbstractCSSOptimization implements ProcessorInterface {
use CSSTrait;
/**
* Array of styles
*
* @var array
*/
private $styles = [];
/**
* Combined CSS filename
*
* @var string
*/
private $filename;
/**
* Minifies and combines all CSS files into one
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function optimize( $html ) {
Logger::info( 'CSS COMBINE PROCESS STARTED.', [ 'css combine process' ] );
$html_nocomments = $this->hide_comments( $html );
$styles = $this->find( '<link\s+([^>]+[\s"\'])?href\s*=\s*[\'"]\s*?(?<url>[^\'"]+\.css(?:\?[^\'"]*)?)\s*?[\'"]([^>]+)?\/?>', $html_nocomments );
if ( ! $styles ) {
Logger::debug( 'No `<link>` tags found.', [ 'css combine process' ] );
return $html;
}
Logger::debug(
'Found ' . count( $styles ) . ' `<link>` tag(s).',
[
'css combine process',
'tags' => $styles,
]
);
$styles = $this->parse( $styles );
if ( empty( $styles ) ) {
Logger::debug( 'No `<link>` tags to optimize.', [ 'css combine process' ] );
return $html;
}
Logger::debug(
count( $styles ) . ' `<link>` tag(s) remaining.',
[
'css combine process',
'tags' => $styles,
]
);
if ( ! $this->combine() ) {
Logger::error( 'CSS combine process failed.', [ 'css combine process' ] );
return $html;
}
return $this->insert_combined_css( $html );
}
/**
* Parses all found styles tag to keep only the ones to combine
*
* @since 3.7
*
* @param array $styles Array of matched styles.
* @return array
*/
private function parse( array $styles ) {
foreach ( $styles as $key => $style ) {
if ( $this->is_external_file( $style['url'] ) ) {
if ( $this->is_excluded_external( $style['url'] ) ) {
unset( $styles[ $key ] );
continue;
}
$this->styles[ $style['url'] ] = [
'type' => 'external',
'tag' => $style[0],
'url' => rocket_add_url_protocol( strtok( $style['url'], '?' ) ),
];
continue;
}
if ( $this->is_minify_excluded_file( $style ) ) {
Logger::debug(
'Style is excluded.',
[
'css combine process',
'tag' => $style[0],
]
);
unset( $styles[ $key ] );
continue;
}
$this->styles[ $style['url'] ] = [
'type' => 'internal',
'tag' => $style[0],
'url' => strtok( $style['url'], '?' ),
];
}
return $styles;
}
/**
* Checks if the provided external URL is excluded from combine
*
* @since 3.7
*
* @param string $url External URL to check.
* @return boolean
*/
private function is_excluded_external( $url ) {
foreach ( $this->get_excluded_externals() as $excluded ) {
if ( false !== strpos( $url, $excluded ) ) {
Logger::debug(
'Style is external.',
[
'css combine process',
'url' => $url,
]
);
return true;
}
}
return false;
}
/**
* Gets external URLs excluded from combine
*
* @since 3.7
*
* @return array
*/
private function get_excluded_externals() {
/**
* Filters CSS external URLs to exclude from the combine process
*
* @since 3.7
*
* @param array $pattern Patterns to match.
*/
$excluded_externals = (array) apply_filters( 'rocket_combine_css_excluded_external', [] );
return array_merge( $excluded_externals, $this->options->get( 'exclude_css', [] ) );
}
/**
* Combine the CSS content into one file and save it
*
* @since 3.1
*
* @return bool True if successful, false otherwise
*/
protected function combine() {
if ( empty( $this->styles ) ) {
return false;
}
$file_hash = implode( ',', array_column( $this->styles, 'url' ) );
$this->filename = md5( $file_hash . $this->minify_key ) . '.css';
$combined_file = $this->minify_base_path . $this->filename;
if ( rocket_direct_filesystem()->exists( $combined_file ) ) {
Logger::debug(
'Combined CSS file already exists.',
[
'css combine process',
'path' => $combined_file,
]
);
return true;
}
$combined_content = $this->get_content( $combined_file );
$combined_content = $this->apply_font_display_swap( $combined_content );
if ( empty( $combined_content ) ) {
Logger::error(
'No combined content.',
[
'css combine process',
'path' => $combined_file,
]
);
return false;
}
if ( ! $this->write_file( $combined_content, $combined_file ) ) {
Logger::error(
'Combined CSS file could not be created.',
[
'css combine process',
'path' => $combined_file,
]
);
return false;
}
Logger::debug(
'Combined CSS file successfully created.',
[
'css combine process',
'path' => $combined_file,
]
);
return true;
}
/**
* Insert the combined CSS file and remove the original CSS tags
*
* The combined CSS file is added after the closing </title> tag, and the replacement occurs only once. The original CSS tags are then removed from the HTML.
*
* @since 3.3.3
*
* @param string $html HTML content.
* @return string
*/
protected function insert_combined_css( $html ) {
foreach ( $this->styles as $style ) {
$html = str_replace( $style['tag'], '', $html );
}
$minify_url = $this->get_minify_url( $this->filename );
Logger::info(
'Combined CSS file successfully added.',
[
'css combine process',
'url' => $minify_url,
]
);
// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
return preg_replace( '/<\/title>/i', '$0<link rel="stylesheet" href="' . esc_url( $minify_url ) . '" media="all" data-minify="1" />', $html, 1 );
}
/**
* Gathers the content from all styles to combine & minify it if needed
*
* @since 3.7
*
* @param string $combined_file Absolute path to the combined file.
* @return string
*/
private function get_content( $combined_file ) {
$content = '';
foreach ( $this->styles as $key => $style ) {
if ( 'internal' === $style['type'] ) {
$filepath = $this->get_file_path( $style['url'] );
$file_content = $this->get_file_content( $filepath );
$file_content = $this->rewrite_paths( $filepath, $combined_file, $file_content );
} elseif ( 'external' === $style['type'] ) {
$file_content = $this->local_cache->get_content( $style['url'] );
$file_content = $this->rewrite_paths( $style['url'], $combined_file, $file_content );
}
if ( empty( $file_content ) ) {
unset( $this->styles[ $key ] );
continue;
}
$content .= $file_content;
}
$content = $this->minify( $content );
if ( empty( $content ) ) {
Logger::debug( 'No CSS content.', [ 'css combine process' ] );
}
return $content;
}
/**
* Minifies the content
*
* @since 3.1
*
* @param string $content Content to minify.
* @return string
*/
protected function minify( $content ) {
$minifier = new MinifyCSS( $content );
return $minifier->minify();
}
}

View File

@@ -0,0 +1,331 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\CSS;
use WP_Rocket\Dependencies\Minify as Minifier;
use WP_Rocket\Engine\Optimization\CSSTrait;
use WP_Rocket\Engine\Optimization\Minify\ProcessorInterface;
use WP_Rocket\Logger\Logger;
/**
* Minify CSS files
*
* @since 3.1
*/
class Minify extends AbstractCSSOptimization implements ProcessorInterface {
use CSSTrait;
/**
* Minifies CSS files
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function optimize( $html ) {
Logger::info( 'CSS MINIFICATION PROCESS STARTED.', [ 'css minification process' ] );
$styles = $this->get_styles( $html );
if ( empty( $styles ) ) {
return $html;
}
foreach ( $styles as $style ) {
if ( $this->is_minify_excluded_file( $style ) ) {
Logger::debug(
'Style is excluded.',
[
'css minification process',
'tag' => $style[0],
]
);
continue;
}
$integrity_validated = $this->local_cache->validate_integrity( $style );
if ( false === $integrity_validated ) {
Logger::debug(
'Style integrity attribute not valid.',
[
'css minification process',
'tag' => $style[0],
]
);
continue;
}
$style['final'] = $integrity_validated;
$minify_url = $this->replace_url( strtok( $style['url'], '?' ) );
if ( ! $minify_url ) {
Logger::error(
'Style minification failed.',
[
'css minification process',
'tag' => $style[0],
]
);
continue;
}
$html = $this->replace_style( $style, $minify_url, $html );
}
return $html;
}
/**
* Get all style tags from HTML.
*
* @param string $html HTML content.
* @return array Array with style tags, empty array if no style tags found.
*/
protected function get_styles( $html ) {
$html_nocomments = $this->hide_comments( $html );
$styles = $this->find( '<link\s+([^>]+[\s"\'])?href\s*=\s*[\'"]\s*?(?<url>[^\'"]+\.css(?:\?[^\'"]*)?)\s*?[\'"]([^>]+)?\/?>', $html_nocomments );
if ( ! $styles ) {
Logger::debug( 'No `<link>` tags found.', [ 'css minification process' ] );
return [];
}
Logger::debug(
'Found ' . count( $styles ) . ' `<link>` tags.',
[
'css minification process',
'tags' => $styles,
]
);
return $styles;
}
/**
* Creates the minify URL if the minification is successful
*
* @since 2.11
*
* @param string $url Original file URL.
* @return string|bool The minify URL if successful, false otherwise
*/
private function replace_url( $url ) {
if ( empty( $url ) ) {
return false;
}
// This filter is documented in /inc/classes/optimization/class-abstract-optimization.php.
$url = apply_filters( 'rocket_asset_url', $url, $this->get_zones() );
$parsed_url = wp_parse_url( $url );
if ( empty( $parsed_url['path'] ) ) {
return false;
}
if ( ! empty( $parsed_url['host'] ) ) {
$url = rocket_add_url_protocol( $url );
}
$unique_id = md5( $url . $this->minify_key );
$filename = preg_replace( '/\.(css)$/', '-' . $unique_id . '.css', ltrim( rocket_realpath( $parsed_url['path'] ), '/' ) );
$minified_file = rawurldecode( $this->minify_base_path . $filename );
$minify_url = $this->get_minify_url( $filename, $url );
if ( rocket_direct_filesystem()->exists( $minified_file ) ) {
Logger::debug(
'Minified CSS file already exists.',
[
'css minification process',
'path' => $minified_file,
]
);
return $minify_url;
}
$external_url = $this->is_external_file( $url );
$file_path = $external_url ? $this->local_cache->get_filepath( $url ) : $this->get_file_path( $url );
if ( empty( $file_path ) ) {
Logger::error(
'Couldnt get the file path from the URL.',
[
'css minification process',
'url' => $url,
]
);
return false;
}
$file_content = $external_url ? $this->local_cache->get_content( $url ) : $this->get_file_content( $file_path );
if ( ! $file_content ) {
Logger::error(
'No file content.',
[
'css minification process',
'path' => $file_path,
]
);
return false;
}
$minified_content = $external_url ? $this->minify( $url, $minified_file, $file_content ) : $this->minify( $file_path, $minified_file, $file_content );
if ( empty( $minified_content ) ) {
return false;
}
$minified_content = $this->font_display_swap( $url, $minified_file, $minified_content );
if ( empty( $minified_content ) ) {
return false;
}
$save_minify_file = $this->save_minify_file( $minified_file, $minified_content );
if ( ! $save_minify_file ) {
return false;
}
return $minify_url;
}
/**
* Replace old style tag with the minified tag.
*
* @param array $style Style matched data.
* @param string $minify_url Minified URL.
* @param string $html HTML content.
*
* @return string
*/
protected function replace_style( $style, $minify_url, $html ) {
$replace_style = str_replace( $style['url'], $minify_url, $style['final'] );
$replace_style = str_replace( '<link', '<link data-minify="1"', $replace_style );
$html = str_replace( $style[0], $replace_style, $html );
Logger::info(
'Style minification succeeded.',
[
'css minification process',
'url' => $minify_url,
]
);
return $html;
}
/**
* Save minified CSS file.
*
* @since 3.7
*
* @param string $minified_file Minified file path.
* @param string $minified_content Minified HTML content.
*
* @return bool
*/
protected function save_minify_file( $minified_file, $minified_content ) {
$save_minify_file = $this->write_file( $minified_content, $minified_file );
if ( ! $save_minify_file ) {
Logger::error(
'Minified CSS file could not be created.',
[
'css minification process',
'path' => $minified_file,
]
);
return false;
}
Logger::debug(
'Minified CSS file successfully created.',
[
'css minification process',
'path' => $minified_file,
]
);
return true;
}
/**
* Applies font display swap if the file contains @font-face.
*
* @since 3.7
*
* @param string $url File Url.
* @param string $minified_file Minified file path.
* @param string $content CSS file content.
* @return string
*/
protected function font_display_swap( $url, $minified_file, $content ) {
if (
preg_match( '/(?:-|\.)min.css/iU', $url )
&&
false === stripos( $content, '@font-face' )
) {
Logger::error(
'Do not apply font display swap on min.css files without font-face.',
[
'css minification process',
'path' => $minified_file,
]
);
if ( ! $this->is_external_file( $url ) ) {
return '';
}
return $content;
}
return $this->apply_font_display_swap( $content );
}
/**
* Minifies the content
*
* @since 2.11
*
* @param string $file_path Source filepath.
* @param string $minified_file Target filepath.
* @param string $file_content Content to minify.
* @return string
*/
protected function minify( $file_path, $minified_file, $file_content ) {
$file_content = $this->rewrite_paths( $file_path, $minified_file, $file_content );
$minifier = $this->get_minifier( $file_content );
$minified_content = $minifier->minify();
if ( empty( $minified_content ) ) {
Logger::error(
'No minified content.',
[
'css minification process',
'path' => $minified_file,
]
);
return '';
}
return $minified_content;
}
/**
* Returns a new minifier instance
*
* @since 3.1
*
* @param string $file_content Content to minify.
* @return Minifier\CSS
*/
protected function get_minifier( $file_content ) {
return new Minifier\CSS( $file_content );
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\CSS;
use WP_Rocket\Engine\Optimization\AssetsLocalCache;
use WP_Rocket\Engine\Optimization\Minify\AbstractMinifySubscriber;
/**
* Minify/Combine CSS subscriber
*
* @since 3.1
*/
class Subscriber extends AbstractMinifySubscriber {
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.1
*
* @return array
*/
public static function get_subscribed_events() {
$events = [
'rocket_css_url' => [
[ 'fix_ssl_minify' ],
[ 'i18n_multidomain_url' ],
],
'rocket_buffer' => [ 'process', 16 ],
];
return $events;
}
/**
* Processes the HTML to Minify/Combine CSS.
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function process( $html ) {
if ( ! $this->is_allowed() ) {
return $html;
}
$assets_local_cache = new AssetsLocalCache( rocket_get_constant( 'WP_ROCKET_MINIFY_CACHE_PATH' ), $this->filesystem );
if ( $this->options->get( 'minify_css' ) && $this->options->get( 'minify_concatenate_css' ) ) {
$this->set_processor_type( new Combine( $this->options, $assets_local_cache ) );
} elseif ( $this->options->get( 'minify_css' ) && ! $this->options->get( 'minify_concatenate_css' ) ) {
$this->set_processor_type( new Minify( $this->options, $assets_local_cache ) );
}
return $this->processor->optimize( $html );
}
/**
* Checks if is allowed to Minify/Combine CSS.
*
* @since 3.1
*
* @return bool
*/
protected function is_allowed() {
if ( rocket_get_constant( 'DONOTROCKETOPTIMIZE' ) ) {
return false;
}
if ( ! (bool) $this->options->get( 'minify_css', 0 ) ) {
return false;
}
return ! is_rocket_post_excluded_option( 'minify_css' );
}
/**
* Returns an array of CDN zones for CSS files.
*
* @since 3.1
*
* @return array
*/
public function get_zones() {
return [ 'all', 'css_and_js', 'css' ];
}
}