Initial commit xmarticaims

This commit is contained in:
2026-11-02 10:26:32 -06:00
commit e74236f5c1
9764 changed files with 2880647 additions and 0 deletions
@@ -0,0 +1,251 @@
<?php
namespace WP_Rocket\Engine\Optimization;
use WP_Rocket\Admin\Options_Data;
/**
* Base abstract class for files optimization
*
* @since 3.1
* @author Remy Perona
*/
abstract class AbstractOptimization {
use RegexTrait;
/**
* Plugin options.
*
* @var Options_Data
*/
protected $options;
/**
* Minify key.
*
* @var mixed
*/
protected $minify_key;
/**
* Concatenated list of excluded files.
*
* @var string
*/
protected $excluded_files;
/**
* Minify base path.
*
* @var string
*/
protected $minify_base_path;
/**
* Minify base URL.
*
* @var string
*/
protected $minify_base_url;
/**
* Initializes the minify base path and URL.
*/
protected function init_base_path_and_url() {
$site_id = get_current_blog_id() . '/';
$this->minify_base_path = rocket_get_constant( 'WP_ROCKET_MINIFY_CACHE_PATH' ) . $site_id;
$this->minify_base_url = rocket_get_constant( 'WP_ROCKET_MINIFY_CACHE_URL' ) . $site_id;
}
/**
* Finds nodes matching the pattern in the HTML.
*
* @since 3.1
* @author Remy Perona
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @return bool|array
*/
protected function find( string $pattern, string $html ) {
preg_match_all( '/' . $pattern . '/Umsi', $html, $matches, PREG_SET_ORDER );
if ( empty( $matches ) ) {
return false;
}
return $matches;
}
/**
* Determines if the file is external.
*
* @since 2.11
* @author Remy Perona
*
* @param string $url URL of the file.
* @return bool True if external, false otherwise
*/
protected function is_external_file( $url ) {
$file = get_rocket_parse_url( $url );
if ( empty( $file['path'] ) ) {
return true;
}
$wp_content = wp_parse_url( content_url() );
if ( empty( $wp_content['path'] ) ) {
return true;
}
/**
* Filters the allowed hosts for optimization
*
* @since 3.4
* @author Remy Perona
*
* @param array $hosts Allowed hosts.
* @param array $zones Zones to check available hosts.
*/
$hosts = (array) apply_filters( 'rocket_cdn_hosts', [], $this->get_zones() );
if ( ! empty( $wp_content['host'] ) ) {
$hosts[] = $wp_content['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 ) {
$check_url = strtok( $url, '?' );
if ( false !== strpos( $check_url, $host ) ) {
return false;
}
}
return true;
}
if ( empty( $file['host'] ) ) {
return false;
}
// URL has no domain and doesn't contain the WP_CONTENT path or wp-includes.
return ! preg_match( '#(' . $wp_content['path'] . '|wp-includes)#', $file['path'] );
}
/**
* Writes the content to a file
*
* @since 3.1
* @author Remy Perona
*
* @param string $content Content to write.
* @param string $file Path to the file to write in.
* @return bool
*/
protected function write_file( $content, $file ) {
if ( rocket_direct_filesystem()->is_readable( $file ) ) {
return true;
}
if ( ! rocket_mkdir_p( dirname( $file ) ) ) {
return false;
}
if ( function_exists( 'gzencode' ) ) {
// This filter is documented in inc/classes/Buffer/class-cache.php.
$gzip_content = gzencode( $content, apply_filters( 'rocket_gzencode_level_compression', 6 ) );
if ( $gzip_content ) {
rocket_put_content( $file . '.gz', $gzip_content );
}
}
return rocket_put_content( $file, $content );
}
/**
* Gets the file path from an URL
*
* @since 3.1
* @author Remy Perona
*
* @param string $url File URL.
* @return bool|string
*/
protected function get_file_path( $url ) {
return rocket_url_to_path( strtok( $url, '?' ), $this->get_zones() );
}
/**
* Gets content of a file
*
* @since 3.1
* @author Remy Perona
*
* @param string $file File path.
* @return string
*/
protected function get_file_content( $file ) {
return rocket_direct_filesystem()->get_contents( $file );
}
/**
* Hides unwanted blocks from the HTML to be parsed for optimization
*
* @since 3.1.4
* @author Remy Perona
*
* @param string $html HTML content.
* @return string
*/
protected function hide_comments( $html ) {
$html = preg_replace( '#<!--\s*noptimize\s*-->.*?<!--\s*/\s*noptimize\s*-->#is', '', $html );
$html = preg_replace( '/<!--(.*)-->/Uis', '', $html );
return $html;
}
/**
* Get full minified url with ?ver query string.
*
* @param string $minified_path Path of minified file.
* @param string $minified_url Url of minified file.
*
* @return string
*/
protected function get_full_minified_url( $minified_path, $minified_url ) {
$file_mtime = rocket_direct_filesystem()->mtime( $minified_path );
$version = $file_mtime ? $file_mtime : md5( $minified_url . $this->minify_key );
return add_query_arg( 'ver', $version, $minified_url );
}
/**
* Gets the CDN zones.
*
* @since 3.1
*
* @return array
*/
abstract public function get_zones();
}
@@ -0,0 +1,48 @@
<?php
namespace WP_Rocket\Engine\Optimization;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
/**
* Service provider for the WP Rocket optimizations
*
* @since 3.5.3
*/
class AdminServiceProvider 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 = [
'minify_css_admin_subscriber',
'google_fonts_settings',
'google_fonts_admin_subscriber',
'minify_admin_subscriber',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$this->getContainer()->share( 'minify_css_admin_subscriber', 'WP_Rocket\Engine\Optimization\Minify\CSS\AdminSubscriber' )
->addTag( 'admin_subscriber' );
$this->getContainer()->add( 'google_fonts_settings', 'WP_Rocket\Engine\Optimization\GoogleFonts\Admin\Settings' )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'beacon' ) )
->addArgument( $this->getContainer()->get( 'template_path' ) );
$this->getContainer()->share( 'google_fonts_admin_subscriber', 'WP_Rocket\Engine\Optimization\GoogleFonts\Admin\Subscriber' )
->addArgument( $this->getContainer()->get( 'google_fonts_settings' ) )
->addTag( 'admin_subscriber' );
$this->getContainer()->share( 'minify_admin_subscriber', 'WP_Rocket\Engine\Optimization\Minify\AdminSubscriber' )
->addTag( 'admin_subscriber' )
->addArgument( $this->getContainer()->get( 'options' ) );
}
}
@@ -0,0 +1,187 @@
<?php
namespace WP_Rocket\Engine\Optimization;
use WP_Filesystem_Direct;
/**
* Cache locally 3rd party assets.
*
* @since 3.1
*/
class AssetsLocalCache {
/**
* 3rd party assets cache folder path
*
* @since 3.1
*
* @var string
*/
protected $cache_path;
/**
* Filesystem instance.
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Cache contents with url.
*
* @var array
*/
private $url_cache = [];
/**
* Constructor
*
* @since 3.1
*
* @param string $cache_path 3rd party assets cache folder path.
* @param WP_Filesystem_Direct $filesystem Filesysten instance.
*/
public function __construct( $cache_path, $filesystem ) {
$this->cache_path = "{$cache_path}3rd-party/";
$this->filesystem = $filesystem;
}
/**
* Get remote file contents.
*
* @param string $url Url of the file to get contents for.
*
* @return string Raw file contents.
*/
private function get_raw_content( $url ) {
$cache_key = md5( $url );
if ( ! isset( $this->url_cache[ $cache_key ] ) ) {
$this->url_cache[ $cache_key ] = wp_remote_retrieve_body( wp_remote_get( $url ) );
}
return $this->url_cache[ $cache_key ];
}
/**
* Gets content for the provided URL.
* Use the local cache file if it exists, else get it from the 3rd party URL and save it locally for future use.
*
* @since 3.1
*
* @param string $url URL to get the content from.
*
* @return string
*/
public function get_content( $url ) {
$filepath = $this->get_filepath( $url );
if ( empty( $filepath ) ) {
return '';
}
if ( $this->filesystem->is_readable( $filepath ) ) {
return $this->filesystem->get_contents( $filepath );
}
$content = $this->get_raw_content( $url );
if ( empty( $content ) ) {
return '';
}
$this->write_file( $content, $filepath );
return $content;
}
/**
* Gets the filepath of the local copy for the given URL
*
* @since 3.7
*
* @param string $url URL to get filepath for.
* @return string
*/
public function get_filepath( $url ) {
$parts = wp_parse_url( $url );
if ( empty( $parts['path'] ) ) {
return '';
}
$filename = $parts['host'] . str_replace( '/', '-', $parts['path'] );
return $this->cache_path . $filename;
}
/**
* Writes the content to a file
*
* @since 3.1
*
* @param string $content Content to write.
* @param string $file Path to the file to write in.
* @return bool
*/
protected function write_file( $content, $file ) {
if ( $this->filesystem->is_readable( $file ) ) {
return true;
}
if ( ! rocket_mkdir_p( dirname( $file ) ) ) {
return false;
}
return rocket_put_content( $file, $content );
}
/**
* Check if this link HTML has integrity attribute or not?
*
* @since 3.7.5
*
* @param string $asset Link HTML to be tested.
*
* @return array|false Matched array with integrityhashmethod, integrityhash keys.
*/
private function has_integrity( $asset ) {
if ( ! preg_match( '#\s*integrity\s*=[\'"](?<integrityhashmethod>.*)-(?<integrityhash>.*)[\'"]#Ui', $asset, $integrity_matches ) ) {
return false;
}
if ( ! isset( $integrity_matches['integrityhashmethod'], $integrity_matches['integrityhash'] ) ) {
return false;
}
return $integrity_matches;
}
/**
* Validate the integrity attribute if the content matches with the hashed integrity value.
*
* @param array $asset_matched the matched array which has 0, url keys.
*
* @return bool|string
*/
public function validate_integrity( $asset_matched ) {
$integrity_matches = $this->has_integrity( $asset_matched[0] );
if ( false === $integrity_matches ) {
return $asset_matched[0];
}
// validate the hash algorithm.
if ( ! in_array( $integrity_matches['integrityhashmethod'], hash_algos(), true ) ) {
return false;
}
$content = $this->get_raw_content( $asset_matched['url'] );
$content_hash = base64_encode( hash( $integrity_matches['integrityhashmethod'], $content, true ) );// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
if ( $integrity_matches['integrityhash'] !== $content_hash ) {
return false;
}
return str_replace( $integrity_matches[0], '', $asset_matched[0] );
}
}
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\Buffer;
use WP_Rocket\Buffer\Abstract_Buffer;
use WP_Rocket\Buffer\Tests;
/**
* Handle page optimizations.
*
* @since 3.3
*/
class Optimization extends Abstract_Buffer {
/**
* Process identifier used by the logger.
*
* @var string
* @since 3.3
*/
protected $process_id = 'optimization process';
/**
* Tests instance
*
* @var Tests
*/
protected $tests;
/**
* Constructor.
*
* @since 3.3
*
* @param Tests $tests Tests instance.
*/
public function __construct( Tests $tests ) {
parent::__construct( $tests );
$this->log( 'OPTIMIZATION PROCESS STARTED.', [], 'info' );
}
/** ----------------------------------------------------------------------------------------- */
/** CACHE =================================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Do preliminary tests and maybe launch the buffer process.
*
* @since 3.3
*/
public function maybe_init_process() {
if ( ! $this->tests->can_init_process() ) {
$this->log_last_test_error();
return;
}
ob_start( [ $this, 'maybe_process_buffer' ] );
}
/**
* Maybe optimize the page content.
*
* @since 3.3
*
* @param string $buffer The buffer content.
* @return string The buffered content.
*/
public function maybe_process_buffer( $buffer ) {
/**
* Triggered before WP Rocket starts the optimization process.
*
* @since 3.4.2
* @author Soponar Cristina
*
* @param string $buffer HTML content.
*/
do_action( 'rocket_before_maybe_process_buffer', $buffer );
if ( ! $this->is_feed_uri() && ! $this->is_html( $buffer ) ) {
return $buffer;
}
if ( ! $this->tests->can_process_buffer( $buffer ) ) {
$this->log_last_test_error();
return $buffer;
}
/**
* This hook is used for:
* - Async CSS files
* - Defer JavaScript files
* - Minify/Combine HTML/CSS/JavaScript
* - CDN
* - LazyLoad
*
* @param string $buffer The page content.
*/
$buffer = (string) apply_filters( 'rocket_buffer', $buffer );
$this->log( 'Page optimized.', [], 'info' );
/**
* Fires after processing the buffer
*
* @since 3.12
*/
do_action( 'rocket_after_process_buffer' );
return $buffer;
}
/**
* Tell if the current url is a feed.
*
* @return bool
*/
public function is_feed_uri() {
global $wp_rewrite, $wp;
$feed_uri = '/(?:.+/)?' . $wp_rewrite->feed_base . '(?:/(?:.+/?)?)?$';
return (bool) preg_match( '#^(' . $feed_uri . ')$#i', '/' . $wp->request );
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\Buffer;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Event subscriber to buffer and process a page content.
*
* @since 3.3
*/
class Subscriber implements Subscriber_Interface {
/**
* Optimization instance
*
* @var Optimization
*/
private $optimizer;
/**
* Constructor
*
* @param Optimization $optimizer Optimization instance.
*/
public function __construct( Optimization $optimizer ) {
$this->optimizer = $optimizer;
}
/**
* {@inheritdoc}
*/
public static function get_subscribed_events() {
return [
'template_redirect' => [ 'start_content_process', 2 ],
];
}
/**
* Start buffering the page content and apply optimizations if we can.
*
* @since 3.3
*/
public function start_content_process() {
return $this->optimizer->maybe_init_process();
}
}
@@ -0,0 +1,593 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization;
use WP_Rocket\Dependencies\PathConverter\ConverterInterface;
use WP_Rocket\Dependencies\PathConverter\Converter;
trait CSSTrait {
/**
* Currently imported files.
*
* @var array
*/
private $imports = [];
/**
* Found charset on CSS.
*
* @var null|string
*/
private $found_charset = null;
/**
* Rewrites the paths inside the CSS file content
*
* @since 3.1
*
* @param string $source Source filepath.
* @param string $target Target filepath.
* @param string $content File content.
* @return string
*/
public function rewrite_paths( $source, $target, $content ) {
/**
* Filters the source path for an asset inside a CSS file
*
* @since 3.3.1
*
* @param string $source Source filepath.
*/
$source = apply_filters( 'rocket_css_asset_source_path', $source );
/**
* Filters the target path for an asset inside a CSS file
*
* @since 3.3.1
*
* @param string $target Target filepath.
*/
$target = apply_filters( 'rocket_css_asset_target_path', $target );
$content = $this->move( $this->get_converter( $source, $target ), $content, $source );
$this->set_cached_import( $source );
$content = $this->combine_imports( $content, $target );
/**
* Filters the content of a CSS file
*
* @since 3.4
*
* @param string $content CSS content.
* @param string $source Source filepath.
* @param string $target Target filepath.
*/
return apply_filters( 'rocket_css_content', $content, $source, $target );
}
/**
* Get an instance of the Converter class
*
* @param string $source Source filepath.
* @param string $target Destination filepath.
* @return Converter
*/
protected function get_converter( $source, $target ) {
return new Converter( $source, $target );
}
/**
* Moving a css file should update all relative urls.
* Relative references (e.g. ../images/image.gif) in a certain css file,
* will have to be updated when a file is being saved at another location
* (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
*
* Method copied from WP_Rocket\Dependencies\Minify\CSS;
*
* @param ConverterInterface $converter Relative path converter.
* @param string $content The CSS content to update relative urls for.
* @param string $source The source path or URL for the CSS file.
*
* @return string
*/
protected function move( ConverterInterface $converter, $content, $source ) {
/*
* Relative path references will usually be enclosed by url(). @import
* is an exception, where url() is not necessary around the path (but is
* allowed).
* This *could* be 1 regular expression, where both regular expressions
* in this array are on different sides of a |. But we're using named
* patterns in both regexes, the same name on both regexes. This is only
* possible with a (?J) modifier, but that only works after a fairly
* recent PCRE version. That's why I'm doing 2 separate regular
* expressions & combining the matches after executing of both.
*/
$relative_regexes = [
// url(xxx).
'/
# open url()
url\(
\s*
# open path enclosure
(?P<quotes>["\'])?
# fetch path
(?P<path>.+?)
# close path enclosure
(?(quotes)(?P=quotes))
\s*
# close url()
\)
/ix',
// @import "xxx"
'/
# import statement
@import
# whitespace
\s+
# we don\'t have to check for @import url(), because the
# condition above will already catch these
# open path enclosure
(?P<quotes>["\'])
# fetch path
(?P<path>.+?)
# close path enclosure
(?P=quotes)
/ix',
];
// find all relative urls in css.
$matches = [];
foreach ( $relative_regexes as $relative_regex ) {
if ( preg_match_all( $relative_regex, $content, $regex_matches, PREG_SET_ORDER ) ) {
$matches = array_merge( $matches, $regex_matches );
}
}
$search = [];
$replace = [];
// loop all urls.
foreach ( $matches as $match ) {
// determine if it's a url() or an @import match.
$type = ( strpos( $match[0], '@import' ) === 0 ? 'import' : 'url' );
$url = $match['path'];
if ( preg_match( '/^#/', $url ) ) {
continue;
}
if ( ! preg_match( '/^(data:|https?:|\\/)/', $url ) ) {
// attempting to interpret GET-params makes no sense, so let's discard them for awhile.
$params = strrchr( $url, '?' );
$url = $params ? substr( $url, 0, -strlen( $params ) ) : $url;
// fix relative url.
$url = filter_var( $source, FILTER_VALIDATE_URL ) ? dirname( $source ) . '/' . ltrim( $url, '/' ) : $converter->convert( $url );
// now that the path has been converted, re-apply GET-params.
$url .= $params;
}
/*
* Urls with control characters above 0x7e should be quoted.
* According to Mozilla's parser, whitespace is only allowed at the
* end of unquoted urls.
* Urls with `)` (as could happen with data: uris) should also be
* quoted to avoid being confused for the url() closing parentheses.
* And urls with a # have also been reported to cause issues.
* Urls with quotes inside should also remain escaped.
*
* @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
* @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
* @see https://github.com/matthiasmullie/minify/issues/193
*/
$url = trim( $url );
if ( preg_match( '/[\s\)\'"#\x{7f}-\x{9f}]/u', $url ) ) {
$url = $match['quotes'] . $url . $match['quotes'];
}
// build replacement.
$search[] = $match[0];
if ( 'url' === $type ) {
$replace[] = 'url(' . $url . ')';
} elseif ( 'import' === $type ) {
$replace[] = '@import "' . $url . '"';
}
}
// replace urls.
return str_replace( $search, $replace, $content );
}
/**
* Replace local imports with their contents recursively.
*
* @since 3.8.6
*
* @param string $content CSS Content.
* @param string $target Target CSS file path.
*
* @return string
*/
protected function combine_imports( $content, $target ) {
$import_regexes = [
// @import url(xxx)
'/
# import statement
@import
# whitespace
\s+
# open url()
url\(
# (optional) open path enclosure
(?P<quotes>["\']?)
# fetch path
(?P<path>.+?)
# (optional) close path enclosure
(?P=quotes)
# close url()
\)
# (optional) trailing whitespace
\s*
# (optional) media statement(s)
(?P<media>[^;]*)
# (optional) trailing whitespace
\s*
# (optional) closing semi-colon
;?
/ix',
// @import 'xxx'
'/
# import statement
@import
# whitespace
\s+
# open path enclosure
(?P<quotes>["\'])
# fetch path
(?P<path>.+?)
# close path enclosure
(?P=quotes)
# (optional) trailing whitespace
\s*
# (optional) media statement(s)
(?P<media>[^;]*)
# (optional) trailing whitespace
\s*
# (optional) closing semi-colon
;?
/ix',
];
// find all relative imports in css.
$matches = [];
foreach ( $import_regexes as $import_regexe ) {
if ( preg_match_all( $import_regexe, $content, $regex_matches, PREG_SET_ORDER ) ) {
$matches = array_merge( $matches, $regex_matches );
}
}
if ( empty( $matches ) ) {
return $content;
}
$search = [];
$replace = [];
// loop the matches.
foreach ( $matches as $match ) {
/**
* Filter Skip import replacement for one file.
*
* @since 3.8.6
*
* @param bool Skipped or not (Default not skipped).
* @param string $file_path Matched import path.
* @param string $import_match Full import match.
*/
if ( apply_filters( 'rocket_skip_import_replacement', false, $match['path'], $match ) ) {
continue;
}
list( $import_path, $import_content ) = $this->get_internal_file_contents( $match['path'], dirname( $target ) );
if ( empty( $import_content ) ) {
continue;
}
if ( $this->check_cached_import( $import_path ) ) {
$search[] = $match[0];
$replace[] = '';
continue;
}
$this->set_cached_import( $import_path );
// check if this is only valid for certain media.
if ( ! empty( $match['media'] ) ) {
$import_content = '@media ' . $match['media'] . '{' . $import_content . '}';
}
// Use recursion to rewrite paths and combine imports again for imported content.
$import_content = $this->rewrite_paths( $import_path, $target, $import_content );
// add to replacement array.
$search[] = $match[0];
$replace[] = $import_content;
}
// replace the import statements.
return str_replace( $search, $replace, $content );
}
/**
* Applies font-display:swap to all font-family rules without a previously set font-display property.
*
* @since 3.7
*
* @param string $css_file_content CSS file content to modify.
*
* @return string Modified CSS content.
*/
private function apply_font_display_swap( $css_file_content ) {
$css_file_content = (string) $css_file_content;
return preg_replace_callback(
'/(?:@font-face)\s*{(?<value>[^}]+)}/i',
function ( $matches ) {
if ( preg_match( '/font-display:\s*(?<swap_value>\w*);?/i', $matches['value'], $attribute ) ) {
if ( 'swap' === strtolower( $attribute['swap_value'] ) ) {
return $matches[0];
}
$swap = str_replace( $attribute['swap_value'], 'swap', $attribute[0] );
return preg_replace( '/font-display:\s*(?<swap_value>\w*);?/i', $swap, $matches[0] );
}
return str_replace( $matches['value'], "font-display:swap;{$matches['value']}", $matches[0] );
},
$css_file_content
);
}
/**
* Get internal file full path and contents.
*
* @since 3.8.6
*
* @param string $file Internal file path (maybe external url or relative path).
* @param string $base_path Base path as reference for relative paths.
*
* @return array Array of two values ( full path, contents )
*/
private function get_internal_file_contents( $file, $base_path ) {
if ( $this->is_external_path( $file ) && wp_http_validate_url( $file ) ) {
return [ $file, false ];
}
// Remove query strings.
$file = str_replace( '?' . wp_parse_url( $file, PHP_URL_QUERY ), '', $file );
// Check if this file is readable or it's relative path so we add base_path at it's start.
if ( ! rocket_direct_filesystem()->is_readable( $this->get_local_path( $file ) ) ) {
$ds = rocket_get_constant( 'DIRECTORY_SEPARATOR' );
$file = $base_path . $ds . str_replace( '/', $ds, $file );
}else {
$file = $this->get_local_path( $file );
}
$file_type = wp_check_filetype( $file, [ 'css' => 'text/css' ] );
if ( 'css' !== $file_type['ext'] ) {
return [ $file, null ];
}
$import_content = rocket_direct_filesystem()->get_contents( $file );
return [ $file, $import_content ];
}
/**
* Determines if the file is external.
*
* @since 3.8.6
*
* @param string $url URL of the file.
* @return bool True if external, false otherwise.
*/
protected function is_external_path( $url ) {
$file = get_rocket_parse_url( $url );
if ( empty( $file['path'] ) ) {
return true;
}
$parsed_site_url = wp_parse_url( site_url() );
if ( empty( $parsed_site_url['host'] ) ) {
return true;
}
// This filter is documented in inc/Engine/Admin/Settings/Settings.php.
$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( $url, $host ) ) {
return false;
}
}
return true;
}
return false;
}
/**
* Get local absolute path for image.
*
* @since 3.8.6
*
* @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 );
}
/**
* Normalize relative url to full url.
*
* @since 3.8.6
*
* @param string $url Url to be normalized.
*
* @return string Normalized url.
*/
private function normalize_url( $url ) {
$url_host = wp_parse_url( $url, PHP_URL_HOST );
if ( ! empty( $url_host ) ) {
return $url;
}
$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;
}
/**
* Set cached import locally not to imported again.
*
* @param string $path Path to be cached.
*/
private function set_cached_import( string $path ) {
$real_path = rocket_realpath( $path );
$this->imports[ md5( $real_path ) ] = $real_path;
}
/**
* Check if path imported before.
*
* @param string $path Path to be checked.
*
* @return bool
*/
private function check_cached_import( string $path ): bool {
return isset( $this->imports[ md5( rocket_realpath( $path ) ) ] );
}
/**
* Move charset to top of CSS file OR remove all charsets for internal CSS.
*
* @param string $content CSS content.
* @param bool $keep_first_charset Keep first charset if true, otherwise remove all charsets.
*
* @return string
*/
public function handle_charsets( string $content, bool $keep_first_charset = true ): string {
$new_content = preg_replace_callback( '/@charset\s+["|\'](.*?)["|\'];?/i', [ $this, 'match_charsets' ], $content );
if ( ! $keep_first_charset ) {
return $new_content;
}
if ( is_null( $this->found_charset ) ) {
return $content;
}
return "@charset \"{$this->found_charset}\";" . $new_content;
}
/**
* Match each charset on the CSS file.
*
* @param array $match Match array.
*
* @return string
*/
private function match_charsets( array $match ): string { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.matchFound
if ( is_null( $this->found_charset ) ) {
$this->found_charset = $match[1];
}
return '';
}
}
@@ -0,0 +1,309 @@
<?php
namespace WP_Rocket\Engine\Optimization;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Create a static file for CSS/JS generated by a PHP file
*
* @since 3.1
*/
class CacheDynamicResource extends AbstractOptimization implements Subscriber_Interface {
use CSSTrait;
/**
* Plugin options instance.
*
* @since 3.1
*
* @var Options_Data
*/
protected $options;
/**
* Cache busting base path
*
* @since 3.1
*
* @var string
*/
protected $busting_path;
/**
* Cache busting base URL
*
* @since 3.1
*
* @var string
*/
protected $busting_url;
/**
* Excluded files from optimization
*
* @since 3.1
*
* @var string
*/
protected $excluded_files;
/**
* Extension to use for the CDN zones selection
*
* @var string
*/
protected $extension = '';
/**
* Creates an instance of CacheDynamicResource.
*
* @since 3.1
*
* @param Options_Data $options Plugin options instance.
* @param string $busting_path Base cache busting files path.
* @param string $busting_url Base cache busting files URL.
*/
public function __construct( Options_Data $options, $busting_path, $busting_url ) {
$site_id = get_current_blog_id();
$this->options = $options;
$this->busting_path = "{$busting_path}{$site_id}/";
$this->busting_url = "{$busting_url}{$site_id}/";
/**
* Filters files to exclude from static dynamic resources
*
* @since 2.9.3
* @author Remy Perona
*
* @param array $excluded_files An array of filepath to exclude.
*/
$this->excluded_files = (array) apply_filters( 'rocket_exclude_static_dynamic_resources', [] );
$this->excluded_files[] = '/wp-admin/admin-ajax.php';
foreach ( $this->excluded_files as $i => $excluded_file ) {
// Escape character for future use in regex pattern.
$this->excluded_files[ $i ] = str_replace( '#', '\#', $excluded_file );
}
$this->excluded_files = implode( '|', $this->excluded_files );
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.1
*
* @return array
*/
public static function get_subscribed_events() {
return [
'style_loader_src' => [ 'cache_dynamic_resource', 16 ],
'script_loader_src' => [ 'cache_dynamic_resource', 16 ],
];
}
/**
* Filters the source dynamic php file to replace it with a static file
*
* @since 3.1
*
* @param string $src source URL.
*
* @return string
*/
public function cache_dynamic_resource( $src ) {
if ( ! $this->is_allowed() ) {
return $src;
}
switch ( current_filter() ) {
case 'script_loader_src':
$this->set_extension( 'js' );
break;
case 'style_loader_src':
$this->set_extension( 'css' );
break;
}
if ( $this->is_excluded_file( $src ) ) {
return $src;
}
return $this->replace_url( $src );
}
/**
* Replaces the dynamic URL by the static file URL
*
* @since 3.1
*
* @param string $src Source URL.
*
* @return string
*/
public function replace_url( $src ) {
$path = ltrim( rocket_extract_url_component( $src, PHP_URL_PATH ), '/' );
/**
* Filters the dynamic resource cache filename
*
* @since 2.9
*
* @param string $filename filename for the cache file
*/
$filename = apply_filters( 'rocket_dynamic_resource_cache_filename', preg_replace( '/\.php$/', '.' . $this->extension, $path ) );
$filename = ltrim( rocket_realpath( rtrim( str_replace( [ ' ', '%20' ], '-', $filename ) ) ), '/' );
$filepath = $this->busting_path . $filename;
if ( ! rocket_direct_filesystem()->is_readable( $filepath ) ) {
$content = $this->get_url_content( $src );
if ( ! $content ) {
return $src;
}
if ( 'css' === $this->extension ) {
$content = $this->rewrite_paths( $this->get_file_path( $src ), $filepath, $content );
$content = $this->apply_font_display_swap( $content );
}
if ( ! $this->write_file( $content, $filepath ) ) {
return $src;
}
}
return $this->get_cache_url( $filename );
}
/**
* Determines if we can optimize
*
* @since 3.1
*
* @return bool
*/
public function is_allowed() {
global $pagenow;
if ( rocket_bypass() ) {
return false;
}
if ( rocket_get_constant( 'DONOTROCKETOPTIMIZE' ) ) {
return false;
}
if ( is_user_logged_in() && ! $this->options->get( 'cache_logged_user' ) ) {
return false;
}
if ( 'wp-login.php' === $pagenow ) {
return false;
}
return true;
}
/**
* Determines if the file is excluded from optimization
*
* @since 3.1
*
* @param string $src source URL.
*
* @return bool
*/
public function is_excluded_file( $src ) {
$file = get_rocket_parse_url( $src );
if ( isset( $file['path'] ) && ! preg_match( '#\.php$#', $file['path'] ) ) {
return true;
}
if ( $this->is_external_file( $src ) ) {
return true;
}
if ( preg_match( '#^' . $this->excluded_files . '$#', $file['path'] ) ) {
return true;
}
if ( ! isset( $file['query'] ) ) {
return false;
}
$file['query'] = remove_query_arg( 'ver', $file['query'] );
return (bool) $file['query'];
}
/**
* Sets the current file extension and minify key
*
* @since 3.1
*
* @param string $extension Current file extension.
*/
public function set_extension( $extension ) {
$this->extension = $extension;
$this->minify_key = $this->options->get( 'minify_' . $this->extension . '_key' );
}
/**
* Gets the CDN zones.
*
* @since 3.1
*
* @return array
*/
public function get_zones() {
return [ 'all', 'css_and_js', $this->extension ];
}
/**
* Gets the cache URL for the static file
*
* @since 3.1
*
* @param string $filename Filename for the static file.
*
* @return string
*/
protected function get_cache_url( $filename ) {
$cache_url = $this->busting_url . $filename;
switch ( $this->extension ) {
case 'css':
// This filter is documented in inc/classes/optimization/css/class-abstract-css-optimization.php.
$cache_url = apply_filters( 'rocket_css_url', $cache_url );
break;
case 'js':
// This filter is documented in inc/classes/optimization/css/class-abstract-js-optimization.php.
$cache_url = apply_filters( 'rocket_js_url', $cache_url );
break;
}
return $cache_url;
}
/**
* Gets content from an URL
*
* @since 3.1
*
* @param string $url URL to get the content from.
*
* @return string|bool
*/
protected function get_url_content( $url ) {
$content = wp_remote_retrieve_body( wp_remote_get( $url ) );
if ( ! $content ) {
return false;
}
return $content;
}
}
@@ -0,0 +1,124 @@
<?php
namespace WP_Rocket\Engine\Optimization;
trait ContentTrait {
/**
* Gets all public post types.
*
* @since 3.9 moved into trait
* @since 2.11
*/
private function get_public_post_types() {
global $wpdb;
$post_types = get_post_types(
[
'public' => true,
'publicly_queryable' => true,
]
);
$post_types[] = 'page';
/**
* Filters the post types excluded from critical CSS generation.
*
* @since 2.11
*
* @param array $excluded_post_types An array of post types names.
*
* @return array
*/
$excluded_post_types = (array) apply_filters(
'rocket_cpcss_excluded_post_types',
[
'elementor_library',
'oceanwp_library',
'tbuilder_layout',
'tbuilder_layout_part',
'slider',
'karma-slider',
'tt-gallery',
'xlwcty_thankyou',
'fusion_template',
'blocks',
'jet-woo-builder',
'fl-builder-template',
'cms_block',
'web-story',
]
);
$post_types = array_diff( $post_types, $excluded_post_types );
$post_types = esc_sql( $post_types );
$post_types = "'" . implode( "','", $post_types ) . "'";
return $wpdb->get_results(
"SELECT MAX(ID) as ID, post_type
FROM (
SELECT ID, post_type
FROM $wpdb->posts
WHERE post_type IN ( $post_types )
AND post_status = 'publish'
ORDER BY post_date DESC
) AS posts
GROUP BY post_type"
);
}
/**
* Gets all public taxonomies.
*
* @since 3.9 moved into trait
* @since 2.11
*/
private function get_public_taxonomies() {
global $wpdb;
$taxonomies = get_taxonomies(
[
'public' => true,
'publicly_queryable' => true,
]
);
/**
* Filters the taxonomies excluded from critical CSS generation.
*
* @since 2.11
*
* @param array $excluded_taxonomies An array of taxonomies names.
*
* @return array
*/
$excluded_taxonomies = (array) apply_filters(
'rocket_cpcss_excluded_taxonomies',
[
'post_format',
'product_shipping_class',
'karma-slider-category',
'truethemes-gallery-category',
'coupon_campaign',
'element_category',
'mediamatic_wpfolder',
'attachment_category',
]
);
$taxonomies = array_diff( $taxonomies, $excluded_taxonomies );
$taxonomies = esc_sql( $taxonomies );
$taxonomies = "'" . implode( "','", $taxonomies ) . "'";
return $wpdb->get_results(
"SELECT MAX( term_id ) AS ID, taxonomy
FROM (
SELECT term_id, taxonomy
FROM $wpdb->term_taxonomy
WHERE taxonomy IN ( $taxonomies )
AND count > 0
) AS taxonomies
GROUP BY taxonomy"
);
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DeferJS;
use WP_Rocket\Event_Management\Subscriber_Interface;
class AdminSubscriber implements Subscriber_Interface {
/**
* DeferJS instance
*
* @var DeferJS
*/
private $defer_js;
/**
* Instantiate the class
*
* @param DeferJS $defer_js DeferJS instance.
*/
public function __construct( DeferJS $defer_js ) {
$this->defer_js = $defer_js;
}
/**
* Returns array of events this listen to.
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_first_install_options' => 'add_defer_js_option',
'wp_rocket_upgrade' => [ 'exclude_jquery_defer', 14, 2 ],
'rocket_meta_boxes_fields' => [ 'add_meta_box', 5 ],
];
}
/**
* Adds defer js option to WP Rocket options array
*
* @since 3.8
*
* @param array $options WP Rocket options array.
* @return array
*/
public function add_defer_js_option( array $options ): array {
return $this->defer_js->add_option( $options );
}
/**
* Adds jQuery to defer JS exclusion field if safe mode was enabled before 3.8
*
* @since 3.8
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function exclude_jquery_defer( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.8', '>' ) ) {
return;
}
$this->defer_js->exclude_jquery_upgrade();
}
/**
* 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['defer_all_js'] = __( 'Load JavaScript deferred', 'rocket' );
return $fields;
}
}
@@ -0,0 +1,315 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DeferJS;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\DynamicLists\DefaultLists\DataManager;
class DeferJS {
/**
* Options instance
*
* @var Options_Data
*/
private $options;
/**
* DataManager instance
*
* @var DataManager
*/
private $data_manager;
/**
* Instantiate the class
*
* @param Options_Data $options Options instance.
* @param DataManager $data_manager DataManager instance.
*/
public function __construct( Options_Data $options, DataManager $data_manager ) {
$this->options = $options;
$this->data_manager = $data_manager;
}
/**
* Add the exclude defer JS option in 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_defer_js'] = [];
return $options;
}
/**
* Defer all JS files.
*
* @since 3.8
*
* @param string $html HTML content.
* @return string
*/
public function defer_js( string $html ): string {
if ( ! $this->can_defer_js() ) {
return $html;
}
$buffer_nocomments = preg_replace( '/<!--(.*)-->/Uis', '', $html );
preg_match_all( '#<script\s+(?:[^>]+[\s\'"])?src\s*=\s*[\'"]\s*?(?<url>[^\'"]+)\s*?[\'"](?:[^>]+)?\/?>#i', $buffer_nocomments, $matches, PREG_SET_ORDER );
if ( empty( $matches ) ) {
return $html;
}
$exclude_defer_js = implode( '|', $this->get_excluded() );
if ( ! @preg_replace( '#(' . $exclude_defer_js . ')#i', '', 'dummy-string' ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
return $html;
}
foreach ( $matches as $tag ) {
if ( preg_match( '#(' . $exclude_defer_js . ')#i', $tag['url'] ) ) {
continue;
}
if ( preg_match( '/\s+(?:async|defer)/i', $tag[0] ) ) {
continue;
}
$deferred_tag = str_replace( '>', ' defer>', $tag[0] );
$html = str_replace( $tag[0], $deferred_tag, $html );
}
return $html;
}
/**
* Defers inline JS containing jQuery calls
*
* @since 3.8
*
* @param string $html HTML content.
* @return string
*/
public function defer_inline_js( string $html ): string {
if ( ! $this->can_defer_js() ) {
return $html;
}
$exclude_defer_js = implode( '|', $this->get_excluded() );
if ( preg_match( '/(jquery(?:.*)?\.js)/i', $exclude_defer_js ) ) {
return $html;
}
$buffer_nocomments = preg_replace( '/<!--(.*)-->/Uis', '', $html );
preg_match_all( '#<script(?:[^>]*)>(?<content>[\s\S]*?)</script>#msi', $buffer_nocomments, $matches, PREG_SET_ORDER );
if ( empty( $matches ) ) {
return $html;
}
/**
* Filters the patterns used to find jQuery in inline JS
*
* @since 3.8
*
* @param string $jquery_patterns A RegEx pattern to find jQuery inline JS.
*/
$jquery_patterns = apply_filters( 'rocket_defer_jquery_patterns', 'jQuery|\$\.\(|\$\(' );
$inline_exclusions = $this->get_inline_exclusions_list_pattern();
foreach ( $matches as $inline_js ) {
if ( empty( $inline_js['content'] ) ) {
continue;
}
if ( preg_match( '/(application\/ld\+json)/i', $inline_js[0] ) ) {
continue;
}
if ( empty( $inline_exclusions ) || preg_match( "/({$inline_exclusions})/msi", $inline_js['content'] ) ) {
continue;
}
if ( ! empty( $jquery_patterns ) && ! preg_match( "/({$jquery_patterns})/msi", $inline_js['content'] ) ) {
continue;
}
$tag = str_replace( $inline_js['content'], $this->inline_js_wrapper( $inline_js['content'] ), $inline_js[0] );
$html = str_replace( $inline_js[0], $tag, $html );
}
return $html;
}
/**
* Adds the JS wrapper for inline jQuery code
*
* @since 3.8
*
* @param string $content Inline JS content.
* @return string
*/
private function inline_js_wrapper( string $content ): string {
return "window.addEventListener('DOMContentLoaded', function() {" . $content . '});';
}
/**
* Checks if we can defer JS
*
* @since 3.8
*
* @return boolean
*/
private function can_defer_js(): bool {
if ( rocket_get_constant( 'DONOTROCKETOPTIMIZE' ) ) {
return false;
}
if ( ! $this->options->get( 'defer_all_js', 0 ) ) {
return false;
}
return ! is_rocket_post_excluded_option( 'defer_all_js' );
}
/**
* Get list of JS files to be excluded from defer JS.
*
* @since 3.8
*
* @return array
*/
public function get_excluded(): array {
if ( ! $this->can_defer_js() ) {
return [];
}
$exclude_defer_js = array_unique( array_merge( $this->get_external_exclusions(), $this->options->get( 'exclude_defer_js', [] ) ) );
/**
* Filter list of Deferred JavaScript files
*
* @since 2.10
*
* @param array $exclude_defer_js An array of URLs for the JS files to be excluded.
*/
$exclude_defer_js = apply_filters( 'rocket_exclude_defer_js', $exclude_defer_js );
foreach ( $exclude_defer_js as $i => $exclude ) {
$exclude_defer_js[ $i ] = str_replace( '#', '\#', $exclude );
}
return $exclude_defer_js;
}
/**
* Excludes jQuery from combine JS when defer and combine are enabled
*
* @since 3.8
*
* @param array $excluded_files Array of excluded files from combine JS.
* @return array
*/
public function exclude_jquery_combine( array $excluded_files ): array {
if ( ! $this->can_defer_js() ) {
return $excluded_files;
}
if ( ! (bool) $this->options->get( 'minify_concatenate_js', 0 ) ) {
return $excluded_files;
}
$excluded_files[] = '/jquery-?[0-9.]*(.min|.slim|.slim.min)?.js';
return $excluded_files;
}
/**
* Adds jQuery to defer JS exclusion field if safe mode was enabled before 3.8
*
* @since 3.8
*
* @return void
*/
public function exclude_jquery_upgrade() {
$options = get_option( 'wp_rocket_settings' );
if ( ! isset( $options['defer_all_js_safe'] ) ) {
return;
}
if ( ! (bool) $options['defer_all_js_safe'] ) {
return;
}
$options['exclude_defer_js'][] = '/jquery-?[0-9.]*(.min|.slim|.slim.min)?.js';
update_option( 'wp_rocket_settings', $options );
}
/**
* Get exclusion list pattern.
*
* @return string
*/
private function get_inline_exclusions_list_pattern() {
$inline_exclusions_list = $this->get_inline_exclusions();
/**
* Filters the patterns used to find inline JS that should not be deferred
*
* @since 3.8
*
* @param array $inline_exclusions_list Array of inline JS that should not be deferred.
*/
$additional_inline_exclusions_list = apply_filters( 'rocket_defer_inline_exclusions', null );
$inline_exclusions = '';
// Check if filter return is string so convert it to array for backward compatibility.
if ( is_string( $additional_inline_exclusions_list ) ) {
$additional_inline_exclusions_list = explode( '|', $additional_inline_exclusions_list );
}
// Cast filter return to array.
$inline_exclusions_list = array_merge( $inline_exclusions_list, (array) $additional_inline_exclusions_list );
foreach ( $inline_exclusions_list as $inline_exclusions_item ) {
$inline_exclusions .= preg_quote( (string) $inline_exclusions_item, '#' ) . '|';
}
return rtrim( $inline_exclusions, '|' );
}
/**
* Get inline exclusions list
*
* @return array
*/
private function get_inline_exclusions(): array {
$lists = $this->data_manager->get_lists();
return isset( $lists->defer_js_inline_exclusions ) ? $lists->defer_js_inline_exclusions : [];
}
/**
* Get external exclusions list
*
* @return array
*/
private function get_external_exclusions(): array {
$lists = $this->data_manager->get_lists();
return isset( $lists->defer_js_external_exclusions ) ? $lists->defer_js_external_exclusions : [];
}
}
@@ -0,0 +1,44 @@
<?php
namespace WP_Rocket\Engine\Optimization\DeferJS;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
/**
* Service provider for the WP Rocket Defer JS
*
* @since 3.8
*/
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 = [
'defer_js',
'defer_js_admin_subscriber',
'defer_js_subscriber',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$this->getContainer()->add( 'defer_js', DeferJS::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'dynamic_lists_defaultlists_data_manager' ) );
$this->getContainer()->share( 'defer_js_admin_subscriber', AdminSubscriber::class )
->addArgument( $this->getContainer()->get( 'defer_js' ) )
->addTag( 'admin_subscriber' );
$this->getContainer()->share( 'defer_js_subscriber', Subscriber::class )
->addArgument( $this->getContainer()->get( 'defer_js' ) )
->addTag( 'front_subscriber' );
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DeferJS;
use WP_Rocket\Event_Management\Subscriber_Interface;
class Subscriber implements Subscriber_Interface {
/**
* DeferJS instance
*
* @var DeferJS
*/
private $defer_js;
/**
* Instantiate the class
*
* @param DeferJS $defer_js DeferJS instance.
*/
public function __construct( DeferJS $defer_js ) {
$this->defer_js = $defer_js;
}
/**
* Returns array of events this listen to.
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_buffer' => [
[ 'defer_js', 24 ],
[ 'defer_inline_js', 25 ],
],
'rocket_exclude_js' => 'exclude_jquery_combine',
'rocket_minify_excluded_external_js' => 'exclude_jquery_combine',
];
}
/**
* Adds the defer attribute to JS files
*
* @since 3.8
*
* @param string $html HTML content.
* @return string
*/
public function defer_js( string $html ): string {
return $this->defer_js->defer_js( $html );
}
/**
* Defers inline JS containing jQuery calls
*
* @since 3.8
*
* @param string $html HTML content.
* @return string
*/
public function defer_inline_js( string $html ): string {
return $this->defer_js->defer_inline_js( $html );
}
/**
* Excludes jQuery from combine JS when defer and combine are enabled
*
* @since 3.8
*
* @param array $excluded_files Array of excluded files from combine JS.
* @return array
*/
public function exclude_jquery_combine( array $excluded_files ): array {
return $this->defer_js->exclude_jquery_combine( $excluded_files );
}
}
@@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DelayJS\Admin;
use WP_Rocket\Admin\Options;
use WP_Rocket\Engine\Admin\Settings\Settings as AdminSettings;
class Settings {
/**
* Options instance.
*
* @var Options
*/
protected $options_api;
/**
* Constructor.
*
* @param Options $options_api Options instance.
*/
public function __construct( Options $options_api ) {
$this->options_api = $options_api;
}
/**
* Add the delay JS options to the WP Rocket options array
*
* @since 3.9 Removed delay_js_scripts key, added delay_js_exclusions.
* @since 3.7
*
* @param array $options WP Rocket options array.
*
* @return array
*/
public function add_options( $options ): array {
$options = (array) $options;
$options['delay_js'] = 0;
$options['delay_js_exclusions'] = [];
return $options;
}
/**
* Sets the delay_js_exclusions default value for users with delay JS enabled on upgrade
*
* @since 3.9 Sets the delay_js_exclusions default value if delay_js is 1
* @since 3.7
*
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function set_option_on_update( $old_version ) {
if ( version_compare( $old_version, '3.9', '>=' ) ) {
return;
}
$options = $this->options_api->get( 'settings', [] );
$options['delay_js_exclusions'] = [];
if (
isset( $options['delay_js'] )
&&
1 === (int) $options['delay_js']
) {
$options['minify_concatenate_js'] = 0;
}
$this->options_api->set( 'settings', $options );
}
/**
* Sanitizes delay JS options when saving the settings
*
* @since 3.9
*
* @param array $input Array of values submitted from the form.
* @param AdminSettings $settings Settings class instance.
*
* @return array
*/
public function sanitize_options( $input, $settings ): array {
$input['delay_js'] = $settings->sanitize_checkbox( $input, 'delay_js' );
$input['delay_js_exclusions'] =
! empty( $input['delay_js_exclusions'] )
?
rocket_sanitize_textarea_field( 'delay_js_exclusions', $input['delay_js_exclusions'] )
:
[];
return $input;
}
/**
* Disable combine JS option when delay JS is enabled
*
* @since 3.9
*
* @param array $value The new, unserialized option value.
* @param array $old_value The old option value.
*
* @return array
*/
public function maybe_disable_combine_js( $value, $old_value ): array {
if ( ! isset( $value['delay_js'], $value['minify_concatenate_js'] ) ) {
return $value;
}
if (
0 === $value['minify_concatenate_js']
||
0 === $value['delay_js']
) {
return $value;
}
if (
isset( $old_value['delay_js'], $old_value['minify_concatenate_js'] )
&&
$value['delay_js'] === $old_value['delay_js']
&&
1 === $value['delay_js']
&&
0 === $old_value['minify_concatenate_js']
) {
return $value;
}
$value['minify_concatenate_js'] = 0;
return $value;
}
/**
* Get default exclusion list.
*
* @since 3.9.1
*
* @return string[]
*/
public static function get_delay_js_default_exclusions(): array {
$exclusions = [
'\/jquery(-migrate)?-?([0-9.]+)?(.min|.slim|.slim.min)?.js(\?(.*))?( |\'|"|>)',
'js-(before|after)',
];
$wp_content = wp_parse_url( content_url( '/' ), PHP_URL_PATH );
$wp_includes = wp_parse_url( includes_url( '/' ), PHP_URL_PATH );
$pattern = '(?:placeholder)(.*)';
$paths = [];
if ( ! $wp_content && ! $wp_includes ) {
return $exclusions;
}
if ( $wp_content ) {
$paths[] = $wp_content;
}
if ( $wp_includes ) {
$paths[] = $wp_includes;
}
$exclusions[] = str_replace( 'placeholder', implode( '|', $paths ), $pattern );
return $exclusions;
}
/**
* Check if current exclusion list has the default list.
*
* @since 3.9.1
*
* @return bool
*/
public static function exclusion_list_has_default(): bool {
$current_list = get_rocket_option( 'delay_js_exclusions', [] );
if ( empty( $current_list ) ) {
return false;
}
$default_list = self::get_delay_js_default_exclusions();
if ( count( $current_list ) < count( $default_list ) ) {
return false;
}
$current_list = array_flip( $current_list );
foreach ( $default_list as $item ) {
if ( ! isset( $current_list[ $item ] ) ) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,535 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DelayJS\Admin;
use WP_Rocket\Admin\Options;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\DynamicLists\DelayJSLists\DataManager;
use WP_Rocket\Engine\Optimization\DynamicLists\DynamicLists;
use WP_Theme;
class SiteList {
/**
* Delay JS data manager.
*
* @var DataManager
*/
protected $dynamic_lists;
/**
* Options instance.
*
* @var Options_Data
*/
protected $options;
/**
* Options API instance.
*
* @var Options
*/
private $options_api;
/**
* SiteList Constructor.
*
* @param DynamicLists $dynamic_lists Dynamic Lists instance.
* @param Options_Data $options Options instance.
* @param Options $options_api Options API instance.
*/
public function __construct( DynamicLists $dynamic_lists, Options_Data $options, Options $options_api ) {
$this->dynamic_lists = $dynamic_lists;
$this->options = $options;
$this->options_api = $options_api;
}
/**
* Check if plugin is in the list and return it if found.
*
* @param string $item_id Plugin ID like wp-rocket/wp-rocket.php.
*
* @return array
*/
private function get_plugin_in_list( string $item_id ) {
$list = $this->dynamic_lists->get_delayjs_list();
return ! empty( $list->plugins->$item_id ) ? (array) $list->plugins->$item_id : [];
}
/**
* Check if theme is in the list and return it if found.
*
* @param string $item_id Theme ID (directory name) like twentytwenty.
*
* @return array
*/
private function get_theme_in_list( string $item_id ) {
$list = $this->dynamic_lists->get_delayjs_list();
return ! empty( $list->themes->$item_id ) ? (array) $list->themes->$item_id : [];
}
/**
* Check if script is in the list and return it if found.
*
* @param string $item_id Script ID.
*
* @return array
*/
private function get_script_in_list( string $item_id ) {
$scripts = $this->get_scripts_from_list();
return ! empty( $scripts[ $item_id ] ) ? (array) $scripts[ $item_id ] : [];
}
/**
* Get all scripts from the list.
*
* @return array
*/
private function get_scripts_from_list() {
$list = $this->dynamic_lists->get_delayjs_list();
return ! empty( $list->scripts ) ? (array) $list->scripts : [];
}
/**
* Get all plugins from the list.
*
* @return array
*/
private function get_plugins_from_list() {
$list = $this->dynamic_lists->get_delayjs_list();
return ! empty( $list->plugins ) ? (array) $list->plugins : [];
}
/**
* Get all themes from the list.
*
* @return array
*/
private function get_themes_from_list() {
$list = $this->dynamic_lists->get_delayjs_list();
return ! empty( $list->themes ) ? (array) $list->themes : [];
}
/**
* Get list of exclusions from the API list.
*
* @param string $item_id Item ID to get exclusions for (plugin slug, theme slug, script ID).
*
* @return array
*/
public function get_delayjs_exclusions_by_id( string $item_id ) {
$item = $this->get_script_in_list( $item_id );
if ( $item ) {
return $item['exclusions'];
}
$item = $this->get_plugin_in_list( $item_id );
if ( $item ) {
return $item['exclusions'];
}
$item = $this->get_theme_in_list( $item_id );
if ( $item ) {
return $item['exclusions'];
}
return [];
}
/**
* Get all exclusions (merged together) for a list of item IDs.
*
* @param array $items List of items.
*
* @return array
*/
public function get_delayjs_items_exclusions( array $items ) {
if ( empty( $items ) ) {
return [];
}
$exclusions = [];
foreach ( $items as $item ) {
$exclusions = array_merge( $exclusions, $this->get_delayjs_exclusions_by_id( $item ) );
}
return $exclusions;
}
/**
* Get active theme ID.
*
* @return string
*/
public function get_active_theme() {
return $this->get_theme_name( wp_get_theme() );
}
/**
* Get active plugins (list of IDs).
*
* @return array
*/
public function get_active_plugins() {
$plugins = (array) get_option( 'active_plugins', [] );
if ( ! is_multisite() ) {
return $plugins;
}
return array_merge(
$plugins,
array_keys( (array) get_site_option( 'active_sitewide_plugins', [] ) )
);
}
/**
* Prepare the list of scripts, plugins and theme for the view.
*
* @return array|array[]
*/
public function prepare_delayjs_ui_list() {
$full_list = [
'scripts' => [
'title' => __( 'Analytics & Ads', 'rocket' ),
'items' => [],
'dashicon-class' => 'analytics',
],
'plugins' => [
'title' => __( 'Plugins', 'rocket' ),
'items' => [],
'dashicon-class' => 'admin-plugins',
],
'themes' => [
'title' => __( 'Themes', 'rocket' ),
'items' => [],
'dashicon-class' => 'admin-appearance',
],
];
// Scripts.
$scripts = $this->get_scripts_from_list();
foreach ( $scripts as $script_key => $script ) {
$full_list['scripts']['items'][] = [
'id' => $script_key,
'title' => $script->title,
'icon' => $this->get_icon( $script ),
];
}
$active_plugins = $this->get_active_plugins();
foreach ( $this->get_plugins_from_list() as $plugin_key => $plugin ) {
if ( ! in_array( $plugin->condition, $active_plugins, true ) ) {
continue;
}
$full_list['plugins']['items'][] = [
'id' => $plugin_key,
'title' => $plugin->title,
'icon' => $this->get_icon( $plugin ),
];
}
$active_theme = $this->get_active_theme();
foreach ( $this->get_themes_from_list() as $theme_key => $theme ) {
if ( $theme->condition !== $active_theme ) {
continue;
}
$full_list['themes']['items'][] = [
'id' => $theme_key,
'title' => $theme->title,
'icon' => $this->get_icon( $theme ),
];
}
return $full_list;
}
/**
* Fetch the icon.
*
* @param array $item item from the list.
* @return string
*/
private function get_icon( $item ) {
if ( empty( $item ) || empty( $item->icon_url ) ) {
return '';
}
return $item->icon_url;
}
/**
* Sanitizes delay JS options when saving the settings
*
* @since 3.13
*
* @param array $input Array of values submitted from the form.
*
* @return array
*/
public function sanitize_options( $input ): array {
if ( empty( $input['delay_js_exclusions_selected'] ) ) {
$input['delay_js_exclusions_selected'] = [];
$input['delay_js_exclusions_selected_exclusions'] = [];
return $input;
}
$input['delay_js_exclusions_selected_exclusions'] = $this->get_delayjs_items_exclusions( $input['delay_js_exclusions_selected'] );
return $input;
}
/**
* Refresh exclusions option based on selected items option.
*
* @return void
*/
public function refresh_exclusions_option() {
$slug = rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' );
$options = get_option( $slug, [] );
if ( empty( $options ) ) {
return;
}
$options['delay_js_exclusions_selected_exclusions'] = $this->get_delayjs_items_exclusions( $options['delay_js_exclusions_selected'] ?? [] );
update_option( $slug, $options );
}
/**
* Get plugin item ids from the list using plugin base.
*
* @param string $plugin_base Plugin basename.
*
* @return string[]
*/
private function get_plugin_item_ids( string $plugin_base ) {
$item_ids = [];
foreach ( $this->get_plugins_from_list() as $plugin_key => $plugin ) {
if ( $plugin_base !== $plugin->condition ) {
continue;
}
$item_ids[ $plugin_key ] = $plugin->is_default;
}
return $item_ids;
}
/**
* Add plugin exclusions only if plugin is default is checked in backend.
*
* @param string $plugin_base Plugin basename.
*
* @return void
*/
public function add_default_plugin_exclusions( string $plugin_base ) {
$plugin_item_ids = $this->get_plugin_item_ids( $plugin_base );
if ( empty( $plugin_item_ids ) ) {
return;
}
$selected_items = $this->options->get( 'delay_js_exclusions_selected', [] );
if ( empty( $selected_items ) ) {
return;
}
$current_selected_items = $selected_items;
foreach ( $plugin_item_ids as $plugin_item_id => $plugin_is_default ) {
if ( ! $plugin_is_default ) {
continue;
}
$selected_items[] = $plugin_item_id;
}
if ( $current_selected_items === $selected_items ) {
return;
}
$this->options->set( 'delay_js_exclusions_selected', $selected_items );
$this->options->set(
'delay_js_exclusions_selected_exclusions',
$this->get_delayjs_items_exclusions( $selected_items )
);
$this->options_api->set( 'settings', $this->options->get_options() );
}
/**
* Remove plugin selections from settings.
*
* @param string $plugin_base Plugin basename.
*
* @return void
*/
public function remove_plugin_selection( $plugin_base ) {
$plugin_item_ids = $this->get_plugin_item_ids( $plugin_base );
if ( empty( $plugin_item_ids ) ) {
return;
}
$selected_items = $this->options->get( 'delay_js_exclusions_selected', [] );
if ( empty( $selected_items ) ) {
return;
}
$current_selected_items = $selected_items;
foreach ( $plugin_item_ids as $plugin_item_id => $plugin_is_default ) {
$selected_item_key = array_search( $plugin_item_id, $selected_items, true );
if ( false === $selected_item_key ) {
continue;
}
unset( $selected_items[ $selected_item_key ] );
}
if ( $current_selected_items === $selected_items ) {
return;
}
$this->options->set( 'delay_js_exclusions_selected', $selected_items );
$this->options->set(
'delay_js_exclusions_selected_exclusions',
$this->get_delayjs_items_exclusions( $selected_items )
);
$this->options_api->set( 'settings', $this->options->get_options() );
}
/**
* Get theme name from theme object.
*
* @param WP_Theme $theme Theme to get its name.
*
* @return string
*/
private function get_theme_name( WP_Theme $theme ) {
$parent = $theme->get_template();
if ( ! empty( $parent ) ) {
return $parent;
}
return $theme->get( 'Name' );
}
/**
* Get Theme item ids from the list using theme name.
*
* @param string $theme_name Theme name.
*
* @return string[]
*/
private function get_theme_item_ids( $theme_name ) {
$item_ids = [];
foreach ( $this->get_themes_from_list() as $theme_key => $theme ) {
if ( $theme_name !== $theme->condition ) {
continue;
}
$item_ids[] = $theme_key;
}
return $item_ids;
}
/**
* Replace the old theme with the new theme exclusions.
*
* @param WP_Theme $new_theme WP_Theme instance of the new theme.
* @param WP_Theme $old_theme WP_Theme instance of the old theme.
*
* @return void
*/
public function replace_theme_selection( $new_theme, $old_theme ) {
$new_theme_ids = $this->get_theme_item_ids( $this->get_theme_name( $new_theme ) );
$old_theme_ids = $this->get_theme_item_ids( $this->get_theme_name( $old_theme ) );
if ( empty( $new_theme_ids ) && empty( $old_theme_ids ) ) {
return;
}
$selected_items = $this->options->get( 'delay_js_exclusions_selected', [] );
if ( empty( $selected_items ) ) {
return;
}
$current_selected_items = $selected_items;
if ( ! empty( $old_theme_ids ) ) {
foreach ( $old_theme_ids as $old_theme_id ) {
$selected_item_key = array_search( $old_theme_id, $selected_items, true );
if ( false === $selected_item_key ) {
continue;
}
unset( $selected_items[ $selected_item_key ] );
}
}
if ( ! empty( $new_theme_ids ) ) {
$themes = $this->get_themes_from_list();
foreach ( $new_theme_ids as $new_theme_id ) {
if ( ! $themes[ $new_theme_id ]->is_default ) {
continue;
}
$selected_items[] = $new_theme_id;
}
}
if ( $current_selected_items === $selected_items ) {
return;
}
$this->options->set( 'delay_js_exclusions_selected', $selected_items );
$this->options->set(
'delay_js_exclusions_selected_exclusions',
$this->get_delayjs_items_exclusions( $selected_items )
);
$this->options_api->set( 'settings', $this->options->get_options() );
}
/**
* Get default items from the list with their exclusions.
*
* @return array
*/
public function get_default_exclusions() {
$items = [];
$scripts = $this->get_scripts_from_list();
foreach ( $scripts as $script_key => $script ) {
if ( ! $script->is_default ) {
continue;
}
$items[ $script_key ] = $script->exclusions;
}
$active_plugins = $this->get_active_plugins();
foreach ( $this->get_plugins_from_list() as $plugin_key => $plugin ) {
if ( ! in_array( $plugin->condition, $active_plugins, true ) || ! $plugin->is_default ) {
continue;
}
$items[ $plugin_key ] = $plugin->exclusions;
}
$active_theme = $this->get_active_theme();
foreach ( $this->get_themes_from_list() as $theme_key => $theme ) {
if ( $theme->condition !== $active_theme || ! $theme->is_default ) {
continue;
}
$items[ $theme_key ] = $theme->exclusions;
}
/**
* Filters the delay JS default exclusions list.
* Key is the plugin/theme/script unique ID and value is array of exclusions
*
* @since 3.13
*
* @param array $items Array of default excluded items.
*/
return apply_filters( 'rocket_delay_js_default_exclusions', $items );
}
}
@@ -0,0 +1,214 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DelayJS\Admin;
use WP_Rocket\Engine\Admin\Settings\Settings as AdminSettings;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Theme;
class Subscriber implements Subscriber_Interface {
/**
* Settings instance
*
* @var Settings
*/
private $settings;
/**
* Site List instance.
*
* @var SiteList
*/
private $site_list;
/**
* Instantiate the class
*
* @param Settings $settings Settings instance.
* @param SiteList $site_list DelayJS Site List instance.
*/
public function __construct( Settings $settings, SiteList $site_list ) {
$this->settings = $settings;
$this->site_list = $site_list;
}
/**
* Return an array of events that this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_first_install_options' => [
[ 'add_options' ],
[ 'add_default_exclusions_options' ],
],
'wp_rocket_upgrade' => [ 'set_option_on_update', 13, 2 ],
'rocket_input_sanitize' => [
[ 'sanitize_options', 13, 2 ],
[ 'sanitize_selected_exclusions', 14 ],
],
'pre_update_option_wp_rocket_settings' => [ 'maybe_disable_combine_js', 11, 2 ],
'rocket_after_save_dynamic_lists' => 'refresh_exclusions_option',
'activate_plugin' => 'add_plugin_exclusions',
'deactivate_plugin' => 'remove_plugin_exclusions',
'switch_theme' => [ 'handle_switch_theme_exclusions', 10, 3 ],
'rocket_meta_boxes_fields' => [ 'add_meta_box', 6 ],
];
}
/**
* Add the delay JS options to the WP Rocket options array
*
* @param array $options WP Rocket options array.
*
* @return array
* @since 3.7
*/
public function add_options( $options ): array {
return $this->settings->add_options( $options );
}
/**
* Add the delay JS exclusions options to the WP Rocket options array
* based on the default items in the list.
*
* @param array $options WP Rocket options array.
*
* @return array
* @since 3.13
*/
public function add_default_exclusions_options( $options ): array {
$default_exclusions = $this->site_list->get_default_exclusions();
if ( empty( $default_exclusions ) ) {
$options['delay_js_exclusions_selected'] = [];
$options['delay_js_exclusions_selected_exclusions'] = [];
return $options;
}
$options['delay_js_exclusions_selected'] = array_keys( $default_exclusions );
$options['delay_js_exclusions_selected_exclusions'] = array_merge( ...array_values( $default_exclusions ) );
return $options;
}
/**
* Sets the delay_js_exclusions default value for users with delay JS enabled on upgrade
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
* @since 3.7
*
* @since 3.9 Sets the delay_js_exclusions default value if delay_js is 1
*/
public function set_option_on_update( $new_version, $old_version ) {
$this->settings->set_option_on_update( $old_version );
}
/**
* Sanitizes Delay JS options values when the settings form is submitted
*
* @param array $input Array of values submitted from the form.
* @param AdminSettings $settings Settings class instance.
*
* @return array
* @since 3.9
*/
public function sanitize_options( $input, AdminSettings $settings ): array {
return $this->settings->sanitize_options( $input, $settings );
}
/**
* Sanitizes delay JS selected exclusions options when saving the settings.
*
* @since 3.13
*
* @param array $input Array of values submitted from the form.
*
* @return array
*/
public function sanitize_selected_exclusions( $input ) {
return $this->site_list->sanitize_options( $input );
}
/**
* Disable combine JS option when delay JS is enabled
*
* @param array $value The new, unserialized option value.
* @param array $old_value The old option value.
*
* @return array
* @since 3.9
*/
public function maybe_disable_combine_js( $value, $old_value ): array {
return $this->settings->maybe_disable_combine_js( $value, $old_value );
}
/**
* Refresh exclusions option when the dynamic list is updated weekly or manually.
*
* @return void
*/
public function refresh_exclusions_option() {
$this->site_list->refresh_exclusions_option();
}
/**
* Remove plugin from exclusions list once deactivated.
*
* @param string $plugin Plugin basename.
*
* @return void
*/
public function remove_plugin_exclusions( string $plugin ) {
if ( plugin_basename( WP_ROCKET_FILE ) === $plugin ) {
return;
}
$this->site_list->remove_plugin_selection( $plugin );
}
/**
* Handle switch theme exclusions, remove the old theme exclusions and add the new one.
*
* @param string $new_name Name of the new theme.
* @param WP_Theme $new_theme WP_Theme instance of the new theme.
* @param WP_Theme $old_theme WP_Theme instance of the old theme.
*
* @return void
*/
public function handle_switch_theme_exclusions( string $new_name, WP_Theme $new_theme, WP_Theme $old_theme ) {
$this->site_list->replace_theme_selection( $new_theme, $old_theme );
}
/**
* Add plugin exclusions with plugin activation for default checked plugins.
*
* @param string $plugin Plugin basename.
*
* @return void
*/
public function add_plugin_exclusions( string $plugin ) {
if ( plugin_basename( WP_ROCKET_FILE ) === $plugin ) {
return;
}
$this->site_list->add_default_plugin_exclusions( $plugin );
}
/**
* 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['delay_js'] = __( 'Delay JavaScript execution', 'rocket' );
return $fields;
}
}
@@ -0,0 +1,304 @@
<?php
declare( strict_types=1 );
namespace WP_Rocket\Engine\Optimization\DelayJS;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\DynamicLists\DefaultLists\DataManager;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Logger\Logger;
class HTML {
use RegexTrait;
/**
* Plugin options instance.
*
* @var Options_Data
*/
protected $options;
/**
* DataManager instance
*
* @var DataManager
*/
private $data_manager;
/**
* Array of excluded patterns from delay JS
*
* @since 3.9
*
* @var array
*/
protected $excluded = [];
/**
* Allowed type attributes.
*
* @var array Array of allowed type attributes.
*/
private $allowed_types = [
'text/javascript',
'module',
'application/javascript',
'application/ecmascript',
'application/x-ecmascript',
'application/x-javascript',
'text/ecmascript',
'text/javascript1.0',
'text/javascript1.1',
'text/javascript1.2',
'text/javascript1.3',
'text/javascript1.4',
'text/javascript1.5',
'text/jscript',
'text/livescript',
'text/x-ecmascript',
'text/x-javascript',
];
/**
* Logger instance.
*
* @var Logger
*/
protected $logger;
/**
* Creates an instance of HTML.
*
* @param Options_Data $options Plugin options instance.
* @param DataManager $data_manager DataManager instance.
* @param Logger $logger Logger instance.
*/
public function __construct( Options_Data $options, DataManager $data_manager, Logger $logger ) {
$this->options = $options;
$this->data_manager = $data_manager;
$this->logger = $logger;
}
/**
* Adjust HTML to have delay js structure.
*
* @since 3.9 Updated to use exclusions list instead of inclusions list.
* @since 3.7
*
* @param string $html Buffer html for the page.
*
* @return string
*/
public function delay_js( $html ): string {
if ( ! $this->is_allowed() ) {
return $html;
}
$this->set_exclusions();
$this->excluded = array_merge( $this->excluded, $this->options->get( 'delay_js_exclusions', [] ) );
$this->excluded = array_merge( $this->excluded, $this->options->get( 'delay_js_exclusions_selected_exclusions', [] ) );
/**
* Filters the delay JS exclusions array
*
* @since 3.9
*
* @param array $excluded Array of excluded patterns.
*/
$this->excluded = (array) apply_filters( 'rocket_delay_js_exclusions', $this->excluded );
$this->excluded = array_map(
function ( $value ) {
if ( ! is_string( $value ) ) {
$value = (string) $value;
}
return str_replace(
[ '+', '?ver', '#' ],
[ '\+', '\?ver', '\#' ],
$value
);
},
$this->excluded
);
return $this->parse( $html );
}
/**
* Checks if is allowed to Delay JS.
*
* @since 3.7
*
* @return bool
*/
public function is_allowed(): bool {
if ( rocket_bypass() ) {
return false;
}
if ( rocket_get_constant( 'DONOTROCKETOPTIMIZE' ) ) {
return false;
}
if ( is_rocket_post_excluded_option( 'delay_js' ) ) {
return false;
}
return (bool) $this->options->get( 'delay_js', 0 );
}
/**
* Gets Javascript to redirect IE visitors to the uncached page
*
* @since 3.9
*
* @return string
*/
public function get_ie_fallback(): string {
return 'if(navigator.userAgent.match(/MSIE|Internet Explorer/i)||navigator.userAgent.match(/Trident\/7\..*?rv:11/i)){var href=document.location.href;if(!href.match(/[?&]nowprocket/)){if(href.indexOf("?")==-1){if(href.indexOf("#")==-1){document.location.href=href+"?nowprocket=1"}else{document.location.href=href.replace("#","?nowprocket=1#")}}else{if(href.indexOf("#")==-1){document.location.href=href+"&nowprocket=1"}else{document.location.href=href.replace("#","&nowprocket=1#")}}}}';
}
/**
* Parse the html and add/remove attributes from specific scripts.
*
* @since 3.7
*
* @param string $html Buffer html for the page.
*
* @return string
*/
private function parse( $html ): string {
if ( empty( $html ) ) {
return $html;
}
$result = $this->replace_xmp_tags( $html );
$result = $this->replace_svg_tags( $result );
$replaced_html = preg_replace_callback(
'/<\s*script(?<attr>\s*[^>]*?)?>(?<content>.*?)?<\s*\/\s*script\s*>/ims',
[
$this,
'replace_scripts',
],
$result
);
if ( empty( $replaced_html ) ) {
return $html;
}
$replaced_html = $this->restore_xmp_tags( $replaced_html );
return $this->restore_svg_tags( $replaced_html );
}
/**
* Callback method for preg_replace_callback that is used to adjust attributes for scripts.
*
* @since 3.9 Use exclusions list & fake type attribute.
* @since 3.7
*
* @param array $matches Matches array for scripts regex.
*
* @return string
*/
public function replace_scripts( $matches ): string {
foreach ( $this->excluded as $pattern ) {
if ( preg_match( "#{$pattern}#i", $matches[0] ) ) {
$this->logger->debug( "DelayJS: Script {$matches[0]} excluded by $pattern" );
return $matches[0];
}
}
if ( empty( $matches['attr'] ) ) {
return '<script type="rocketlazyloadscript">' . $matches['content'] . '</script>';
}
$type_regex = '/type\s*=\s*(["\'])(?<type>.*)\1/i';
preg_match( $type_regex . 'U', $matches['attr'], $type_matches );
if (
! empty( $type_matches )
&&
! empty( trim( $type_matches['type'] ) )
&&
! in_array( trim( $type_matches['type'] ), $this->allowed_types, true )
) {
return $matches[0];
}
$matches['attr'] = preg_replace( $type_regex, 'data-rocket-type=$1$2$1', $matches['attr'] );
// To remove type attribute without any value.
$matches['attr'] = preg_replace( '/(\s+type\s+)|(^type\s+)|(\s+type$)/i', '', $matches['attr'] );
// Checks if script has src attribute so then treat as external script and replace src with data-rocket-src.
$src_regex = '/src\s*=\s*(["\'])(.*)\1/i';
$matches['attr'] = preg_replace( $src_regex, 'data-rocket-src=$1$2$1', $matches['attr'] );
return '<script type="rocketlazyloadscript" ' . trim( $matches['attr'] ) . '>' . $matches['content'] . '</script>';
}
/**
* Move meta charset to head if not found to the top of page content.
*
* @since 3.9.4
*
* @param string $html Html content.
*
* @return string
*/
public function move_meta_charset_to_head( $html ): string {
$meta_pattern = "#<meta[^h]*(http-equiv[^=]*=[^\'\"]*[\'\" ]Content-Type[\'\"][ ]*[^>]*|)(charset[^=]*=[ ]*[\'\" ]*[^\'\"> ][^\'\">]+[^\'\"> ][\'\" ]*|charset[^=]*=*[^\'\"> ][^\'\">]+[^\'\"> ])([^>]*|)>(?=.*</head>)#Usmi";
if ( ! preg_match( $meta_pattern, $html, $matches ) ) {
return $html;
}
$replaced_html = preg_replace( "$meta_pattern", '', $html );
if ( empty( $replaced_html ) ) {
return $html;
}
if ( preg_match( '/<head\b/i', $replaced_html ) ) {
$replaced_html = preg_replace( '/(<head\b[^>]*?>)/i', "\${1}{$matches[0]}", $replaced_html, 1 );
if ( empty( $replaced_html ) ) {
return $html;
}
return $replaced_html;
}
if ( preg_match( '/<html\b/i', $replaced_html ) ) {
$replaced_html = preg_replace( '/(<html\b[^>]*?>)/i', "\${1}{$matches[0]}", $replaced_html, 1 );
if ( empty( $replaced_html ) ) {
return $html;
}
return $replaced_html;
}
$replaced_html = preg_replace( '/(<\w+)/', "{$matches[0]}\${1}", $replaced_html, 1 );
if ( empty( $replaced_html ) ) {
return $html;
}
return $replaced_html;
}
/**
* Get exclusions
*
* @return void
*/
private function set_exclusions() {
$lists = $this->data_manager->get_lists();
$this->excluded = isset( $lists->delay_js_exclusions ) ? $lists->delay_js_exclusions : [];
}
}
@@ -0,0 +1,60 @@
<?php
namespace WP_Rocket\Engine\Optimization\DelayJS;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Optimization\DelayJS\Admin\Settings;
use WP_Rocket\Engine\Optimization\DelayJS\Admin\SiteList;
use WP_Rocket\Engine\Optimization\DelayJS\Admin\Subscriber as AdminSubscriber;
use WP_Rocket\Logger\Logger;
/**
* Service provider for the WP Rocket Delay JS
*
* @since 3.7
*/
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 = [
'delay_js_settings',
'delay_js_admin_subscriber',
'delay_js_html',
'delay_js_subscriber',
'delay_js_sitelist',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$this->getContainer()->add( 'delay_js_sitelist', SiteList::class )
->addArgument( $this->getContainer()->get( 'dynamic_lists' ) )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'options_api' ) );
$this->getContainer()->add( 'delay_js_settings', Settings::class )
->addArgument( $this->getContainer()->get( 'options_api' ) );
$this->getContainer()->share( 'delay_js_admin_subscriber', AdminSubscriber::class )
->addArgument( $this->getContainer()->get( 'delay_js_settings' ) )
->addArgument( $this->getContainer()->get( 'delay_js_sitelist' ) )
->addTag( 'admin_subscriber' );
$this->getContainer()->add( 'delay_js_html', HTML::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'dynamic_lists_defaultlists_data_manager' ) )
->addArgument( new Logger() );
$this->getContainer()->share( 'delay_js_subscriber', Subscriber::class )
->addArgument( $this->getContainer()->get( 'delay_js_html' ) )
->addArgument( rocket_direct_filesystem() )
->addArgument( $this->getContainer()->get( 'options' ) )
->addTag( 'front_subscriber' );
}
}
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DelayJS;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
class Subscriber implements Subscriber_Interface {
/**
* HTML instance.
*
* @since 3.7
*
* @var HTML
*/
private $html;
/**
* WP_Filesystem_Direct instance.
*
* @since 3.7
*
* @var \WP_Filesystem_Direct
*/
private $filesystem;
/**
* Options Data instance
*
* @var Options_Data
*/
private $options;
/**
* Script enqueued status.
*
* @since 3.7
*
* @var bool
*/
private $is_enqueued = false;
/**
* Subscriber constructor.
*
* @param HTML $html HTML Instance.
* @param \WP_Filesystem_Direct $filesystem The Filesystem object.
* @param Options_Data $options Options data instance.
*/
public function __construct( HTML $html, $filesystem, Options_Data $options ) {
$this->html = $html;
$this->filesystem = $filesystem;
$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 [
'rocket_buffer' => [
[ 'delay_js', 26 ],
[ 'add_delay_js_script', 26 ],
],
'pre_get_rocket_option_minify_concatenate_js' => 'maybe_disable_option',
];
}
/**
* Modifies scripts HTML to apply delay JS attribute
*
* @since 3.7
*
* @param string $buffer_html Html for the page.
*
* @return string
*/
public function delay_js( $buffer_html ) {
return $this->html->delay_js( $buffer_html );
}
/**
* Displays the inline script to the head when the option is enabled.
*
* @since 3.9.4 Move meta charset to head.
* @since 3.9 Hooked on rocket_buffer, display the script right after <head>
* @since 3.7
*
* @param string $html HTML content.
*
* @return string
*/
public function add_delay_js_script( $html ): string {
if ( ! $this->html->is_allowed() ) {
return $html;
}
$pattern = '/<head[^>]*>/i';
$lazyload_script = $this->filesystem->get_contents( rocket_get_constant( 'WP_ROCKET_PATH' ) . 'assets/js/lazyload-scripts.min.js' );
$replaced_html = $html;
if ( false !== $lazyload_script ) {
$replaced_html = preg_replace( $pattern, "$0<script>{$lazyload_script}</script>", $replaced_html, 1 );
if ( empty( $replaced_html ) ) {
return $html;
}
}
$replaced_html = preg_replace( $pattern, '$0<script>' . $this->html->get_ie_fallback() . '</script>', $replaced_html, 1 );
if ( empty( $replaced_html ) ) {
return $html;
}
return $this->html->move_meta_charset_to_head( $replaced_html );
}
/**
* Disables defer JS if delay JS is enabled
*
* @since 3.9
*
* @param null $value Original value. Should be always null.
*
* @return null|false
*/
public function maybe_disable_option( $value ) {
if ( $this->html->is_allowed() ) {
return false;
}
return $value;
}
}
@@ -0,0 +1,140 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists;
use WP_Error;
use WP_Rocket\Admin\Options_Data;
abstract class AbstractAPIClient {
/**
* API URL.
*/
const API_URL = 'https://b.rucss.wp-rocket.me/api/';
/**
* Response Code.
*
* @var int
*/
private $response_code = 200;
/**
* Error message.
*
* @var string
*/
private $error_message = '';
/**
* Response Body.
*
* @var string
*/
private $response_body = '';
/**
* Plugin options instance.
*
* @var Options_Data
*/
private $options;
/**
* Instantiate the class.
*
* @param Options_Data $options Options instance.
*/
public function __construct( Options_Data $options ) {
$this->options = $options;
}
/**
* Specify API endpoint path.
*
* @return string
*/
abstract protected function get_api_path();
/**
* Get exclusions list.
*
* @param string $hash Hash of lists content to compare.
*
* @return array
*/
public function get_exclusions_list( $hash ) {
$args = [
'body' => [
'hash' => $hash,
],
'timeout' => 5,
];
if ( ! $this->handle_request( $args ) ) {
return [
'code' => $this->response_code,
'message' => $this->error_message,
];
}
return [
'code' => $this->response_code,
'body' => $this->response_body,
];
}
/**
* Handle the request.
*
* @param array $args Passed arguments.
*
* @return bool
*/
private function handle_request( array $args ) {
$api_url = rocket_get_constant( 'WP_ROCKET_EXCLUSIONS_API_URL', false )
? rocket_get_constant( 'WP_ROCKET_EXCLUSIONS_API_URL', false )
: self::API_URL;
if ( empty( $args['body'] ) ) {
$args['body'] = [];
}
$args['body']['credentials'] = [
'wpr_email' => $this->options->get( 'consumer_email', '' ),
'wpr_key' => $this->options->get( 'consumer_key', '' ),
];
$response = wp_remote_get(
$api_url . $this->get_api_path(),
$args
);
return $this->check_response( $response );
}
/**
* Handle SaaS request error.
*
* @param array|WP_Error $response WP Remote request.
*
* @return bool
*/
private function check_response( $response ): bool {
$this->response_code = is_array( $response )
? wp_remote_retrieve_response_code( $response )
: $response->get_error_code();
if ( 200 !== $this->response_code && 206 !== $this->response_code ) {
$this->error_message = is_array( $response )
? wp_remote_retrieve_response_message( $response )
: $response->get_error_message();
return false;
}
$this->response_body = wp_remote_retrieve_body( $response );
return true;
}
}
@@ -0,0 +1,160 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists;
use WP_Filesystem_Direct;
use StdClass;
abstract class AbstractDataManager {
/**
* Filesystem instance
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Cache ttl.
*
* @var int
*/
protected $cache_duration = WEEK_IN_SECONDS;
/**
* Instantiate the class
*
* @param WP_Filesystem_Direct $filesystem Filesystem instance.
*/
public function __construct( $filesystem = null ) {
$this->filesystem = is_null( $filesystem ) ? rocket_direct_filesystem() : $filesystem;
}
/**
* Get cache transient name.
*
* @return string
*/
abstract protected function get_cache_transient_name();
/**
* Get lists json filename.
*
* @return string
*/
abstract protected function get_json_filename();
/**
* Gets the lists content
*
* @return object
*/
public function get_lists() {
$transient = get_transient( $this->get_cache_transient_name() );
if ( false !== $transient ) {
return $transient;
}
$json = $this->get_lists_from_file();
$lists = json_decode( $json );
if ( empty( $lists ) ) {
return new StdClass();
}
$this->set_lists_cache( $lists );
return $lists;
}
/**
* Returns the hash of the current JSON
*
* @return string
*/
public function get_lists_hash() {
return md5( $this->get_lists_from_file() );
}
/**
* Save dynamic lists on file & transient
*
* @param string $content Lists content.
*
* @return boolean
*/
public function save_dynamic_lists( string $content ) {
$result = $this->put_lists_to_file( $content );
$lists = json_decode( $content );
$this->set_lists_cache( $lists );
return $result;
}
/**
* Gets the path to the dynamic lists JSON file
*
* @return string
*/
private function get_json_filepath(): string {
return rocket_get_constant( 'WP_ROCKET_CONFIG_PATH', '' ) . $this->get_json_filename() . '.json';
}
/**
* Gets lists JSON content from file
*
* @return string
*/
private function get_lists_from_file(): string {
$content = '';
$lists_filepath = $this->get_json_filepath();
if ( $this->filesystem->exists( $lists_filepath ) ) {
$content = $this->filesystem->get_contents( $lists_filepath );
}
if ( ! empty( $content ) ) {
return $content;
}
$fallback_filepath = rocket_get_constant( 'WP_ROCKET_PATH', '' ) . $this->get_json_filename() . '.json';
if ( $this->filesystem->exists( $fallback_filepath ) ) {
$content = $this->filesystem->get_contents( $fallback_filepath );
}
if ( ! empty( $content ) ) {
$this->put_lists_to_file( $content );
return $content;
}
return $content;
}
/**
* Write lists content to JSON file
*
* @param string $content JSON content.
*
* @return bool
*/
private function put_lists_to_file( string $content ): bool {
return $this->filesystem->put_contents( $this->get_json_filepath(), $content, rocket_get_filesystem_perms( 'file' ) );
}
/**
* Sets transient for lists content
*
* @param object $content Lists content.
*
* @return void
*/
private function set_lists_cache( $content ) {
set_transient( $this->get_cache_transient_name(), $content, $this->cache_duration );
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists\DefaultLists;
use WP_Rocket\Engine\Optimization\DynamicLists\AbstractAPIClient;
class APIClient extends AbstractAPIClient {
/**
* Specify API endpoint path.
*
* @return string
*/
protected function get_api_path() {
return 'exclusions/list';
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists\DefaultLists;
use WP_Rocket\Engine\Optimization\DynamicLists\AbstractDataManager;
class DataManager extends AbstractDataManager {
/**
* Get cache transient name.
*
* @return string
*/
protected function get_cache_transient_name() {
return 'wpr_dynamic_lists';
}
/**
* Get lists json filename.
*
* @return string
*/
protected function get_json_filename() {
return 'dynamic-lists';
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists\DelayJSLists;
use WP_Rocket\Engine\Optimization\DynamicLists\AbstractAPIClient;
class APIClient extends AbstractAPIClient {
/**
* Specify API endpoint path.
*
* @return string
*/
protected function get_api_path() {
return 'delay-js-exclusions/list';
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists\DelayJSLists;
use WP_Rocket\Engine\Optimization\DynamicLists\AbstractDataManager;
class DataManager extends AbstractDataManager {
/**
* Get cache transient name.
*
* @return string
*/
protected function get_cache_transient_name() {
return 'wpr_dynamic_lists_delayjs';
}
/**
* Get lists json filename.
*
* @return string
*/
protected function get_json_filename() {
return 'dynamic-lists-delayjs';
}
}
@@ -0,0 +1,283 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists;
use WP_Rocket\Abstract_Render;
use WP_Rocket\Engine\Admin\Beacon\Beacon;
use WP_Rocket\Engine\License\API\User;
use WP_REST_Response;
use WP_Error;
class DynamicLists extends Abstract_Render {
/**
* Providers array.
* Array of objects with keys: api_client and data_manager.
*
* @var array
*/
private $providers;
/**
* User instance
*
* @var User
*/
private $user;
/**
* Beacon instance
*
* @var Beacon
*/
private $beacon;
/**
* Route Rest API namespace.
*/
const ROUTE_NAMESPACE = 'wp-rocket/v1';
/**
* Instantiate the class.
*
* @param array $providers Lists providers.
* @param User $user User instance.
* @param string $template_path Path to views.
* @param Beacon $beacon Beacon instance.
*/
public function __construct( array $providers, User $user, $template_path, Beacon $beacon ) {
parent::__construct( $template_path );
$this->providers = $providers;
$this->user = $user;
$this->beacon = $beacon;
}
/**
* Registers the dynamic lists update route
*
* @return void
*/
public function register_rest_route() {
register_rest_route(
self::ROUTE_NAMESPACE,
'dynamic_lists/update',
[
'methods' => 'PUT',
'callback' => [ $this, 'rest_update_response' ],
'permission_callback' => [ $this, 'check_permissions' ],
]
);
}
/**
* Checks user's permissions. This is a callback registered to REST route's "permission_callback" parameter.
*
* @return bool true if the user has permission; else false.
*/
public function check_permissions() {
return current_user_can( 'rocket_manage_options' );
}
/**
* Returns the update response
*
* @return WP_REST_Response|WP_Error
*/
public function rest_update_response() {
return rest_ensure_response( $this->update_lists_from_remote() );
}
/**
* Updates the lists from remote
*
* @return array
*/
public function update_lists_from_remote() {
if ( $this->user->is_license_expired() ) {
return [
'success' => false,
'data' => '',
'message' => __( 'You need an active license to get the latest version of the lists from our server.', 'rocket' ),
];
}
$response = [];
$success = false;
$should_purge = false;
foreach ( $this->providers as $provider ) {
$result = $provider->api_client->get_exclusions_list( $provider->data_manager->get_lists_hash() );
if ( empty( $result['code'] ) || empty( $result['body'] ) ) {
$response[ $provider->title ] = [
'success' => false,
'data' => '',
'message' => __( 'Could not get updated lists from server.', 'rocket' ),
];
continue;
}
if ( 206 === $result['code'] ) {
$response[ $provider->title ] = [
'success' => true,
'data' => '',
'message' => __( 'Lists are up to date.', 'rocket' ),
];
continue;
}
if ( ! $provider->data_manager->save_dynamic_lists( $result['body'] ) ) {
$response[ $provider->title ] = [
'success' => false,
'data' => '',
'message' => __( 'Could not update lists.', 'rocket' ),
];
continue;
}
$success = true;
$response[ $provider->title ] = [
'success' => true,
'data' => '',
'message' => __( 'Lists are successfully updated.', 'rocket' ),
];
$should_purge |= $provider->clear_cache ?? true;
}
if ( $success ) {
/**
* Fires after saving all dynamic lists files.
*
* @since 3.12.1
*
* @param bool $should_purge Should purge status based on the updated providers.
*/
do_action( 'rocket_after_save_dynamic_lists', $should_purge );
}
return $response;
}
/**
* Schedule cron to update dynamic lists weekly.
*
* @return void
*/
public function schedule_lists_update() {
if ( ! wp_next_scheduled( 'rocket_update_dynamic_lists' ) ) {
wp_schedule_event( time(), 'weekly', 'rocket_update_dynamic_lists' );
}
}
/**
* Clear dynamic lists update event.
*/
public function clear_schedule_lists_update() {
wp_clear_scheduled_hook( 'rocket_update_dynamic_lists' );
}
/**
* Displays the dynamic lists update section on tools tab
*
* @return void
*/
public function display_update_lists_section() {
if ( ! current_user_can( 'rocket_manage_options' ) ) {
return;
}
$data = [
'beacon' => $this->beacon->get_suggest( 'dynamic_lists' ),
];
echo $this->generate( 'settings/dynamic-lists-update', $data ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Get the cached ignored parameters
*
* @return array
*/
public function get_cache_ignored_parameters(): array {
$lists = $this->providers['defaultlists']->data_manager->get_lists();
return isset( $lists->cache_ignored_parameters ) ? array_flip( $lists->cache_ignored_parameters ) : [];
}
/**
* Get the JS minify excluded external paths
*
* @return array
*/
public function get_js_minify_excluded_external(): array {
$lists = $this->providers['defaultlists']->data_manager->get_lists();
return isset( $lists->js_minify_external ) ? $lists->js_minify_external : [];
}
/**
* Get the patterns to move after the combine JS file
*
* @return array
*/
public function get_js_move_after_combine(): array {
$lists = $this->providers['defaultlists']->data_manager->get_lists();
return isset( $lists->js_move_after_combine ) ? $lists->js_move_after_combine : [];
}
/**
* Get the inline JS excluded from combine JS
*
* @return array
*/
public function get_combine_js_excluded_inline(): array {
$lists = $this->providers['defaultlists']->data_manager->get_lists();
return isset( $lists->js_excluded_inline ) ? $lists->js_excluded_inline : [];
}
/**
* Get the preload exclusions
*
* @return array
*/
public function get_preload_exclusions(): array {
$lists = $this->providers['defaultlists']->data_manager->get_lists();
return isset( $lists->preload_exclusions ) ? $lists->preload_exclusions : [];
}
/**
* Get Delay JS dynamic list.
*
* @return array
*/
public function get_delayjs_list() {
return $this->providers['delayjslists']->data_manager->get_lists();
}
/**
* Get the JS minify excluded files
*
* @return array
*/
public function get_js_exclude_files(): array {
$lists = $this->providers['defaultlists']->data_manager->get_lists();
return isset( $lists->exclude_js_files ) ? $lists->exclude_js_files : [];
}
/**
* Get the incompatible plugins list
*
* @return array
*/
public function get_incompatible_plugins() {
$lists = $this->providers['incompatible_plugins']->data_manager->get_plugins_list();
return isset( $lists ) ? $lists : [];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists\IncompatiblePluginsLists;
use WP_Rocket\Engine\Optimization\DynamicLists\AbstractAPIClient;
class APIClient extends AbstractAPIClient {
/**
* Specify API endpoint path.
*
* @return string
*/
protected function get_api_path() {
return 'incompatible-plugins/list';
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists\IncompatiblePluginsLists;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\DynamicLists\AbstractDataManager;
class DataManager extends AbstractDataManager {
/**
* Plugin options instance.
*
* @var Options_Data
*/
private $options;
/**
* Instantiate the class.
*
* @param Options_Data $options Options instance.
*/
public function __construct( Options_Data $options ) {
parent::__construct();
$this->options = $options;
}
/**
* Get cache transient name.
*
* @return string
*/
protected function get_cache_transient_name() {
return 'wpr_dynamic_lists_incompatible_plugins';
}
/**
* Get lists json filename.
*
* @return string
*/
protected function get_json_filename() {
return 'dynamic-lists-incompatible-plugins';
}
/**
* Gets the plugins list content
*
* @return array
*/
public function get_plugins_list() {
$lists = [];
$list_from_json = $this->get_lists();
foreach ( $list_from_json as $conditions => $list ) {
if ( $this->meet_conditions( $conditions ) ) {
$list = array_column( $list, 'file', 'slug' );
$lists = array_merge( $lists, $list );
}
}
return $lists;
}
/**
* Check if the condition is meet based on plugin option and condition string.
* If $conditions contain "||" split and treat it like or
*
* @param string $conditions condition.
*
* @return bool
*/
private function meet_conditions( $conditions = '' ) {
if ( empty( $conditions ) ) {
return true;
}
$conditions = explode( '||', $conditions );
foreach ( $conditions as $condition ) {
if ( $this->options->get( trim( $condition ), false ) ) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,86 @@
<?php
namespace WP_Rocket\Engine\Optimization\DynamicLists;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Optimization\DynamicLists\DefaultLists\APIClient as DefaultListsAPIClient;
use WP_Rocket\Engine\Optimization\DynamicLists\DefaultLists\DataManager as DefaultListsDataManager;
use WP_Rocket\Engine\Optimization\DynamicLists\DelayJSLists\APIClient as DelayJSListsAPIClient;
use WP_Rocket\Engine\Optimization\DynamicLists\DelayJSLists\DataManager as DelayJSListsDataManager;
use WP_Rocket\Engine\Optimization\DynamicLists\IncompatiblePluginsLists\DataManager as IncompatiblePluginsListsDataManager;
use WP_Rocket\Engine\Optimization\DynamicLists\IncompatiblePluginsLists\APIClient as IncompatiblePluginsListsAPIClient;
/**
* Service provider for the WP Rocket DynamicLists
*/
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 = [
'dynamic_lists_defaultlists_data_manager',
'dynamic_lists_defaultlists_api_client',
'dynamic_lists_delayjslists_data_manager',
'dynamic_lists_delayjslists_api_client',
'dynamic_lists_incompatible_plugins_lists_data_manager',
'dynamic_lists_incompatible_plugins_lists_api_client',
'dynamic_lists',
'dynamic_lists_subscriber',
];
/**
* Registers the option array in the container
*
* @return void
*/
public function register() {
$this->getContainer()->add( 'dynamic_lists_defaultlists_data_manager', DefaultListsDataManager::class );
$this->getContainer()->add( 'dynamic_lists_defaultlists_api_client', DefaultListsAPIClient::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$this->getContainer()->add( 'dynamic_lists_delayjslists_data_manager', DelayJSListsDataManager::class );
$this->getContainer()->add( 'dynamic_lists_delayjslists_api_client', DelayJSListsAPIClient::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$this->getContainer()->add( 'dynamic_lists_incompatible_plugins_lists_data_manager', IncompatiblePluginsListsDataManager::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$this->getContainer()->add( 'dynamic_lists_incompatible_plugins_lists_api_client', IncompatiblePluginsListsAPIClient::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$providers = [
'defaultlists' =>
(object) [
'api_client' => $this->getContainer()->get( 'dynamic_lists_defaultlists_api_client' ),
'data_manager' => $this->getContainer()->get( 'dynamic_lists_defaultlists_data_manager' ),
'title' => __( 'Default Lists', 'rocket' ),
],
'delayjslists' =>
(object) [
'api_client' => $this->getContainer()->get( 'dynamic_lists_delayjslists_api_client' ),
'data_manager' => $this->getContainer()->get( 'dynamic_lists_delayjslists_data_manager' ),
'title' => __( 'Delay JavaScript Execution Exclusion Lists', 'rocket' ),
],
'incompatible_plugins' =>
(object) [
'api_client' => $this->getContainer()->get( 'dynamic_lists_incompatible_plugins_lists_api_client' ),
'data_manager' => $this->getContainer()->get( 'dynamic_lists_incompatible_plugins_lists_data_manager' ),
'title' => __( 'Incompatible plugins Lists', 'rocket' ),
'clear_cache' => false,
],
];
$this->getContainer()->add( 'dynamic_lists', DynamicLists::class )
->addArgument( $providers )
->addArgument( $this->getContainer()->get( 'user' ) )
->addArgument( $this->getContainer()->get( 'template_path' ) )
->addArgument( $this->getContainer()->get( 'beacon' ) );
$this->getContainer()->share( 'dynamic_lists_subscriber', Subscriber::class )
->addArgument( $this->getContainer()->get( 'dynamic_lists' ) );
}
}
@@ -0,0 +1,204 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\DynamicLists;
use WP_Rocket\Event_Management\Subscriber_Interface;
class Subscriber implements Subscriber_Interface {
/**
* DynamicLists instance
*
* @var DynamicLists
*/
private $dynamic_lists;
/**
* Instantiate the class
*
* @param DynamicLists $dynamic_lists DynamicLists instance.
*/
public function __construct( DynamicLists $dynamic_lists ) {
$this->dynamic_lists = $dynamic_lists;
}
/**
* Events this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rest_api_init' => 'register_rest_route',
'rocket_localize_admin_script' => [ 'add_dynamic_lists_script', 11 ],
'init' => 'schedule_lists_update',
'rocket_update_dynamic_lists' => 'update_lists',
'rocket_deactivation' => 'clear_schedule_lists_update',
'rocket_settings_tools_content' => 'display_update_lists_section',
'rocket_cache_ignored_parameters' => 'add_cache_ignored_parameters',
'rocket_minify_excluded_external_js' => 'add_minify_excluded_external_js',
'rocket_move_after_combine_js' => 'add_move_after_combine_js',
'rocket_excluded_inline_js_content' => 'add_combine_js_excluded_inline',
'rocket_preload_exclude_urls' => 'add_preload_exclusions',
'rocket_exclude_js' => 'add_js_exclude_files',
'rocket_plugins_to_deactivate' => 'add_incompatible_plugins_to_deactivate',
];
}
/**
* Registers the REST dynamic lists update route
*
* @return void
*/
public function register_rest_route() {
$this->dynamic_lists->register_rest_route();
}
/**
* Add REST data to our localize script data.
*
* @param array $data Localize script data.
* @return array
*/
public function add_dynamic_lists_script( $data ) {
$data['rest_url'] = rest_url( 'wp-rocket/v1/dynamic_lists/update/' );
$data['rest_nonce'] = wp_create_nonce( 'wp_rest' );
return $data;
}
/**
* Scheduling the dynamic lists update cron event.
*/
public function schedule_lists_update() {
$this->dynamic_lists->schedule_lists_update();
}
/**
* Clear the dynamic lists update cron event.
*
* @return void
*/
public function clear_schedule_lists_update() {
$this->dynamic_lists->clear_schedule_lists_update();
}
/**
* Update dynamic lists from API.
*
* * @return void
*/
public function update_lists() {
$this->dynamic_lists->update_lists_from_remote();
}
/**
* Displays the dynamic lists update section on tools tab
*
* @return void
*/
public function display_update_lists_section() {
$this->dynamic_lists->display_update_lists_section();
}
/**
* Add the cached ignored parameters to the array
*
* @param string $params Array of ignored parameters.
*
* @return array
*/
public function add_cache_ignored_parameters( $params = [] ): array {
if ( ! is_array( $params ) ) {
$params = (array) $params;
}
return array_merge( $params, $this->dynamic_lists->get_cache_ignored_parameters() );
}
/**
* Add the excluded external JS patterns to the array
*
* @param string $excluded Array of excluded patterns.
*
* @return array
*/
public function add_minify_excluded_external_js( $excluded = [] ): array {
if ( ! is_array( $excluded ) ) {
$excluded = (array) $excluded;
}
return array_merge( $excluded, $this->dynamic_lists->get_js_minify_excluded_external() );
}
/**
* Add the JS patterns to move after the combine JS file to the array
*
* @param string $excluded Array of patterns to move.
*
* @return array
*/
public function add_move_after_combine_js( $excluded = [] ): array {
if ( ! is_array( $excluded ) ) {
$excluded = (array) $excluded;
}
return array_merge( $excluded, $this->dynamic_lists->get_js_move_after_combine() );
}
/**
* Add the excluded inline JS patterns to the array
*
* @param string $excluded Array of excluded patterns.
*
* @return array
*/
public function add_combine_js_excluded_inline( $excluded = [] ): array {
if ( ! is_array( $excluded ) ) {
$excluded = (array) $excluded;
}
return array_merge( $excluded, $this->dynamic_lists->get_combine_js_excluded_inline() );
}
/**
* Add the preload exclusions to the array
*
* @param array $excluded Array of ignored URL regex.
*
* @return array
*/
public function add_preload_exclusions( $excluded = [] ): array {
if ( ! is_array( $excluded ) ) {
$excluded = (array) $excluded;
}
return array_merge( $excluded, $this->dynamic_lists->get_preload_exclusions() );
}
/**
* Add the js files exclusions to the array
*
* @param array $js_files Array of files.
*
* @return array
*/
public function add_js_exclude_files( $js_files = [] ): array {
if ( ! is_array( $js_files ) ) {
$js_files = (array) $js_files;
}
return array_merge( $js_files, $this->dynamic_lists->get_js_exclude_files() );
}
/**
* Add incompatible plugins to the array
*
* @param array $plugins Array of $plugins.
*
* @return array
*/
public function add_incompatible_plugins_to_deactivate( $plugins = [] ): array {
return array_merge( (array) $plugins, $this->dynamic_lists->get_incompatible_plugins() );
}
}
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
/**
* Abstract Optimization Parent Class for Google Fonts Optimizers.
*
* @since 3.8
*/
abstract class AbstractGFOptimization {
/**
* Allowed display values.
*
* @since 3.8
*
* @var array
*/
protected $display_values = [
'auto' => 1,
'block' => 1,
'swap' => 1,
'fallback' => 1,
'optional' => 1,
];
/**
* Flag for whether google fonts have been detected (Default: true)
*
* @since 3.8.8
*
* @var bool
*/
protected $has_google_fonts = true;
/**
* Optimize Google Fonts
*
* @param string $html HTML content.
*
* @return string
*/
abstract public function optimize( $html ): string;
/**
* Check whether the optimizer has found google fonts on the page.
*
* @since 3.8.8
*
* @return bool Will default to true when extending classes have not set via the optimize() method.
*/
public function has_google_fonts() {
return $this->has_google_fonts;
}
/**
* Returns font with display value.
*
* @since 3.8 Moved here from GoogleFonts\Combine::class
* @since 3.5.1
*
* @param array $font Array containing font tag and matches.
*
* @return string Google Font tag with display param.
*/
protected function get_font_with_display( array $font ) {
$font_url = html_entity_decode( $font['url'] );
$query = wp_parse_url( $font_url, PHP_URL_QUERY );
if ( empty( $query ) ) {
return $font[0];
}
$parsed_font = wp_parse_args( $query );
$font_url = ! empty( $parsed_font['display'] )
? str_replace( "&display={$parsed_font['display']}", '&display=swap', $font_url )
: "{$font_url}&display=swap";
return str_replace( $font['url'], esc_url( $font_url ), $font[0] );
}
/**
* Get the font display value.
*
* @since 3.8 Moved here from GoogleFonts\Combine::class
* @since 3.5.1
*
* @return string font display value.
*/
protected function get_font_display_value(): string {
/**
* Filters the combined Google Fonts display parameter value
*
* @since 3.8 Moved here from GoogleFonts\Combine::class
* @since 3.3.5
*
* @param string $display Display value. Can be either auto, block, swap, fallback or optional.
*/
$display = apply_filters( 'rocket_combined_google_fonts_display', 'swap' );
if ( ! is_string( $display ) ) {
return 'swap';
}
return isset( $this->display_values[ $display ] ) ? $display : 'swap';
}
/**
* Returns the optimized markup for Google Fonts
*
* @since 3.9.1
*
* @param string $url Google Fonts URL.
*
* @return string
*/
protected function get_optimized_markup( string $url ): string {
return sprintf(
'<link rel="preload" as="style" href="%1$s" /><link rel="stylesheet" href="%1$s" media="print" onload="this.media=\'all\'" /><noscript><link rel="stylesheet" href="%1$s" /></noscript>', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
$url
);
}
}
@@ -0,0 +1,85 @@
<?php
namespace WP_Rocket\Engine\Optimization\GoogleFonts\Admin;
use WP_Rocket\Abstract_Render;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Admin\Beacon\Beacon;
class Settings extends Abstract_Render {
/**
* WP Rocket options instance
*
* @var Options_Data
*/
private $options;
/**
* Beacon instance
*
* @var Beacon
*/
private $beacon;
/**
* Instantiate the class
*
* @param Options_Data $options WP Rocket options instance.
* @param Beacon $beacon Beacon instance.
* @param string $template_path Path to template files.
*/
public function __construct( Options_Data $options, Beacon $beacon, $template_path ) {
parent::__construct( $template_path );
$this->options = $options;
$this->beacon = $beacon;
}
/**
* Displays the Google Fonts Optimization section in the tools tab
*
* @since 3.7
*
* @return void
*/
public function display_google_fonts_enabler() {
if ( ! current_user_can( 'rocket_manage_options' ) ) {
return;
}
if ( ! apply_filters( 'pre_get_rocket_option_minify_google_fonts', true ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
return;
}
if ( $this->options->get( 'minify_google_fonts', 0 ) ) {
return;
}
$data = [
'beacon' => $this->beacon->get_suggest( 'google_fonts' ),
];
echo $this->generate( 'settings/enable-google-fonts', $data ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Callback method for the AJAX request to enable Google Fonts Optimization
*
* @since 3.7
*
* @return void
*/
public function enable_google_fonts() {
check_ajax_referer( 'rocket-ajax', 'nonce', true );
if ( ! current_user_can( 'rocket_manage_options' ) ) {
wp_send_json_error();
return;
}
$this->options->set( 'minify_google_fonts', 1 );
update_option( rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' ), $this->options->get_options() );
wp_send_json_success();
}
}
@@ -0,0 +1,59 @@
<?php
namespace WP_Rocket\Engine\Optimization\GoogleFonts\Admin;
use WP_Rocket\Event_Management\Subscriber_Interface;
class Subscriber implements Subscriber_Interface {
/**
* Google Fonts Settings instance
*
* @var Settings
*/
private $settings;
/**
* Instantiate the class
*
* @param Settings $settings Google Fonts Settings instance.
*/
public function __construct( Settings $settings ) {
$this->settings = $settings;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.7
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_settings_tools_content' => 'display_google_fonts_enabler',
'wp_ajax_rocket_enable_google_fonts' => 'enable_google_fonts',
];
}
/**
* Displays the Google Fonts Optimization section in the tools tab
*
* @since 3.7
*
* @return void
*/
public function display_google_fonts_enabler() {
$this->settings->display_google_fonts_enabler();
}
/**
* Callback method for the AJAX request to enable Google Fonts Optimization
*
* @since 3.7
*
* @return void
*/
public function enable_google_fonts() {
$this->settings->enable_google_fonts();
}
}
@@ -0,0 +1,146 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Logger\Logger;
/**
* Combine Google Fonts
*
* @since 3.1
*/
class Combine extends AbstractGFOptimization {
use RegexTrait;
/**
* Found fonts
*
* @since 3.1
*
* @var string
*/
protected $fonts = '';
/**
* Found subsets
*
* @since 3.1
*
* @var string
*/
protected $subsets = '';
/**
* Combines multiple Google Fonts links into one
*
* @since 3.1
*
* @param string $html HTML content.
*
* @return string
*/
public function optimize( $html ): string {
Logger::info( 'GOOGLE FONTS COMBINE PROCESS STARTED.', [ 'GF combine process' ] );
$html_nocomments = $this->hide_comments( $html );
$fonts = $this->find( '<link(?:\s+(?:(?!href\s*=\s*)[^>])+)?(?:\s+href\s*=\s*([\'"])(?<url>(?:https?:)?\/\/fonts\.googleapis\.com\/css[^\d](?:(?!\1).)+)\1)(?:\s+[^>]*)?>', $html_nocomments );
if ( ! $fonts ) {
Logger::debug( 'No Google Fonts found.', [ 'GF combine process' ] );
$this->has_google_fonts = false;
return $html;
}
$this->has_google_fonts = true;
$num_fonts = count( $fonts );
Logger::debug(
"Found {$num_fonts} Google Fonts.",
[
'GF combine process',
'tags' => $fonts,
]
);
$this->parse( $fonts );
if ( empty( $this->fonts ) ) {
Logger::debug( 'No Google Fonts left to combine.', [ 'GF combine process' ] );
return $html;
}
$html = preg_replace( '@<\/title>@i', '$0' . $this->get_optimized_markup( $this->get_combined_url() ), $html, 1 );
foreach ( $fonts as $font ) {
$html = str_replace( $font[0], '', $html );
}
Logger::info(
'Google Fonts successfully combined.',
[
'GF combine process',
'url' => $this->fonts . $this->subsets,
]
);
return $html;
}
/**
* Parses found matches to extract fonts and subsets.
*
* @since 3.1
*
* @param array $matches Found matches for the pattern.
*
* @return void
*/
private function parse( array $matches ) {
$fonts_array = [];
$subsets_array = [];
foreach ( $matches as $match ) {
$url = html_entity_decode( $match[2] );
$query = wp_parse_url( $url, PHP_URL_QUERY );
if ( empty( $query ) ) {
return;
}
$font = wp_parse_args( $query );
if ( isset( $font['family'] ) ) {
$font_family = $font['family'];
$font_family = rtrim( $font_family, '%7C' );
$font_family = rtrim( $font_family, '|' );
// Add font to the collection.
$fonts_array[] = rawurlencode( htmlentities( $font_family ) );
}
// Add subset to collection.
if ( isset( $font['subset'] ) ) {
$subsets_array[] = rawurlencode( htmlentities( $font['subset'] ) );
}
}
// Concatenate fonts tag.
$this->subsets = ! empty( $subsets_array ) ? '&subset=' . implode( ',', array_filter( array_unique( $subsets_array ) ) ) : '';
$this->fonts = ! empty( $fonts_array ) ? implode( '%7C', array_filter( array_unique( $fonts_array ) ) ) : '';
}
/**
* Returns the combined Google fonts URL
*
* @since 3.9.1
*
* @return string
*/
private function get_combined_url(): string {
$display = $this->get_font_display_value();
return esc_url( "https://fonts.googleapis.com/css?family={$this->fonts}{$this->subsets}&display={$display}" );
}
}
@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Logger\Logger;
/**
* Combine v2 Google Fonts
*
* @since 3.8
*/
class CombineV2 extends AbstractGFOptimization {
use RegexTrait;
/**
* Combines multiple Google Fonts (API v2) links into one
*
* @since 3.8
*
* @param string $html HTML content.
*
* @return string
*/
public function optimize( $html ): string {
Logger::info( 'GOOGLE FONTS COMBINE-V2 PROCESS STARTED.', [ 'GF combine process' ] );
$processed_tags = [];
$html_nocomments = $this->hide_comments( $html );
$font_tags = $this->find( '<link(?:\s+(?:(?!href\s*=\s*)[^>])+)?(?:\s+href\s*=\s*([\'"])(?<url>(?:https?:)?\/\/fonts\.googleapis\.com\/css2(?:(?!\1).)+)\1)(?:\s+[^>]*)?>', $html_nocomments );
if ( ! $font_tags ) {
Logger::debug( 'No v2 Google Fonts found.', [ 'GF combine process' ] );
$this->has_google_fonts = false;
return $html;
}
$this->has_google_fonts = true;
$num_tags = count( $font_tags );
Logger::debug(
"Found {$num_tags} v2 Google Fonts.",
[
'GF combine process',
'tags' => $font_tags,
]
);
$families = [];
foreach ( $font_tags as $tag ) {
$parsed_families = $this->parse( $tag );
if ( ! empty( $parsed_families ) ) {
$processed_tags[] = $tag;
$families = array_merge( $families, $parsed_families );
}
}
if ( empty( $families ) ) {
Logger::debug( 'No v2 Google Fonts left to combine.', [ 'GF combine process' ] );
return $html;
}
$families = array_unique( $families );
$combined_tag = $this->get_optimized_markup( $this->get_combined_url( $families ) );
$html = preg_replace( '@<\/title>@i', '$0' . $combined_tag, $html, 1 );
foreach ( $processed_tags as $font ) {
$html = str_replace( $font[0], '', $html );
}
Logger::info(
'V2 Google Fonts successfully combined.',
[
'GF combine process',
'url' => $combined_tag,
]
);
return $html;
}
/**
* Parses found matches to extract fonts and subsets.
*
* @since 3.8
*
* @param array $tag A Google Font v2 url.
*
* @return array
*/
private function parse( array $tag ): array {
if ( false !== strpos( $tag['url'], 'text=' ) ) {
Logger::debug( 'GOOGLEFONTS V2 COMBINE: ' . $tag['url'] . ' SKIPPED TO PRESERVE "text" ATTRIBUTE.' );
return [];
}
$url_pattern = '#(family=[A-Za-z0-9;:,=%&\+\@\.]+)$#';
$display_pattern = '#&display=(?:swap|auto|block|fallback|optional)#';
$decoded_url = html_entity_decode( $tag['url'] );
$query = wp_parse_url( $decoded_url, PHP_URL_QUERY );
if ( empty( $query ) ) {
return [];
}
if ( ! preg_match_all( $url_pattern, $query, $matches, PREG_PATTERN_ORDER ) ) {
return [];
}
$families = [];
foreach ( $matches[1] as $family ) {
$families[] = preg_replace( $display_pattern, '', $family );
}
return $families;
}
/**
* Returns the combined Google fonts URL
*
* @since 3.9.1
*
* @param array $families Array with all Google V2 families.
*
* @return string
*/
private function get_combined_url( array $families ): string {
$display = $this->get_font_display_value();
return esc_url( "https://fonts.googleapis.com/css2{$this->get_concatenated_families( $families )}&display={$display}" );
}
/**
* Get a string of the concatenated font family queries.
*
* @since 3.8
*
* @param array $families Array with all Google V2 families.
*
* @return string
*/
private function get_concatenated_families( array $families ): string {
$families_string = '?';
foreach ( $families as $family ) {
$families_string .= $family . '&';
}
return rtrim( $families_string, '&?' );
}
}
@@ -0,0 +1,129 @@
<?php
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Combine Google Fonts subscriber
*
* @since 3.1
*/
class Subscriber implements Subscriber_Interface {
/**
* Plugin options.
*
* @var Options_Data
*/
private $options;
/**
* Combine instance.
*
* @var AbstractGFOptimization
*/
private $combine;
/**
* CombineV2 instance.
*
* @var AbstractGFOptimization
*/
private $combine_v2;
/**
* Instantiate the subscriber.
*
* @param AbstractGFOptimization $combine Combine instance.
* @param AbstractGFOptimization $combine_v2 Combine V2 instance.
* @param Options_Data $options Options_Data instance.
*/
public function __construct( AbstractGFOptimization $combine, AbstractGFOptimization $combine_v2, Options_Data $options ) {
$this->combine = $combine;
$this->combine_v2 = $combine_v2;
$this->options = $options;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.1
*
* @return array
*/
public static function get_subscribed_events() {
return [
'wp_resource_hints' => [ 'preconnect', 10, 2 ],
'rocket_buffer' => [ 'process', 1001 ],
];
}
/**
* Adds google fonts URL to preconnect
*
* @since 3.5.3
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed for, e.g. 'preconnect' or 'prerender'.
* @return array
*/
public function preconnect( array $urls, $relation_type ) {
if ( ! $this->is_allowed() ) {
return $urls;
}
if ( 'preconnect' !== $relation_type ) {
return $urls;
}
$urls[] = [
'href' => 'https://fonts.gstatic.com',
1 => 'crossorigin',
];
return $urls;
}
/**
* Processes the HTML to combine found Google fonts.
* Handles both Google Fonts API v2 and v1.
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function process( $html ) {
if ( ! $this->is_allowed() ) {
return $html;
}
// Combine Google Font API V2.
$html = $this->combine_v2->optimize( $html );
// Combine Google Font API V1.
$html = $this->combine->optimize( $html );
if ( ! $this->combine->has_google_fonts() && ! $this->combine_v2->has_google_fonts() ) {
$html = preg_replace( '/<link\s+(?:[^>]+[\s"\'])?href\s*=\s*[\'"]https:\/\/fonts\.gstatic\.com[\'"](?:[^>]+[\s"\'])?\s?\/?>/', '', $html );
}
return $html;
}
/**
* Checks if files can combine found Google fonts.
*
* @since 3.1
*/
protected function is_allowed() {
if ( rocket_bypass() ) {
return false;
}
if ( ! $this->options->get( 'minify_google_fonts', 0 ) ) {
return false;
}
return ! is_user_logged_in() || (bool) $this->options->get( 'cache_logged_user', 0 );
}
}
@@ -0,0 +1,140 @@
<?php
namespace WP_Rocket\Engine\Optimization;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Handles IE conditionals comments in the HTML to prevent their content from being processed during optimization.
*
* @since 3.6 Changes template tag to be an HTML comment.
* @since 3.1
*/
class IEConditionalSubscriber implements Subscriber_Interface {
/**
* Stores IE conditionals.
*
* @since 3.1
*
* @var array
*/
private $conditionals = [];
/**
* HTML IE conditional pattern.
*
* @since 3.6.2
*
* @var string
*/
const IE_PATTERN = '/<!--\[if[^\]]*?\]>.*?<!\[endif\]-->/is';
/**
* HTML IE conditional template tag.
*
* @since 3.6.2
*
* @var string
*/
const WP_ROCKET_CONDITIONAL = '<!--{{WP_ROCKET_CONDITIONAL}}-->';
/**
* Return an array of events that this subscriber listens to.
*
* @since 3.1
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_buffer' => [
[ 'extract_ie_conditionals', 1 ],
[ 'inject_ie_conditionals', 34 ],
],
];
}
/**
* Extracts IE conditionals tags and replace them with placeholders.
*
* @since 3.1
*
* @param string $html HTML content.
*
* @return string
*/
public function extract_ie_conditionals( $html ) {
preg_match_all( self::IE_PATTERN, $html, $conditionals_match );
if ( ! $conditionals_match ) {
return $html;
}
foreach ( $conditionals_match[0] as $conditional ) {
$this->conditionals[] = $conditional;
}
return preg_replace( self::IE_PATTERN, self::WP_ROCKET_CONDITIONAL, $html );
}
/**
* Replaces WP Rocket placeholders with IE conditional tags.
*
* @since 3.1
*
* @param string $html HTML content.
*
* @return string
*/
public function inject_ie_conditionals( $html ) {
if ( ! $this->has_conditional_tag( $html ) ) {
return $html;
}
foreach ( $this->conditionals as $conditional ) {
// Prevent scripts containing things like "\\s" to be striped of a backslash when put back in content.
if ( preg_match( '@^(?<opening><!--\[if[^\]]*?\]>\s*?(?:<!-->)?\s*<script(?:\s[^>]*?>))\s*(?<content>.*?)\s*(?<closing></script>\s*(?:<!--)?\s*?<!\[endif\]-->)$@is', $conditional, $matches ) ) {
$conditional = $matches['opening'] . preg_replace( '#(?<!\\\\)(\\$|\\\\)#', '\\\\$1', $matches['content'] ) . $matches['closing'];
}
$html = $this->replace_conditional_tag( $html, $conditional );
}
return $html;
}
/**
* Checks if the template tag for the IE conditional exists in the given HTML string.
*
* @since 3.6.2
*
* @param string $html HTML content.
*
* @return bool true if at least one exists; else false.
*/
private function has_conditional_tag( $html ) {
return ( false !== strpos( $html, self::WP_ROCKET_CONDITIONAL ) );
}
/**
* Replaces the template tag with the original IE conditional HTML.
*
* @since 3.6.2
*
* @param string $html HTML content.
* @param string $original Original IE conditional HTML.
*
* @return string
*/
private function replace_conditional_tag( $html, $original ) {
$template_tag_position = strpos( $html, self::WP_ROCKET_CONDITIONAL );
return substr_replace(
$html,
$original,
$template_tag_position,
strlen( self::WP_ROCKET_CONDITIONAL )
);
}
}
@@ -0,0 +1,133 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify;
use WP_Filesystem_Direct;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Parent class for minify subscribers.
*/
abstract class AbstractMinifySubscriber implements Subscriber_Interface {
/**
* Plugin options.
*
* @var Options_Data
*/
protected $options;
/**
* Processor instance.
*
* @var ProcessorInterface
*/
protected $processor;
/**
* Filesystem instance
*
* @var WP_Filesystem_Direct
*/
protected $filesystem;
/**
* Creates an instance of inheriting class.
*
* @since 3.1
*
* @param Options_Data $options Plugin options.
* @param WP_Filesystem_Direct $filesystem Filesystem instance.
*/
public function __construct( Options_Data $options, $filesystem ) {
$this->options = $options;
$this->filesystem = $filesystem;
}
/**
* Sets the type of processor to use
*
* @since 3.1
*
* @param ProcessorInterface $processor Processor instance.
* @return void
*/
protected function set_processor_type( ProcessorInterface $processor ) {
$this->processor = $processor;
}
/**
* Processes the HTML to perform an optimization and return the new content
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
abstract public function process( $html );
/**
* Checks if files can be optimized
*
* @since 3.1
*/
abstract protected function is_allowed();
/**
* Fix issue with SSL and minification
*
* @since 2.3
*
* @param string $url An url to filter to set the scheme to https if needed.
* @return string
*/
public function fix_ssl_minify( $url ) {
if ( ! is_ssl() ) {
return $url;
}
if ( 0 === strpos( $url, 'https://' ) ) {
return $url;
}
// This filter is documented in inc/Engine/Admin/Settings/Settings.php.
if ( in_array( wp_parse_url( $url, PHP_URL_HOST ), apply_filters( 'rocket_cdn_hosts', [], ( $this->get_zones() ) ), true ) ) {
return $url;
}
return str_replace( 'http://', 'https://', $url );
}
/**
* Compatibility with multilingual plugins & multidomain configuration
*
* @since 2.6.13 Regression Fix: Apply CDN on minified CSS and JS files by checking the CNAME host
* @since 2.6.8
*
* @param string $url Minified file URL.
* @return string Updated minified file URL
*/
public function i18n_multidomain_url( $url ) {
if ( ! rocket_has_i18n() ) {
return $url;
}
$url_host = wp_parse_url( $url, PHP_URL_HOST );
if ( isset( $_SERVER['HTTP_HOST'] ) && $url_host === $_SERVER['HTTP_HOST'] ) {
return $url;
}
if ( ! in_array( $_SERVER['HTTP_HOST'], get_rocket_i18n_host(), true ) ) {
return $url;
}
// This filter is documented in inc/Engine/Admin/Settings/Settings.php.
$cdn_hosts = apply_filters( 'rocket_cdn_hosts', [], ( $this->get_zones() ) );
if ( in_array( $url_host, $cdn_hosts, true ) ) {
return $url;
}
return str_replace( $url_host, sanitize_text_field( $_SERVER['HTTP_HOST'] ), $url ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\Minify;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
class AdminSubscriber implements Subscriber_Interface {
/**
* WP Rocket Options
*
* @var Options_Data
*/
private $options;
/**
* Instantiate the class
*
* @param Options_Data $options WP Rocket Options Instance.
*/
public function __construct( Options_Data $options ) {
$this->options = $options;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'switch_theme' => 'clean_minify_all',
'rocket_meta_boxes_fields' => [ 'add_meta_box', 4 ],
];
}
/**
* Delete all minified cache files
*
* @return void
*/
public function clean_minify_all() {
// Bail out if minify_js or minify_css is not enabled.
if (
! (bool) $this->options->get( 'minify_js', 0 )
&&
! (bool) $this->options->get( 'minify_css', 0 )
) {
return;
}
// Delete all minify cache files.
rocket_clean_minify();
}
/**
* 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['minify_js'] = __( 'Minify/combine JavaScript', 'rocket' );
return $fields;
}
}
@@ -0,0 +1,154 @@
<?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;
}
$file = wp_parse_url( $tag['url'] );
$file_path = isset( $file['path'] ) ? $file['path'] : '';
$host = isset( $file['host'] ) ? $file['host'] : '';
// 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;
}
if ( preg_match( '#^(' . $this->excluded_files . ')$#', $host ) ) {
return true;
}
if ( preg_match( '#^(' . $this->excluded_files . ')$#', $host . $file_path ) ) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,154 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\Minify\CSS;
use WP_Rocket\Event_Management\Subscriber_Interface;
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 ],
'wp_rocket_upgrade' => [ 'on_update', 16, 2 ],
'rocket_meta_boxes_fields' => [ 'add_meta_box', 1 ],
];
}
/**
* 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.
*
* @return void
*/
public function clean_minify( $old, $new ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.newFound
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 ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.newFound
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 ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.newFound
$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 ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.newFound
return (
array_key_exists( $setting, $old )
&&
array_key_exists( $setting, $new )
&&
// phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual
$old[ $setting ] != $new[ $setting ]
);
}
/**
* Clean cache on update.
*
* @param string $new_version new version from the plugin.
* @param string $old_version old version from the plugin.
*
* @return void
*/
public function on_update( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.15', '>=' ) ) {
return;
}
rocket_clean_domain();
}
/**
* 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['minify_css'] = __( 'Minify CSS', 'rocket' );
return $fields;
}
}
@@ -0,0 +1,341 @@
<?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 );
}
$filename = ltrim( rocket_realpath( $parsed_url['path'] ), '/' );
$minified_file = rawurldecode( $this->minify_base_path . $filename );
if ( rocket_direct_filesystem()->exists( $minified_file ) ) {
Logger::debug(
'Minified CSS file already exists.',
[
'css minification process',
'path' => $minified_file,
]
);
return $this->get_full_minified_url( $minified_file, $this->get_minify_url( $filename, $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(
'Couldn’t 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 $this->get_full_minified_url( $minified_file, $this->get_minify_url( $filename, $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 ''; // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
return $minified_content; // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
/**
* 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 );
}
}
@@ -0,0 +1,83 @@
<?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->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' ];
}
}
@@ -0,0 +1,167 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\JS;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Optimization\AbstractOptimization;
use WP_Rocket\Engine\Optimization\AssetsLocalCache;
/**
* Abstract class for JS optimization
*
* @since 3.1
*/
abstract class AbstractJSOptimization extends AbstractOptimization {
const FILE_TYPE = 'js';
/**
* Assets local cache instance
*
* @since 3.1
*
* @var AssetsLocalCache
*/
protected $local_cache;
/**
* Creates an instance of inheriting class.
*
* @since 3.1
*
* @param Options_Data $options Options instance.
* @param AssetsLocalCache $local_cache Assets local cache 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_js_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 A list of files to exclude, ready to be used in a regex pattern.
*/
protected function get_excluded_files() {
$excluded_files = $this->options->get( 'exclude_js', [] );
/**
* Filter JS files to exclude from minification/concatenation.
*
* @since 2.6
*
* @param array $js_files List of excluded JS files.
*/
$excluded_files = (array) apply_filters( 'rocket_exclude_js', $excluded_files );
if ( empty( $excluded_files ) ) {
return '';
}
foreach ( $excluded_files as $i => $excluded_file ) {
// Escape characters for future use in regex pattern.
$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 ];
}
/**
* Determines if it is a file excluded from minification.
*
* @since 2.11
*
* @param array $tag Tag corresponding to a JS 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;
}
$file_path = wp_parse_url( $tag['url'], PHP_URL_PATH );
// File extension is not js.
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;
}
/**
* 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 JS 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_js_url', $minify_url, $original_url );
}
/**
* Patterns in URL excluded from being combined
*
* @since 3.1
*
* @return array
*/
protected function get_excluded_external_file_path() {
$excluded_external = $this->options->get( 'exclude_js', [] );
/**
* Filters JS externals files to exclude from the combine process
*
* @since 2.2
*
* @param array $pattern Patterns to match.
*/
return apply_filters( 'rocket_minify_excluded_external_js', $excluded_external );
}
}
@@ -0,0 +1,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; // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
$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; // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
$minify_filepath = $this->write_file( $minified_content, $minified_file );
if ( ! $minify_filepath ) {
return false; // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
}
return $this->get_minify_url( $filename ); // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
/**
* 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;
}
}
@@ -0,0 +1,352 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\JS;
use WP_Rocket\Dependencies\Minify as Minifier;
use WP_Rocket\Engine\Optimization\Minify\ProcessorInterface;
use WP_Rocket\Logger\Logger;
/**
* Minify JS files
*
* @since 3.1
*/
class Minify extends AbstractJSOptimization implements ProcessorInterface {
/**
* Minifies JS files
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function optimize( $html ) {
Logger::info( 'JS MINIFICATION PROCESS STARTED.', [ 'js minification process' ] );
$scripts = $this->get_scripts( $html );
if ( empty( $scripts ) ) {
return $html;
}
foreach ( $scripts as $script ) {
global $wp_scripts;
$is_external_url = $this->is_external_file( $script['url'] );
if (
! $is_external_url
&&
preg_match( '/[-.]min\.js/iU', $script['url'] )
) {
Logger::debug(
'Script is already minified.',
[
'js minification process',
'tag' => $script[0],
]
);
continue;
}
if (
$is_external_url
&&
$this->is_excluded_external( $script['url'] )
) {
continue;
}
if ( $this->is_minify_excluded_file( $script ) ) {
Logger::debug(
'Script is excluded.',
[
'js minification process',
'tag' => $script[0],
]
);
continue;
}
// Don't minify jQuery included in WP core since it's already minified but without .min in the filename.
if ( ! empty( $wp_scripts->registered['jquery-core']->src ) && false !== strpos( $script['url'], $wp_scripts->registered['jquery-core']->src ) ) {
Logger::debug(
'jQuery script is already minified.',
[
'js minification process',
'tag' => $script[0],
]
);
continue;
}
$integrity_validated = $this->local_cache->validate_integrity( $script );
if ( false === $integrity_validated ) {
Logger::debug(
'Script integrity attribute not valid.',
[
'js minification process',
'tag' => $script[0],
]
);
continue;
}
$script['final'] = $integrity_validated;
$minify_url = $this->replace_url( strtok( $script['url'], '?' ) );
if ( ! $minify_url ) {
Logger::error(
'Script minification failed.',
[
'js minification process',
'tag' => $script[0],
]
);
continue;
}
$html = $this->replace_script( $script, $minify_url, $html );
}
return $html;
}
/**
* Get all script tags from HTML.
*
* @param string $html HTML content.
* @return array Array with script tags, empty array if no script tags found.
*/
private function get_scripts( $html ) {
$html_nocomments = $this->hide_comments( $html );
$scripts = $this->find( '<script\s+([^>]+[\s\'"])?src\s*=\s*[\'"]\s*?(?<url>[^\'"]+\.js(?:\?[^\'"]*)?)\s*?[\'"]([^>]+)?\/?>', $html_nocomments );
if ( ! $scripts ) {
Logger::debug( 'No `<script>` tags found.', [ 'js minification process' ] );
return [];
}
Logger::debug(
'Found ' . count( $scripts ) . ' <link> tags.',
[
'js minification process',
'tags' => $scripts,
]
);
return $scripts;
}
/**
* Checks if the provided external URL is excluded from minify
*
* @since 3.7
*
* @param string $url External URL to check.
* @return boolean
*/
private function is_excluded_external( $url ) {
$excluded_externals = $this->get_excluded_external_file_path();
$excluded_externals[] = 'google-analytics.com/analytics.js';
foreach ( $excluded_externals as $excluded ) {
if ( false !== strpos( $url, $excluded ) ) {
Logger::debug(
'Script is external.',
[
'js combine process',
'url' => $url,
]
);
return true;
}
}
return false;
}
/**
* 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
*/
protected 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 );
}
$filename = ltrim( rocket_realpath( $parsed_url['path'] ), '/' );
$minified_file = rawurldecode( $this->minify_base_path . $filename );
if ( rocket_direct_filesystem()->exists( $minified_file ) ) {
Logger::debug(
'Minified JS file already exists.',
[
'js minification process',
'path' => $minified_file,
]
);
return $this->get_full_minified_url( $minified_file, $this->get_minify_url( $filename, $url ) );
}
$is_external_url = $this->is_external_file( $url );
$file_path = $is_external_url ? $this->local_cache->get_filepath( rocket_add_url_protocol( $url ) ) : $this->get_file_path( $url );
if ( ! $file_path ) {
Logger::error(
'Couldn’t get the file path from the URL.',
[
'js minification process',
'url' => $url,
]
);
return false;
}
$file_content = $is_external_url ? $this->local_cache->get_content( rocket_add_url_protocol( $url ) ) : $this->get_file_content( $file_path );
if ( empty( $file_content ) ) {
Logger::error(
'No file content.',
[
'js minification process',
'path' => $file_path,
]
);
return false;
}
$minified_content = $this->minify( $file_content );
if ( empty( $minified_content ) ) {
Logger::error(
'No minified content.',
[
'js minification process',
'path' => $minified_file,
]
);
return false;
}
$save_minify_file = $this->save_minify_file( $minified_file, $minified_content );
if ( ! $save_minify_file ) {
return false;
}
return $this->get_full_minified_url( $minified_file, $this->get_minify_url( $filename, $url ) );
}
/**
* Replace old script tag with the minified tag.
*
* @param array $script Script matched data.
* @param string $minify_url Minified URL.
* @param string $html HTML content.
*
* @return string
*/
private function replace_script( $script, $minify_url, $html ) {
$replace_script = str_replace( $script['url'], $minify_url, $script['final'] );
$replace_script = str_replace( '<script', '<script data-minify="1"', $replace_script );
$html = str_replace( $script[0], $replace_script, $html );
Logger::info(
'Script minification succeeded.',
[
'js minification process',
'url' => $minify_url,
]
);
return $html;
}
/**
* Save minified JS 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 JS file could not be created.',
[
'js minification process',
'path' => $minified_file,
]
);
return false;
}
Logger::debug(
'Minified JS file successfully created.',
[
'js minification process',
'path' => $minified_file,
]
);
return true;
}
/**
* Minifies the content
*
* @since 2.11
*
* @param string $file_content Content to minify.
* @return string
*/
protected function minify( $file_content ) {
$minifier = $this->get_minifier( $file_content );
$minified_content = $minifier->minify();
if ( empty( $minified_content ) ) {
return ''; // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
return $minified_content; // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
}
/**
* Returns a new minifier instance
*
* @since 3.1
*
* @param string $file_content Content to minify.
* @return Minifier\JS
*/
protected function get_minifier( $file_content ) {
return new Minifier\JS( $file_content );
}
}
@@ -0,0 +1,88 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify\JS;
use WP_Rocket\Dependencies\Minify\JS as MinifyJS;
use WP_Rocket\Engine\Optimization\AssetsLocalCache;
use WP_Rocket\Engine\Optimization\DeferJS\DeferJS;
use WP_Rocket\Engine\Optimization\Minify\AbstractMinifySubscriber;
/**
* Minify/Combine JS 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_js_url' => [
[ 'fix_ssl_minify' ],
[ 'i18n_multidomain_url' ],
],
'rocket_buffer' => [ 'process', 22 ],
];
return $events;
}
/**
* Processes the HTML to Minify/Combine JS.
*
* @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 );
$container = apply_filters( 'rocket_container', null );
if ( $this->options->get( 'minify_js' ) && $this->options->get( 'minify_concatenate_js' ) ) {
$this->set_processor_type( new Combine( $this->options, new MinifyJS(), $assets_local_cache, $container->get( 'defer_js' ) ) );
} elseif ( $this->options->get( 'minify_js' ) && ! $this->options->get( 'minify_concatenate_js' ) ) {
$this->set_processor_type( new Minify( $this->options, $assets_local_cache ) );
}
return $this->processor->optimize( $html );
}
/**
* Checks if is allowed to Minify/Combine JS.
*
* @since 3.1
*
* @return bool
*/
protected function is_allowed() {
if ( rocket_get_constant( 'DONOTROCKETOPTIMIZE' ) ) {
return false;
}
if ( ! (bool) $this->options->get( 'minify_js', 0 ) ) {
return false;
}
return ! is_rocket_post_excluded_option( 'minify_js' );
}
/**
* Returns an array of CDN zones for JS files.
*
* @since 3.1
*
* @return array
*/
public function get_zones() {
return [ 'all', 'css_and_js', 'js' ];
}
}
@@ -0,0 +1,13 @@
<?php
namespace WP_Rocket\Engine\Optimization\Minify;
interface ProcessorInterface {
/**
* Performs the optimization process on the given HTML
*
* @param string $html HTML content.
* @return string
*/
public function optimize( $html );
}
@@ -0,0 +1,139 @@
<?php
declare( strict_types=1 );
namespace WP_Rocket\Engine\Optimization\RUCSS;
use WP_Error;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Logger\Logger;
abstract class AbstractAPIClient {
/**
* API URL.
*/
const API_URL = 'https://saas.wp-rocket.me/';
/**
* Part of request Url after the main API_URL.
*
* @var string
*/
protected $request_path;
/**
* Response Code.
*
* @var int
*/
protected $response_code = 200;
/**
* Error message.
*
* @var string
*/
protected $error_message = '';
/**
* Response Body.
*
* @var string
*/
protected $response_body;
/**
* Plugin options instance.
*
* @var Options_Data
*/
protected $options;
/**
* Instantiate the class.
*
* @param Options_Data $options Options instance.
*/
public function __construct( Options_Data $options ) {
$this->options = $options;
}
/**
* Handle the request.
*
* @param array $args Passed arguments.
* @param string $type GET or POST.
*
* @return bool
*/
private function handle_request( array $args, string $type = 'post' ) {
$api_url = rocket_get_constant( 'WP_ROCKET_SAAS_API_URL', false )
? rocket_get_constant( 'WP_ROCKET_SAAS_API_URL', false )
: self::API_URL;
if ( empty( $args['body'] ) ) {
$args['body'] = [];
}
$args['body']['credentials'] = [
'wpr_email' => $this->options->get( 'consumer_email', '' ),
'wpr_key' => $this->options->get( 'consumer_key', '' ),
];
$args['method'] = strtoupper( $type );
$response = wp_remote_request(
$api_url . $this->request_path,
$args
);
return $this->check_response( $response );
}
/**
* Handle remote POST.
*
* @param array $args Array with options sent to Saas API.
*
* @return bool WP Remote request status.
*/
protected function handle_post( array $args ): bool {
return $this->handle_request( $args );
}
/**
* Handle remote GET.
*
* @param array $args Array with options sent to Saas API.
*
* @return bool WP Remote request status.
*/
protected function handle_get( array $args ): bool {
return $this->handle_request( $args, 'get' );
}
/**
* Handle SaaS request error.
*
* @param array|WP_Error $response WP Remote request.
*
* @return bool
*/
private function check_response( $response ): bool {
$this->response_code = is_array( $response )
? wp_remote_retrieve_response_code( $response )
: $response->get_error_code();
if ( 200 !== $this->response_code ) {
$previous_errors = (int) get_transient( 'wp_rocket_rucss_errors_count' );
set_transient( 'wp_rocket_rucss_errors_count', $previous_errors + 1, 5 * MINUTE_IN_SECONDS );
$this->error_message = is_array( $response )
? wp_remote_retrieve_response_message( $response )
: $response->get_error_message();
return false;
}
delete_transient( 'wp_rocket_rucss_errors_count' );
$this->response_body = wp_remote_retrieve_body( $response );
return true;
}
}
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Tables\UsedCSS;
class Database {
/**
* Instance of RUCSS used_css table.
*
* @var UsedCSS
*/
private $rucss_usedcss_table;
/**
* Creates an instance of the class.
*
* @param UsedCSS $rucss_usedcss_table RUCSS UsedCSS Database Table.
*/
public function __construct( UsedCSS $rucss_usedcss_table ) {
$this->rucss_usedcss_table = $rucss_usedcss_table;
}
/**
* Drop RUCSS Database Tables.
*
* @return void
*/
public function drop_rucss_database_tables() {
// If the table exist, then drop the table.
if ( $this->rucss_usedcss_table->exists() ) {
$this->rucss_usedcss_table->uninstall();
}
}
/**
* Truncate RUCSS used_css DB table.
*
* @return bool
*/
public function truncate_used_css_table(): bool {
if ( ! $this->rucss_usedcss_table->exists() ) {
return false;
}
return $this->rucss_usedcss_table->truncate();
}
/**
* Delete old used css based on last accessed date.
*
* @return void
*/
public function delete_old_used_css() {
if ( ! $this->rucss_usedcss_table->exists() ) {
return;
}
$this->rucss_usedcss_table->delete_old_used_css();
}
/**
* Get old used css based on last accessed date.
*
* @return array
*/
public function get_old_used_css(): array {
if ( ! $this->rucss_usedcss_table->exists() ) {
return [];
}
return $this->rucss_usedcss_table->get_old_used_css();
}
/**
* Remove all completed rows.
*
* @return bool|int
*/
public function remove_all_completed_rows() {
if ( ! $this->rucss_usedcss_table->exists() ) {
return false;
}
return $this->rucss_usedcss_table->remove_all_completed_rows();
}
/**
* Remove the resources table & version stored in options table
*
* @since 3.12
*
* @return bool
*/
public function drop_resources_table(): bool {
global $wpdb;
$result = $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}wpr_rucss_resources" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
if ( false === $result ) {
return false;
}
return delete_option( 'wpr_rucss_resources_version' );
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Engine\Admin\Settings\Settings as AdminSettings;
use WP_Rocket\Event_Management\Subscriber_Interface;
class OptionSubscriber implements Subscriber_Interface {
/**
* Settings instance
*
* @var Settings
*/
private $settings;
/**
* Instantiate the class
*
* @param Settings $settings Settings instance.
*/
public function __construct( Settings $settings ) {
$this->settings = $settings;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_first_install_options' => 'add_options_first_time',
'rocket_input_sanitize' => [ 'sanitize_options', 14, 2 ],
'rocket_meta_boxes_fields' => [ 'add_meta_box', 2 ],
];
}
/**
* Add the RUCSS options to the WP Rocket options array.
*
* @since 3.9
*
* @param array $options WP Rocket options array.
*
* @return array
*/
public function add_options_first_time( $options ): array {
return $this->settings->add_options( $options );
}
/**
* Sanitizes RUCSS options values when the settings form is submitted
*
* @since 3.9
*
* @param array $input Array of values submitted from the form.
* @param AdminSettings $settings Settings class instance.
*
* @return array
*/
public function sanitize_options( $input, AdminSettings $settings ): array {
return $this->settings->sanitize_options( $input, $settings );
}
/**
* 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['remove_unused_css'] = __( 'Remove Unused CSS', 'rocket' );
return $fields;
}
}
@@ -0,0 +1,580 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Admin\Beacon\Beacon;
use WP_Rocket\Engine\Admin\Settings\Settings as AdminSettings;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Tables\UsedCSS;
class Settings {
/**
* Instance of options handler.
*
* @var Options_Data
*/
private $options;
/**
* Instance of Beacon class.
*
* @var Beacon
*/
private $beacon;
/**
* Used CSS table.
*
* @var UsedCSS
*/
private $used_css;
/**
* Creates an instance of the class.
*
* @param Options_Data $options WP Rocket Options instance.
* @param Beacon $beacon Beacon instance.
* @param UsedCSS $used_css Used CSS table.
*/
public function __construct( Options_Data $options, Beacon $beacon, UsedCSS $used_css ) {
$this->options = $options;
$this->beacon = $beacon;
$this->used_css = $used_css;
}
/**
* Add the RUCSS options to the WP Rocket options array
*
* @since 3.9
*
* @param array $options WP Rocket options array.
*
* @return array
*/
public function add_options( $options ): array {
$options = (array) $options;
$options['remove_unused_css'] = 0;
$options['remove_unused_css_safelist'] = [];
return $options;
}
/**
* Determines if Remove Unused CSS option is enabled.
*
* @since 3.9
*
* @return boolean
*/
public function is_enabled(): bool {
return (bool) $this->options->get( 'remove_unused_css', 0 );
}
/**
* Sanitizes RUCSS options values when the settings form is submitted
*
* @since 3.9
*
* @param array $input Array of values submitted from the form.
* @param AdminSettings $settings Settings class instance.
*
* @return array
*/
public function sanitize_options( array $input, AdminSettings $settings ): array {
$input['remove_unused_css'] = $settings->sanitize_checkbox( $input, 'remove_unused_css' );
$input['remove_unused_css_safelist'] = ! empty( $input['remove_unused_css_safelist'] ) ? rocket_sanitize_textarea_field( 'remove_unused_css_safelist', $input['remove_unused_css_safelist'] ) : [];
return $input;
}
/**
* Add Clean used CSS link to WP Rocket admin bar item
*
* @since 3.9
*
* @param \WP_Admin_Bar $wp_admin_bar WP_Admin_Bar instance, passed by reference.
*
* @return void
*/
public function add_clean_used_css_menu_item( $wp_admin_bar ) {
if ( 'local' === wp_get_environment_type() ) {
return;
}
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
return;
}
if ( ! is_admin() ) {
return;
}
if ( ! $this->is_enabled() ) {
return;
}
$referer = '';
$action = 'rocket_clear_usedcss';
if ( ! empty( $_SERVER['REQUEST_URI'] ) ) {
$referer_url = filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_URL );
$referer = '&_wp_http_referer=' . rawurlencode( remove_query_arg( 'fl_builder', $referer_url ) );
}
$wp_admin_bar->add_menu(
[
'parent' => 'wp-rocket',
'id' => 'clean-used-css',
'title' => __( 'Clear Used CSS', 'rocket' ),
'href' => wp_nonce_url( admin_url( "admin-post.php?action={$action}{$referer}" ), $action ),
]
);
}
/**
* Set optimize css delivery value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_value( $field_args ): array {
if ( 'optimize_css_delivery' !== $field_args['id'] ) {
return $field_args;
}
$async_css_value = (bool) $this->options->get( 'async_css', 0 );
$remove_unused_css_value = (bool) $this->options->get( 'remove_unused_css', 0 );
$field_args['value'] = ( $remove_unused_css_value || $async_css_value );
return $field_args;
}
/**
* Set optimize css delivery method value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_method_value( $field_args ): array {
if ( 'optimize_css_delivery_method' !== $field_args['id'] ) {
return $field_args;
}
$value = '';
if ( (bool) $this->options->get( 'async_css', 0 ) ) {
$value = 'async_css';
}
if ( (bool) $this->options->get( 'remove_unused_css', 0 ) ) {
$value = 'remove_unused_css';
}
$field_args['value'] = $value;
return $field_args;
}
/**
* Displays the RUCSS currently processing notice
*
* @since 3.11
*
* @return void
*/
public function display_processing_notice() {
if ( $this->has_saas_error_notice() ) {
return;
}
if ( ! $this->can_display_notice() ) {
return;
}
if ( ! $this->used_css->exists() ) {
return;
}
$transient = get_transient( 'rocket_rucss_processing' );
if ( false === $transient ) {
return;
}
$current_time = time();
if ( $transient < $current_time ) {
return;
}
$remaining = $transient - $current_time;
$message = sprintf(
// translators: %1$s = plugin name, %2$s = number of seconds.
__( '%1$s: Please wait %2$s seconds. The Remove Unused CSS service is processing your pages.', 'rocket' ),
'<strong>WP Rocket</strong>',
'<span id="rocket-rucss-timer">' . $remaining . '</span>'
);
rocket_notice_html(
[
'status' => 'info',
'message' => $message,
'id' => 'rocket-notice-rucss-processing',
]
);
}
/**
* Displays the RUCSS success notice
*
* @since 3.11
*
* @return void
*/
public function display_success_notice() {
if ( ! $this->can_display_notice() ) {
return;
}
if ( ! $this->used_css->exists() ) {
return;
}
if ( $this->has_saas_error_notice() ) {
return;
}
$boxes = get_user_meta( get_current_user_id(), 'rocket_boxes', true );
if ( in_array( 'rucss_success_notice', (array) $boxes, true ) ) {
return;
}
$transient = get_transient( 'rocket_rucss_processing' );
$class = '';
if ( false !== $transient ) {
$class = 'hidden';
}
$message = sprintf(
// translators: %1$s = plugin name, %2$s = number of URLs, %3$s = number of seconds.
__( '%1$s: The Used CSS of your homepage has been processed. WP Rocket will continue to generate Used CSS for up to %2$s URLs per %3$s second(s).', 'rocket' ),
'<strong>WP Rocket</strong>',
apply_filters( 'rocket_rucss_pending_jobs_cron_rows_count', 100 ),
apply_filters( 'rocket_rucss_pending_jobs_cron_interval', MINUTE_IN_SECONDS )
);
if ( ! $this->options->get( 'manual_preload', 0 ) ) {
$message .= ' ' . sprintf(
// translators: %1$s = opening link tag, %2$s = closing link tag.
__( 'We suggest enabling %1$sPreload%2$s for the fastest results.', 'rocket' ),
'<a href="#preload">',
'</a>'
);
}
$beacon = $this->beacon->get_suggest( 'async_opti' );
$message .= '<br>' . sprintf(
// translators: %1$s = opening link tag, %2$s = closing link tag.
__( 'To learn more about the process check our %1$sdocumentation%2$s.', 'rocket' ),
'<a href="' . esc_url( $beacon['url'] ) . '" data-beacon-article="' . esc_attr( $beacon['id'] ) . '" rel="noopener noreferrer" target="_blank">',
'</a>'
);
rocket_notice_html(
[
'message' => $message,
'dismissible' => $class,
'id' => 'rocket-notice-rucss-success',
'dismiss_button' => 'rucss_success_notice',
'dismiss_button_class' => 'button-primary',
]
);
}
/**
* Checks if we can display the RUCSS notices
*
* @param bool $check_enabled check if RUCSS is enabled.
*
* @since 3.11
*
* @return bool
*/
private function can_display_notice( $check_enabled = true ): bool {
$screen = get_current_screen();
if ( ! rocket_direct_filesystem()->is_writable( rocket_get_constant( 'WP_ROCKET_USED_CSS_PATH' ) ) ) {
return false;
}
if (
isset( $screen->id )
&&
'settings_page_wprocket' !== $screen->id
) {
return false;
}
if ( ! current_user_can( 'rocket_manage_options' ) ) {
return false;
}
if ( $check_enabled && ! $this->is_enabled() ) {
return false;
}
return true;
}
/**
* Adds the notice end time to WP Rocket localize script data
*
* @since 3.11
*
* @param array $data Localize script data.
*
* @return array
*/
public function add_localize_script_data( $data ): array {
if ( ! is_array( $data ) ) {
$data = (array) $data;
}
if ( ! $this->is_enabled() ) {
return $data;
}
$transient = get_transient( 'rocket_rucss_processing' );
if ( false === $transient ) {
return $data;
}
$data['notice_end_time'] = $transient;
return $data;
}
/**
* Disables combine CSS if RUCSS is enabled when updating to 3.11
*
* @since 3.11
*
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function set_option_on_update( $old_version ) {
if ( version_compare( $old_version, '3.11', '>=' ) ) {
return;
}
$options = get_option( 'wp_rocket_settings', [] );
if ( 'local' === wp_get_environment_type() ) {
$options['optimize_css_delivery'] = 0;
$options['remove_unused_css'] = 0;
$options['async_css'] = 0;
}
update_option( 'wp_rocket_settings', $options );
}
/**
* Updates safelist items for new SaaS compatibility
*
* @since 3.11.0.2
*
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function update_safelist_items( $old_version ) {
if ( version_compare( $old_version, '3.11.0.2', '>=' ) ) {
return;
}
$options = get_option( 'wp_rocket_settings', [] );
if ( empty( $options['remove_unused_css_safelist'] ) ) {
return;
}
foreach ( $options['remove_unused_css_safelist'] as $key => $value ) {
if ( str_contains( $value, '.css' ) ) {
continue;
}
if ( str_starts_with( $value, '(' ) ) {
continue;
}
$options['remove_unused_css_safelist'][ $key ] = '(.*)' . $value;
}
update_option( 'wp_rocket_settings', $options );
}
/**
* Display a notification on wrong license.
*
* @return void
*/
public function display_wrong_license_notice() {
if ( ! $this->can_display_notice( false ) ) {
return;
}
$main_message = __( "We couldn't generate the used CSS because you're using a nulled version of WP Rocket. You need an active license to use the Remove Unused CSS feature and further improve your website's performance.", 'rocket' );
$cta_message = sprintf(
// translators: %1$s = promo percentage.
__( 'Click here to get a WP Rocket single license at %1$s off!', 'rocket' ),
'10%%'
);
$message = sprintf(
// translators: %1$s = plugin name, %2$s = opening anchor tag, %3$s = closing anchor tag.
"%1\$s: <p>$main_message</p>%2\$s$cta_message%3\$s",
'<strong>WP Rocket</strong>',
'<a href="https://wp-rocket.me/?add-to-cart=191&coupon_code=iamnotapirate10" class="button button-primary" rel="noopener noreferrer" target="_blank">',
'</a>'
);
rocket_notice_html(
[
'status' => 'error',
'dismissible' => '',
'message' => $message,
'id' => 'rocket-notice-rucss-wrong-licence',
]
);
}
/**
* Display an error notice when the connection to the server fails
*
* @return void
*/
public function display_saas_error_notice() {
if ( ! $this->has_saas_error_notice() ) {
$boxes = get_user_meta( get_current_user_id(), 'rocket_boxes', true );
if ( in_array( 'rucss_saas_error_notice', (array) $boxes, true ) ) {
unset( $boxes['rucss_saas_error_notice'] );
update_user_meta( get_current_user_id(), 'rocket_boxes', $boxes );
}
return;
}
if ( ! $this->can_display_notice() ) {
return;
}
$boxes = get_user_meta( get_current_user_id(), 'rocket_boxes', true );
if ( in_array( 'rucss_error_notice', (array) $boxes, true ) ) {
return;
}
$firewall_beacon = $this->beacon->get_suggest( 'rucss_firewall_ips' );
$main_message = sprintf(
// translators: %1$s = <a> open tag, %2$s = </a> closing tag.
__( 'It seems a security plugin or the server\'s firewall prevents WP Rocket from accessing the Remove Unused CSS generator. IPs listed %1$shere in our documentation%2$s should be added to your allowlists:', 'rocket' ),
'<a href="' . esc_url( $firewall_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $firewall_beacon['id'] ) . '" rel="noopener noreferrer" target="_blank">',
'</a>'
);
$security_message = __( '- In the security plugin, if you are using one', 'rocket' );
$firewall_message = __( "- In the server's firewall. Your host can help you with this", 'rocket' );
$message = "<strong>WP Rocket</strong>: $main_message<ul><li>$security_message</li><li>$firewall_message</li></ul>";
rocket_notice_html(
[
'status' => 'error',
'message' => $message,
'dismissible' => '',
'id' => 'rocket-notice-rucss-error-http',
'dismiss_button' => 'rucss_error_notice',
'dismiss_button_class' => 'button-primary',
]
);
}
/**
* Is the error notice present.
*
* @return bool
*/
public function has_saas_error_notice() {
return (bool) get_transient( 'wp_rocket_rucss_errors_count' );
}
/**
* Display a notice on table missing.
*
* @return void
*/
public function display_no_table_notice() {
if ( ! $this->can_display_notice() ) {
return;
}
if ( $this->used_css->exists() ) {
return;
}
// translators: %1$s = plugin name, %2$s = table name, %3$s = <a> open tag, %4$s = </a> closing tag.
$main_message = esc_html__( '%1$s: Could not create the %2$s table in the database which is necessary for the Remove Unused CSS feature to work. Please reach out to %3$sour support%4$s.', 'rocket' );
$message = sprintf(
// translators: %1$s = plugin name, %2$s = table name, %3$s = <a> open tag, %4$s = </a> closing tag.
$main_message,
'<strong>WP Rocket</strong>',
$this->used_css->get_name(),
'<a href="' . $this->get_support_url() . '" target="_blank" rel="noopener">',
'</a>'
);
rocket_notice_html(
[
'status' => 'error',
'dismissible' => '',
'message' => $message,
'id' => 'rocket-notice-rucss-missing-table',
]
);
}
/**
* Get support URL.
*
* @return string
*/
protected function get_support_url() {
return rocket_get_external_url(
'support',
[
'utm_source' => 'wp_plugin',
'utm_medium' => 'wp_rocket',
]
);
}
}
@@ -0,0 +1,756 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Queue;
use WP_Rocket\Engine\Common\Queue\RUCSSQueueRunner;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Admin_Bar;
class Subscriber implements Subscriber_Interface {
/**
* Settings instance
*
* @var Settings
*/
private $settings;
/**
* Database instance
*
* @var Database
*/
private $database;
/**
* UsedCSS instance
*
* @var UsedCSS
*/
private $used_css;
/**
* Queue instance
*
* @var Queue
*/
private $queue;
/**
* Instantiate the class
*
* @param Settings $settings Settings instance.
* @param Database $database Database instance.
* @param UsedCSS $used_css UsedCSS instance.
* @param Queue $queue Queue instance.
*/
public function __construct( Settings $settings, Database $database, UsedCSS $used_css, Queue $queue ) {
$this->settings = $settings;
$this->database = $database;
$this->used_css = $used_css;
$this->queue = $queue;
}
/**
* Return an array of events that this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events(): array {
$slug = rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' );
return [
'update_option_' . $slug => [
[ 'clean_used_css_and_cache', 9, 2 ],
[ 'maybe_set_processing_transient', 50, 2 ],
[ 'maybe_unlock_preload', 9, 2 ],
[ 'maybe_delete_transient', 10, 2 ],
],
'switch_theme' => 'truncate_used_css',
'permalink_structure_changed' => 'truncate_used_css',
'rocket_domain_options_changed' => 'truncate_used_css',
'wp_trash_post' => 'delete_used_css_on_update_or_delete',
'delete_post' => 'delete_used_css_on_update_or_delete',
'clean_post_cache' => 'delete_used_css_on_update_or_delete',
'wp_update_comment_count' => 'delete_used_css_on_update_or_delete',
'edit_term' => 'delete_term_used_css',
'pre_delete_term' => 'delete_term_used_css',
'admin_post_rocket_clear_usedcss' => 'truncate_used_css_handler',
'admin_post_rocket_clear_usedcss_url' => 'clear_url_usedcss',
'admin_notices' => [
[ 'clear_usedcss_result' ],
[ 'display_processing_notice' ],
[ 'display_success_notice' ],
[ 'display_wrong_license_notice' ],
[ 'display_saas_error_notice' ],
[ 'display_no_table_notice' ],
[ 'notice_write_permissions' ],
],
'rocket_admin_bar_items' => [
[ 'add_clean_used_css_menu_item' ],
[ 'add_clear_usedcss_bar_item' ],
],
'rocket_before_add_field_to_settings' => [
[ 'set_optimize_css_delivery_value', 10, 1 ],
[ 'set_optimize_css_delivery_method_value', 10, 1 ],
],
'rocket_localize_admin_script' => 'add_localize_script_data',
'wp_rocket_upgrade' => [
[ 'set_option_on_update', 14, 2 ],
[ 'update_safelist_items', 15, 2 ],
[ 'delete_used_css', 16, 2 ],
[ 'cancel_pending_jobs_as', 16, 2 ],
[ 'drop_resources_table', 18, 2 ],
],
'wp_ajax_rocket_spawn_cron' => 'spawn_cron',
'rocket_deactivation' => 'cancel_queues',
'admin_head-tools_page_action-scheduler' => 'delete_as_tables_transient_on_tools_page',
'pre_get_rocket_option_remove_unused_css' => 'disable_russ_on_wrong_license',
'rocket_before_rollback' => 'cancel_queues',
];
}
/**
* Delete used_css on Update Post or Delete post.
*
* @since 3.9
*
* @param int $post_id The post ID.
*
* @return void
*/
public function delete_used_css_on_update_or_delete( $post_id ) {
if ( ! $this->settings->is_enabled() ) {
return;
}
if ( ! $this->is_deletion_enabled() ) {
return;
}
$url = get_permalink( $post_id );
if ( false === $url ) {
return;
}
$this->used_css->delete_used_css( untrailingslashit( $url ) );
}
/**
* Maybe unlock all locked preload urls.
*
* @param array $old_value An array of submitted values for the settings.
* @param array $value An array of previous values for the settings.
*
* @return void
*/
public function maybe_unlock_preload( $old_value, $value ) {
if ( ! isset( $value['remove_unused_css'], $old_value['remove_unused_css'] ) ) {
return;
}
if ( $value['remove_unused_css'] === $old_value['remove_unused_css'] ) {
return;
}
if ( $value['remove_unused_css'] ) {
return;
}
do_action( 'rocket_preload_unlock_all_urls' );
}
/**
* Deletes the used CSS when updating a term
*
* @since 3.10.2
*
* @param int $term_id the term ID.
*
* @return void
*/
public function delete_term_used_css( $term_id ) {
if ( ! $this->settings->is_enabled() ) {
return;
}
if ( ! $this->is_deletion_enabled() ) {
return;
}
$url = get_term_link( (int) $term_id );
if ( is_wp_error( $url ) ) {
return;
}
$this->used_css->delete_used_css( untrailingslashit( $url ) );
}
/**
* Truncate RUCSS used_css DB table.
*
* @since 3.9
*
* @return void
*/
public function truncate_used_css() {
if ( ! $this->settings->is_enabled() ) {
return;
}
if ( ! $this->is_deletion_enabled() ) {
return;
}
$this->delete_used_css_rows();
$this->set_notice_transient();
}
/**
* Deletes the used CSS from the table
*
* @since 3.11
*
* @return void
*/
private function delete_used_css_rows() {
$this->used_css->delete_all_used_css();
if ( 0 < $this->used_css->get_not_completed_count() ) {
$this->database->remove_all_completed_rows();
} else {
$this->database->truncate_used_css_table();
}
/**
* Fires after the used CSS has been cleaned in the database
*
* @since 3.11
*/
do_action( 'rocket_after_clean_used_css' );
}
/**
* Truncate UsedCSS DB Table when `remove_unused_css_safelist` is changed.
*
* @since 3.9
*
* @param array $old_value An array of submitted values for the settings.
* @param array $value An array of previous values for the settings.
*
* @return void
*/
public function clean_used_css_and_cache( $old_value, $value ) {
if ( ! isset( $value['remove_unused_css_safelist'], $old_value['remove_unused_css_safelist'] ) ) {
return;
}
if ( $value['remove_unused_css_safelist'] === $old_value['remove_unused_css_safelist'] ) {
return;
}
$this->delete_used_css_rows();
$this->set_notice_transient();
}
/**
* Truncate used_css table when clicking on the dashboard button.
*
* @since 3.9
*
* @return void
*/
public function truncate_used_css_handler() {
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'rocket_clear_usedcss' ) ) {
wp_nonce_ays( '' );
}
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
if ( ! $this->settings->is_enabled() ) {
set_transient(
'rocket_clear_usedcss_response',
[
'status' => 'error',
'message' => sprintf(
// translators: %1$s = plugin name.
__( '%1$s: Used CSS option is not enabled!', 'rocket' ),
'<strong>WP Rocket</strong>'
),
]
);
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
rocket_clean_domain();
$this->delete_used_css_rows();
rocket_dismiss_box( 'rocket_warning_plugin_modification' );
set_transient(
'rocket_clear_usedcss_response',
[
'status' => 'success',
'message' => sprintf(
// translators: %1$s = plugin name.
__( '%1$s: Used CSS cache cleared!', 'rocket' ),
'<strong>WP Rocket</strong>'
),
]
);
$this->set_notice_transient();
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
/**
* Show admin notice after clearing used_css table.
*
* @since 3.9
*
* @return void
*/
public function clear_usedcss_result() {
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
return;
}
if ( ! $this->settings->is_enabled() ) {
return;
}
$response = get_transient( 'rocket_clear_usedcss_response' );
if ( ! $response ) {
return;
}
delete_transient( 'rocket_clear_usedcss_response' );
rocket_notice_html( $response );
}
/**
* Add Clean used CSS link to WP Rocket admin bar item
*
* @since 3.9
*
* @param \WP_Admin_Bar $wp_admin_bar WP_Admin_Bar instance, passed by reference.
*
* @return void
*/
public function add_clean_used_css_menu_item( $wp_admin_bar ) {
$this->settings->add_clean_used_css_menu_item( $wp_admin_bar );
}
/**
* Set optimize css delivery value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_value( $field_args ): array {
return $this->settings->set_optimize_css_delivery_value( $field_args );
}
/**
* Set optimize css delivery method value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_method_value( $field_args ): array {
return $this->settings->set_optimize_css_delivery_method_value( $field_args );
}
/**
* Displays the RUCSS currently processing notice
*
* @since 3.11
*
* @return void
*/
public function display_processing_notice() {
$this->settings->display_processing_notice();
}
/**
* Displays the RUCSS success notice
*
* @since 3.11
*
* @return void
*/
public function display_success_notice() {
$this->settings->display_success_notice();
}
/**
* Display a notification on wrong license.
*
* @return void
*/
public function display_wrong_license_notice() {
$transient = get_option( 'wp_rocket_no_licence' );
if ( ! $transient ) {
return;
}
$this->settings->display_wrong_license_notice();
}
/**
* Display error notice when connection to SAAS fails
*
* @return void
*/
public function display_saas_error_notice() {
$this->settings->display_saas_error_notice();
}
/**
* Display admin notice when detecting any missed Action scheduler tables.
*
* @since 3.11.0.3
*
* @return void
*/
public function display_as_missed_tables_notice() {
$screen = get_current_screen();
if ( isset( $screen->id ) && 'tools_page_action-scheduler' === $screen->id ) {
return;
}
if ( $this->is_valid_as_tables() ) {
return;
}
$this->settings->display_as_missed_tables_notice();
}
/**
* Adds the notice end time to WP Rocket localize script data
*
* @since 3.11
*
* @param array $data Localize script data.
* @return array
*/
public function add_localize_script_data( $data ): array {
return $this->settings->add_localize_script_data( $data );
}
/**
* Clear UsedCSS for the current URL.
*
* @return void
*/
public function clear_url_usedcss() {
check_admin_referer( 'rocket_clear_usedcss_url' );
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
wp_nonce_ays( '' );
}
$url = wp_get_referer();
if ( 0 !== strpos( $url, 'http' ) ) {
$parse_url = get_rocket_parse_url( untrailingslashit( home_url() ) );
$url = $parse_url['scheme'] . '://' . $parse_url['host'] . $url;
}
$this->used_css->clear_url_usedcss( $url );
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
/**
* Add clear UsedCSS adminbar item.
*
* @param WP_Admin_Bar $wp_admin_bar Adminbar object.
*
* @return void
*/
public function add_clear_usedcss_bar_item( WP_Admin_Bar $wp_admin_bar ) {
$this->used_css->add_clear_usedcss_bar_item( $wp_admin_bar );
}
/**
* Disables combine CSS if RUCSS is enabled when updating to 3.11
*
* @since 3.11
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function set_option_on_update( $new_version, $old_version ) {
$this->settings->set_option_on_update( $old_version );
if ( version_compare( $old_version, '3.11', '>=' ) ) {
return;
}
$this->database->truncate_used_css_table();
rocket_clean_domain();
$this->set_notice_transient();
}
/**
* Updates safelist items for new SaaS compatibility
*
* @since 3.11.0.2
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function update_safelist_items( $new_version, $old_version ) {
$this->settings->update_safelist_items( $old_version );
}
/**
* Cancel pending jobs actions in Action Scheduler on update to 3.11.3
*
* @since 3.11.3
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function cancel_pending_jobs_as( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.11.3', '>=' ) ) {
return;
}
try {
$this->queue->cancel_pending_jobs_cron();
} catch ( \InvalidArgumentException $e ) {
// nothing to do.
return;
}
}
/**
* Sets the processing transient if RUCSS is enabled
*
* @since 3.11
*
* @param mixed $old_value Option old value.
* @param mixed $value Option new value.
*
* @return void
*/
public function maybe_set_processing_transient( $old_value, $value ) {
if ( ! isset( $old_value['remove_unused_css'], $value['remove_unused_css'] ) ) {
return;
}
if ( 0 === (int) $value['remove_unused_css'] ) {
return;
}
if ( $old_value['remove_unused_css'] === $value['remove_unused_css'] ) {
return;
}
$this->set_notice_transient();
}
/**
* Sets the transient for the processing notice
*
* @since 3.11
*
* @return void
*/
private function set_notice_transient() {
set_transient(
'rocket_rucss_processing',
time() + 90,
1.5 * MINUTE_IN_SECONDS
);
rocket_renew_box( 'rucss_success_notice' );
}
/**
* Sends a request to run cron when switching to RUCSS completed notice
*
* @since 3.11
*
* @return void
*/
public function spawn_cron() {
check_ajax_referer( 'rocket-ajax', 'nonce' );
if ( ! current_user_can( 'rocket_manage_options' ) ) {
wp_send_json_error();
return;
}
spawn_cron();
wp_send_json_success();
}
/**
* Cancel queues and crons for RUCSS.
*
* @return void
*/
public function cancel_queues() {
// Will unhook check for dispatching an async request without RUCSS process running.
\ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request();
// Will unhook check for dispatching an async request when RUCSS process is already running.
RUCSSQueueRunner::instance()->unhook_dispatch_async_request();
$this->queue->cancel_pending_jobs_cron();
if ( ! wp_next_scheduled( 'rocket_rucss_clean_rows_time_event' ) ) {
return;
}
wp_clear_scheduled_hook( 'rocket_rucss_clean_rows_time_event' );
}
/**
* Delete the transient for Action scheduler once admin visits the AS tools page.
*
* @return void
*/
public function delete_as_tables_transient_on_tools_page() {
delete_transient( 'rocket_rucss_as_tables_count' );
}
/**
* Deletes the used CSS on update to 3.11.4 for new storage method
*
* @since 3.11.4
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function delete_used_css( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.11.4', '>=' ) ) {
return;
}
$this->database->truncate_used_css_table();
}
/**
* Disable RUCSS on wrong license.
*
* @return bool
*/
public function disable_russ_on_wrong_license() {
if ( false !== (bool) get_option( 'wp_rocket_no_licence' ) ) {
return false;
}
return null;
}
/**
* Remove the resources table & version stored in options table on update to 3.12
*
* @since 3.12
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function drop_resources_table( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.12', '>=' ) ) {
return;
}
$this->database->drop_resources_table();
}
/**
* Displays a notice if the used CSS folder is not writable
*
* @since 3.11.4
*
* @return void
*/
public function notice_write_permissions() {
$this->used_css->notice_write_permissions();
}
/**
* Display a notice on table missing.
*
* @return void
*/
public function display_no_table_notice() {
$this->settings->display_no_table_notice();
}
/**
* Maybe delete transient.
*
* @param mixed $old_value Option old value.
* @param mixed $value Option new value.
*
* @return void
*/
public function maybe_delete_transient( $old_value, $value ) {
if ( ! isset( $old_value['remove_unused_css'], $value['remove_unused_css'] ) ) {
return;
}
if ( 1 === (int) $value['remove_unused_css'] ) {
return;
}
if ( $old_value['remove_unused_css'] === $value['remove_unused_css'] ) {
return;
}
delete_transient( 'wp_rocket_no_licence' );
}
/**
* Checks if the RUCSS deletion is enabled.
*
* @return bool
*/
protected function is_deletion_enabled(): bool {
/**
* Filters the enable RUCSS deletion value
*
* @param bool $delete_rucss True to enable deletion, false otherwise.
*/
return (bool) apply_filters( 'rocket_rucss_deletion_enabled', true );
}
}
@@ -0,0 +1,56 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Context;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Common\Context\AbstractContext;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Filesystem;
class RUCSSContext extends AbstractContext {
/**
* Filesystem instance
*
* @var Filesystem
*/
protected $filesystem;
/**
* Instantiate the class.
*
* @param Options_Data $options Options.
* @param Filesystem $filesystem Filesystem instance.
*/
public function __construct( Options_Data $options, Filesystem $filesystem ) {
parent::__construct( $options );
$this->filesystem = $filesystem;
}
/**
* Check if the operation is allowed.
*
* @param array $data Data to provide 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' => 'remove_unused_css',
'password_protected' => false,
'post_excluded' => 'remove_unused_css',
'logged_in' => false,
]
);
if ( ! $is_allowed ) {
return false;
}
return $this->filesystem->is_writable_folder();
}
}
@@ -0,0 +1,46 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Context;
use WP_Rocket\Engine\Common\Context\AbstractContext;
class RUCSSOptimizeContext extends AbstractContext {
/**
* Check if the operation is allowed.
*
* @param array $data Data to provide to the context.
* @return bool
*/
public function is_allowed( array $data = [] ): bool {
$is_allowed = $this->run_common_checks(
[
'bypass' => false,
'option' => 'remove_unused_css',
'post_excluded' => 'remove_unused_css',
]
);
if ( 'local' === wp_get_environment_type() ) {
return false;
}
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
return false;
}
if ( is_admin() ) {
return false;
}
if ( ! $is_allowed ) {
return false;
}
if ( ! rocket_can_display_options() ) {
return false;
}
return true;
}
}
@@ -0,0 +1,173 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Controller;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class Filesystem {
/**
* WP Filesystem instance
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Path to the used CSS storage
*
* @var string
*/
private $path;
/**
* Instantiate the class
*
* @param string $base_path Base path to the used CSS storage.
* @param WP_Filesystem_Direct $filesystem WP Filesystem instance.
*/
public function __construct( $base_path, $filesystem = null ) {
$this->filesystem = is_null( $filesystem ) ? rocket_direct_filesystem() : $filesystem;
$this->path = $base_path . get_current_blog_id() . '/';
}
/**
* Get the file path for the used CSS file.
*
* @param string $hash Hash of the file contents.
*
* @return string Path for the used CSS file.
*/
private function get_usedcss_full_path( string $hash ) {
return $this->path . $this->hash_to_path( $hash ) . '.css' . ( function_exists( 'gzdecode' ) ? '.gz' : '' );
}
/**
* Gets the used CSS content corresponding to the provided hash
*
* @param string $hash Hash of the corresponding used CSS.
*
* @return string
*/
public function get_used_css( string $hash ): string {
$file = $this->get_usedcss_full_path( $hash );
if ( ! $this->filesystem->exists( $file ) ) {
return '';
}
$file_contents = $this->filesystem->get_contents( $file );
$css = function_exists( 'gzdecode' ) ? gzdecode( $file_contents ) : $file_contents;
if ( ! $css ) {
return '';
}
return $css;
}
/**
* Writes the used CSS to the filesystem
*
* @param string $hash Hash to use for the filename.
* @param string $used_css Used CSS content.
*
* @return bool
*/
public function write_used_css( string $hash, string $used_css ): bool {
$file = $this->get_usedcss_full_path( $hash );
if ( ! rocket_mkdir_p( dirname( $file ) ) ) {
return false;
}
// This filter is documented in inc/classes/Buffer/class-cache.php.
$css = function_exists( 'gzencode' ) ? gzencode( $used_css, apply_filters( 'rocket_gzencode_level_compression', 6 ) ) : $used_css;
if ( ! $css ) {
return false;
}
return $this->filesystem->put_contents( $file, $css, rocket_get_filesystem_perms( 'file' ) );
}
/**
* Deletes the used CSS files for the corresponding hash
*
* @since 3.11.4
*
* @param string $hash md5 hash string.
*
* @return bool
*/
public function delete_used_css( string $hash ): bool {
$file = $this->get_usedcss_full_path( $hash );
return $this->filesystem->delete( $file, false, 'f' );
}
/**
* Deletes all the used CSS files
*
* @since 3.11.4
*
* @return void
*/
public function delete_all_used_css() {
try {
$dir = new RecursiveDirectoryIterator( $this->path, \FilesystemIterator::SKIP_DOTS );
$items = new RecursiveIteratorIterator( $dir, RecursiveIteratorIterator::CHILD_FIRST );
foreach ( $items as $item ) {
$this->filesystem->delete( $item );
}
} catch ( \Exception $e ) {
return;
}
}
/**
* Checks if the used CSS storage folder is writable
*
* @since 3.11.4
*
* @return bool
*/
public function is_writable_folder() {
if ( ! $this->filesystem->exists( $this->path ) ) {
rocket_mkdir_p( $this->path );
}
return $this->filesystem->is_writable( $this->path );
}
/**
* Converts hash to path with filtered number of levels
*
* @since 3.11.4
*
* @param string $hash md5 hash string.
*
* @return string
*/
private function hash_to_path( string $hash ): string {
/**
* Filters the number of sub-folders level to create for used CSS storage
*
* @since 3.11.4
*
* @param int $levels Number of levels.
*/
$levels = apply_filters( 'rocket_used_css_dir_level', 3 );
$base = substr( $hash, 0, $levels );
$remain = substr( $hash, $levels );
$path_array = str_split( $base );
$path_array[] = $remain;
return implode( '/', $path_array );
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Controller;
use WP_Rocket\Engine\Common\Queue\AbstractASQueue;
/**
* Queue
*
* A job queue using WordPress actions.
*
* @version 3.11.0
*/
class Queue extends AbstractASQueue {
/**
* Queue group.
*
* @var string
*/
protected $group = 'rocket-rucss';
/**
* Pending jobs cron hook.
*
* @var string
*/
private $pending_job_cron = 'rocket_rucss_pending_jobs_cron';
/**
* Check if pending jobs cron is scheduled.
*
* @return bool
*/
public function is_pending_jobs_cron_scheduled() {
return $this->is_scheduled( $this->pending_job_cron );
}
/**
* Cancel pending jobs cron.
*
* @return void
*/
public function cancel_pending_jobs_cron() {
$this->cancel_all( $this->pending_job_cron );
}
/**
* Schedule pending jobs cron.
*
* @param int $interval Cron interval in seconds.
*
* @return string
*/
public function schedule_pending_jobs_cron( int $interval ) {
return $this->schedule_recurring( time(), $interval, $this->pending_job_cron );
}
/**
* Add Async job with DB row ID.
*
* @param int $usedcss_row_id DB row ID.
*
* @return string
*/
public function add_job_status_check_async( int $usedcss_row_id ) {
return $this->add_async(
'rocket_rucss_job_check_status',
[
$usedcss_row_id,
]
);
}
}
@@ -0,0 +1,308 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Cron;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Engine\Common\Queue\RUCSSQueueRunner;
use WP_Rocket\Engine\Optimization\RUCSS\Admin\Database;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS;
class Subscriber implements Subscriber_Interface {
/**
* UsedCss instance
*
* @var UsedCSS
*/
private $used_css;
/**
* Database instance
*
* @var Database
*/
private $database;
/**
* Instantiate the class
*
* @param UsedCSS $used_css UsedCSS instance.
* @param Database $database Database instance.
*/
public function __construct( UsedCSS $used_css, Database $database ) {
$this->used_css = $used_css;
$this->database = $database;
}
/**
* Return an array of events that this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_rucss_pending_jobs' => 'process_pending_jobs',
'rocket_rucss_on_submit_jobs' => 'process_on_submit_jobs',
'rocket_rucss_job_check_status' => 'check_job_status',
'rocket_rucss_clean_rows_time_event' => 'cron_clean_rows',
'cron_schedules' => 'add_interval',
'rocket_deactivation' => 'on_deactivation',
'rocket_remove_rucss_failed_jobs' => 'cron_remove_failed_jobs',
'init' => [
[ 'schedule_clean_not_commonly_used_rows' ],
[ 'schedule_pending_jobs' ],
[ 'initialize_rucss_queue_runner' ],
[ 'schedule_removing_failed_jobs' ],
[ 'schedule_on_submit_jobs' ],
],
];
}
/**
* Schedules cron to clean not commonly used RUCSS rows.
*
* @since 3.9
*
* @return void
*/
public function schedule_clean_not_commonly_used_rows() {
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_rucss_clean_rows_time_event' ) ) {
return;
}
wp_schedule_event( time(), 'weekly', 'rocket_rucss_clean_rows_time_event' );
}
/**
* Initialize the queue runner for our RUCSS.
*
* @return void
*/
public function initialize_rucss_queue_runner() {
if ( ! $this->used_css->is_enabled() ) {
return;
}
RUCSSQueueRunner::instance()->init();
}
/**
* Process pending jobs with Cron iteration.
*
* @return void
*/
public function process_pending_jobs() {
$this->used_css->process_pending_jobs();
}
/**
* Process on submit jobs with Cron iteration.
*
* @return void
*/
public function process_on_submit_jobs() {
$this->used_css->process_on_submit_jobs();
}
/**
* Cron callback for deleting old rows in both table databases.
*
* @since 3.9
*
* @return void
*/
public function cron_clean_rows() {
if ( ! $this->is_deletion_enabled() ) {
return;
}
$this->database->delete_old_used_css();
}
/**
* Cron callback for removing failed jobs.
*
* @return void
*/
public function cron_remove_failed_jobs() {
$this->used_css->clear_failed_urls();
}
/**
* Handle job status by DB row ID.
*
* @param int $row_id DB Row ID.
*
* @return void
*/
public function check_job_status( int $row_id ) {
$this->used_css->check_job_status( $row_id );
}
/**
* Adds new interval for RUCSS pending jobs cron
*
* @since 3.11.3
*
* @param array[] $schedules An array of non-default cron schedule arrays.
*
* @return array
*/
public function add_interval( $schedules ) {
if ( ! $this->used_css->is_enabled() ) {
return $schedules;
}
/**
* Filters the cron interval.
*
* @since 3.11
*
* @param int $interval Interval in seconds.
*/
$interval = apply_filters( 'rocket_rucss_pending_jobs_cron_interval', 1 * rocket_get_constant( 'MINUTE_IN_SECONDS', 60 ) );
$schedules['rocket_rucss_pending_jobs'] = [
'interval' => $interval,
'display' => esc_html__( 'WP Rocket Remove Unused CSS pending jobs', 'rocket' ),
];
$default_interval = 3 * rocket_get_constant( 'DAY_IN_SECONDS', 86400 );
/**
* Filters the cron interval for clearing failed jobs.
*
* @param int $interval Interval in seconds.
*/
$interval = apply_filters( 'rocket_remove_rucss_failed_jobs_cron_interval', $default_interval );
$interval = (bool) $interval ? $interval : $default_interval;
$schedules['rocket_remove_rucss_failed_jobs'] = [
'interval' => $interval,
'display' => esc_html__( 'WP Rocket clear Remove Unused CSS failed jobs', 'rocket' ),
];
/**
* Filters the cron interval for processing on submit jobs.
*
* @param int $interval Interval in seconds.
*/
$interval = (int) apply_filters( 'rocket_remove_rucss_on_submit_jobs_cron_interval', 1 * rocket_get_constant( 'MINUTE_IN_SECONDS', 60 ) );
$schedules['rocket_rucss_on_submit_jobs'] = [
'interval' => $interval,
'display' => esc_html__( 'WP Rocket procees on submit jobs', 'rocket' ),
];
return $schedules;
}
/**
* Schedule on submit jobs.
*
* @return void
*/
public function schedule_on_submit_jobs() {
if (
! $this->used_css->is_enabled()
&&
wp_next_scheduled( 'rocket_rucss_on_submit_jobs' )
) {
wp_clear_scheduled_hook( 'rocket_rucss_on_submit_jobs' );
return;
}
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_rucss_on_submit_jobs' ) ) {
return;
}
wp_schedule_event( time(), 'rocket_rucss_on_submit_jobs', 'rocket_rucss_on_submit_jobs' );
}
/**
* Schedules cron to get RUCSS pendings jobs.
*
* @since 3.11.3
*
* @return void
*/
public function schedule_pending_jobs() {
if (
! $this->used_css->is_enabled()
&&
wp_next_scheduled( 'rocket_rucss_pending_jobs' )
) {
wp_clear_scheduled_hook( 'rocket_rucss_pending_jobs' );
return;
}
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_rucss_pending_jobs' ) ) {
return;
}
wp_schedule_event( time(), 'rocket_rucss_pending_jobs', 'rocket_rucss_pending_jobs' );
}
/**
* Schedules cron to remove failed jobs.
*
* @return void
*/
public function schedule_removing_failed_jobs() {
if (
! $this->used_css->is_enabled()
&&
wp_next_scheduled( 'rocket_remove_rucss_failed_jobs' )
) {
wp_clear_scheduled_hook( 'rocket_remove_rucss_failed_jobs' );
return;
}
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_remove_rucss_failed_jobs' ) ) {
return;
}
wp_schedule_event( time(), 'rocket_remove_rucss_failed_jobs', 'rocket_remove_rucss_failed_jobs' );
}
/**
* Clear schedule of RUCSS CRONs on deactivation.
*
* @return void
*/
public function on_deactivation() {
wp_clear_scheduled_hook( 'action_scheduler_run_queue_rucss', [ 'WP Cron' ] );
}
/**
* Checks if the RUCSS deletion is enabled.
*
* @return bool
*/
protected function is_deletion_enabled(): bool {
/**
* Filters the enable RUCSS deletion value
*
* @param bool $delete_rucss True to enable deletion, false otherwise.
*/
return (bool) apply_filters( 'rocket_rucss_deletion_enabled', true );
}
}
@@ -0,0 +1,608 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Queries;
use WP_Rocket\Dependencies\Database\Query;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Row\UsedCSS as UsedCSSRow;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Schemas\UsedCSS as UsedCSSSchema;
/**
* RUCSS UsedCSS Query.
*/
class UsedCSS extends Query {
/**
* Name of the database table to query.
*
* @var string
*/
protected $table_name = 'wpr_rucss_used_css';
/**
* String used to alias the database table in MySQL statement.
*
* Keep this short, but descriptive. I.E. "tr" for term relationships.
*
* This is used to avoid collisions with JOINs.
*
* @var string
*/
protected $table_alias = 'wpr_rucss';
/**
* Name of class used to setup the database schema.
*
* @var string
*/
protected $table_schema = UsedCSSSchema::class;
/** Item ******************************************************************/
/**
* Name for a single item.
*
* Use underscores between words. I.E. "term_relationship"
*
* This is used to automatically generate action hooks.
*
* @var string
*/
protected $item_name = 'used_css';
/**
* Plural version for a group of items.
*
* Use underscores between words. I.E. "term_relationships"
*
* This is used to automatically generate action hooks.
*
* @var string
*/
protected $item_name_plural = 'used_css';
/**
* Name of class used to turn IDs into first-class objects.
*
* This is used when looping through return values to guarantee their shape.
*
* @var mixed
*/
protected $item_shape = UsedCSSRow::class;
/**
* Table status.
*
* @var boolean
*/
public static $table_exists = false;
/**
* Get pending jobs.
*
* @param int $count Number of rows.
*
* @return array
*/
public function get_pending_jobs( int $count = 100 ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return [];
}
$inprogress_count = $this->query(
[
'count' => true,
'status' => 'in-progress',
]
);
if ( $inprogress_count >= $count ) {
return [];
}
return $this->query(
[
'number' => ( $count - $inprogress_count ),
'status' => 'pending',
'fields' => [
'id',
'url',
],
'job_id__not_in' => [
'not_in' => '',
],
'orderby' => 'modified',
'order' => 'asc',
]
);
}
/**
* Fetch on submit jobs.
*
* @param int $count Number of jobs to fetch.
* @return array|int
*/
public function get_on_submit_jobs( int $count = 100 ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return [];
}
$in_progress_count = $this->query(
[
'count' => true,
'status' => [ 'in-progress' ],
]
);
$pending_count = $this->query(
[
'count' => true,
'status' => [ 'pending' ],
]
);
$processing_count = $in_progress_count + $pending_count;
if ( 0 !== $count && $processing_count >= $count ) {
return [];
}
$query_params = [
'status' => 'to-submit',
'orderby' => 'modified',
'order' => 'asc',
];
if ( 0 !== $count ) {
$query_params['number'] = ( $count - $processing_count );
}
return $this->query( $query_params );
}
/**
* Increment retries number and change status back to pending.
*
* @param int $id DB row ID.
* @param int $retries Current number of retries.
*
* @return bool
*/
public function increment_retries( $id, $retries = 0 ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$update_data = [
'retries' => $retries + 1,
'status' => 'pending',
];
return $this->update_item( $id, $update_data );
}
/**
* Update Job ID.
*
* @param int $id DB row ID.
* @param int $new_job_id new job id.
*
* @return bool
*/
public function update_job_id( $id, $new_job_id ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$update_data['job_id'] = $new_job_id;
return $this->update_item( $id, $update_data );
}
/**
* Create new DB row for specific url.
*
* @param string $url Current page url.
* @param string $job_id API job_id.
* @param string $queue_name API Queue name.
* @param bool $is_mobile if the request is for mobile page.
*
* @return bool
*/
public function create_new_job( string $url, string $job_id = '', string $queue_name = '', bool $is_mobile = false ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$item = [
'url' => untrailingslashit( $url ),
'is_mobile' => $is_mobile,
'job_id' => $job_id,
'queue_name' => $queue_name,
'status' => 'to-submit',
'retries' => 0,
'last_accessed' => current_time( 'mysql', true ),
'submitted_at' => current_time( 'mysql', true ),
];
return $this->add_item( $item );
}
/**
* Change the status to be in-progress.
*
* @param int $id DB row ID.
*
* @return bool
*/
public function make_status_inprogress( int $id ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'status' => 'in-progress',
]
);
}
/**
* Reset the job and add new job_id pending.
*
* @param int $id DB row ID.
* @param string $job_id API job_id.
*
* @return bool
*/
public function reset_job( int $id, string $job_id = '' ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'job_id' => $job_id,
'status' => 'to-submit',
'error_code' => '',
'error_message' => '',
'retries' => 0,
'modified' => current_time( 'mysql', true ),
'submitted_at' => current_time( 'mysql', true ),
]
);
}
/**
* Change the status to be failed.
*
* @param int $id DB row ID.
* @param string $error_code error code.
* @param string $error_message error message.
*
* @return bool
*/
public function make_status_failed( int $id, string $error_code, string $error_message ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'status' => 'failed',
'error_code' => $error_code,
'error_message' => current_time( 'mysql', true ) . " {$error_code}: {$error_message}",
]
);
}
/**
* Complete a job.
*
* @param int $id DB row ID.
* @param string $hash Hash.
*
* @return bool
*/
public function make_status_completed( int $id, string $hash = '' ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'hash' => $hash,
'status' => 'completed',
]
);
}
/**
* Get Used CSS for specific url.
*
* @param string $url Page Url.
* @param bool $is_mobile if the request is for mobile page.
*
* @return false|mixed
*/
public function get_row( string $url, bool $is_mobile = false ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$query = $this->query(
[
'url' => untrailingslashit( $url ),
'is_mobile' => $is_mobile,
]
);
if ( empty( $query[0] ) ) {
return false;
}
return $query[0];
}
/**
* Get all rows with the same url (desktop and mobile versions).
*
* @param string $url Page url.
*
* @return array|false
*/
public function get_rows_by_url( string $url ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$query = $this->query(
[
'url' => untrailingslashit( $url ),
]
);
if ( empty( $query ) ) {
return false;
}
return $query;
}
/**
* Get number of rows with the same hash value.
*
* @param string $hash Hash.
*
* @return int
*/
public function count_rows_by_hash( string $hash ): int {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return 0;
}
return $this->query(
[
'hash' => $hash,
'count' => true,
]
);
}
/**
* Update UsedCSS Row last_accessed date to current date.
*
* @param int $id Used CSS id.
*
* @return bool
*/
public function update_last_accessed( int $id ): bool {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return (bool) $this->update_item(
$id,
[
'last_accessed' => current_time( 'mysql', true ),
]
);
}
/**
* Delete DB row by url.
*
* @param string $url Page url to be deleted.
*
* @return bool
*/
public function delete_by_url( string $url ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$items = $this->get_rows_by_url( $url );
if ( ! $items ) {
return false;
}
$deleted = true;
foreach ( $items as $item ) {
$deleted = $deleted && $this->delete_item( $item->id );
}
return $deleted;
}
/**
* Get the count of not completed rows.
*
* @return int
*/
public function get_not_completed_count() {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return 0;
}
return $this->query(
[
'count' => true,
'status__in' => [ 'pending', 'in-progress' ],
]
);
}
/**
* Get the count of completed rows.
*
* @return int
*/
public function get_completed_count() {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return 0;
}
return $this->query(
[
'count' => true,
'status' => 'completed',
]
);
}
/**
* Get all failed rows.
*
* @param float $delay delay before the urls are deleted.
* @param string $unit unit from the delay.
* @return array|false
*/
public function get_failed_rows( float $delay = 3, string $unit = 'days' ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$query = $this->query(
[
'status' => 'failed',
'date_query' => [
[
'column' => 'modified',
'before' => "$delay $unit ago",
'inclusive' => true,
],
],
],
false
);
if ( empty( $query ) ) {
return false;
}
return $query;
}
/**
* Revert status to pending.
*
* @param integer $id Used CSS id.
* @return boolean
*/
public function revert_to_pending( int $id ): bool {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return (bool) $this->update_item(
$id,
[
'error_code' => '',
'error_message' => '',
'retries' => 0,
'status' => 'pending',
'modified' => current_time( 'mysql', true ),
]
);
}
/**
* Returns the current status of `wpr_rucss_used_css` table; true if it exists, false otherwise.
*
* @return boolean
*/
private function table_exists(): bool {
if ( self::$table_exists ) {
return true;
}
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
// Query statement.
$query = 'SHOW TABLES LIKE %s';
$like = $db->esc_like( $db->{$this->table_name} );
$prepared = $db->prepare( $query, $like );
$result = $db->get_var( $prepared );
// Does the table exist?
$exists = $this->is_success( $result );
if ( $exists ) {
self::$table_exists = $exists;
}
return $exists;
}
/**
* Update the error message.
*
* @param int $job_id Job ID.
* @param int $code Response code.
* @param string $message Response message.
* @param string $previous_message Previous saved message.
*
* @return bool
*/
public function update_message( int $job_id, int $code, string $message, string $previous_message = '' ): bool {
return $this->update_item(
$job_id,
[
'error_message' => $previous_message . ' - ' . current_time( 'mysql', true ) . " {$code}: {$message}",
]
);
}
/**
* Change the status to be pending.
*
* @param int $id DB row ID.
* @param string $job_id API job_id.
* @param string $queue_name API Queue name.
* @param bool $is_mobile if the request is for mobile page.
* @return bool
*/
public function make_status_pending( int $id, string $job_id = '', string $queue_name = '', bool $is_mobile = false ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'job_id' => $job_id,
'queue_name' => $queue_name,
'status' => 'pending',
'is_mobile' => $is_mobile,
]
);
}
}
@@ -0,0 +1,140 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Row;
use WP_Rocket\Dependencies\Database\Row;
/**
* RUCSS UsedCSS Row.
*/
class UsedCSS extends Row {
/**
* Row ID
*
* @var int
*/
public $id;
/**
* URL
*
* @var string
*/
public $url;
/**
* CSS
*
* @var string
*/
public $css;
/**
* Hash storage value
*
* @var string
*/
public $hash;
/**
* Error code
*
* @var string
*/
public $error_code;
/**
* Error message
*
* @var string
*/
public $error_message;
/**
* Number of retries
*
* @var int
*/
public $retries;
/**
* Is CSS for mobile
*
* @var bool
*/
public $is_mobile;
/**
* Job ID
*
* @var string
*/
public $job_id;
/**
* Job queue name
*
* @var string
*/
public $queue_name;
/**
* Status
*
* @var string
*/
public $status;
/**
* Last modified time
*
* @var int
*/
public $modified;
/**
* Last accessed time
*
* @var int
*/
public $last_accessed;
/**
* Unused variable
*
* @var string
*/
public $unprocessedcss;
/**
* Submitted date
*
* @var int
*/
public $submitted_at;
/**
* UsedCSS constructor.
*
* @param mixed $item Object Row.
*/
public function __construct( $item ) {
parent::__construct( $item );
// Set the type of each column, and prepare.
$this->id = (int) $this->id;
$this->url = (string) $this->url;
$this->css = (string) $this->css;
$this->hash = (string) $this->hash;
$this->error_code = (string) $this->error_code;
$this->error_message = (string) $this->error_message;
$this->retries = (int) $this->retries;
$this->is_mobile = (bool) $this->is_mobile;
$this->job_id = (string) $this->job_id;
$this->queue_name = (string) $this->queue_name;
$this->status = (string) $this->status;
$this->modified = empty( $this->modified ) ? 0 : strtotime( $this->modified );
$this->last_accessed = empty( $this->last_accessed ) ? 0 : strtotime( $this->last_accessed );
$this->submitted_at = empty( $this->submitted_at ) ? 0 : strtotime( $this->submitted_at );
}
}
@@ -0,0 +1,168 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Schemas;
use WP_Rocket\Dependencies\Database\Schema;
/**
* RUCSS UsedCSS Schema.
*/
class UsedCSS extends Schema {
/**
* Array of database column objects
*
* @var array
*/
public $columns = [
// ID column.
[
'name' => 'id',
'type' => 'bigint',
'length' => '20',
'unsigned' => true,
'extra' => 'auto_increment',
'primary' => true,
'sortable' => true,
],
// URL column.
[
'name' => 'url',
'type' => 'varchar',
'length' => '2000',
'default' => '',
'cache_key' => true,
'searchable' => true,
'sortable' => true,
],
// CSS column.
[
'name' => 'css',
'type' => 'longtext',
'default' => null,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// Hash column.
[
'name' => 'hash',
'type' => 'varchar',
'length' => '32',
'default' => '',
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// error_code column.
[
'name' => 'error_code',
'type' => 'varchar',
'length' => '32',
'default' => null,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// error_message column.
[
'name' => 'error_message',
'type' => 'longtext',
'default' => null,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// RETRIES column.
[
'name' => 'retries',
'type' => 'tinyint',
'length' => '1',
'default' => 1,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// IS_MOBILE column.
[
'name' => 'is_mobile',
'type' => 'tinyint',
'length' => '1',
'default' => 0,
'cache_key' => true,
'searchable' => true,
'sortable' => true,
],
// JOB_ID column.
[
'name' => 'job_id',
'type' => 'varchar',
'length' => '255',
'default' => null,
'cache_key' => true,
'searchable' => false,
'sortable' => false,
],
// QUEUE_NAME column.
[
'name' => 'queue_name',
'type' => 'varchar',
'length' => '255',
'default' => null,
'cache_key' => true,
'searchable' => false,
'sortable' => false,
],
// STATUS column.
[
'name' => 'status',
'type' => 'varchar',
'length' => '255',
'default' => null,
'cache_key' => true,
'searchable' => true,
'sortable' => false,
],
// MODIFIED column.
[
'name' => 'modified',
'type' => 'timestamp',
'default' => '0000-00-00 00:00:00',
'created' => true,
'date_query' => true,
'sortable' => true,
],
// LAST_ACCESSED column.
[
'name' => 'last_accessed',
'type' => 'timestamp',
'default' => '0000-00-00 00:00:00',
'created' => true,
'date_query' => true,
'sortable' => true,
],
// SUBMITTED_AT column.
[
'name' => 'submitted_at',
'type' => 'timestamp',
'default' => null,
'created' => true,
'date_query' => true,
'sortable' => true,
],
];
}
@@ -0,0 +1,345 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Tables;
use WP_Rocket\Dependencies\Database\Table;
/**
* RUCSS UsedCSS Table.
*/
class UsedCSS extends Table {
/**
* Table name
*
* @var string
*/
protected $name = 'wpr_rucss_used_css';
/**
* Database version key (saved in _options or _sitemeta)
*
* @var string
*/
protected $db_version_key = 'wpr_rucss_used_css_version';
/**
* Database version
*
* @var int
*/
protected $version = 20231010;
/**
* Key => value array of versions => methods.
*
* @var array
*/
protected $upgrades = [
20220121 => 'add_async_rucss_columns',
20220131 => 'make_status_column_index',
20220513 => 'add_hash_column',
20220920 => 'make_status_column_index_instead_queue_name',
20221104 => 'add_error_columns',
20231010 => 'add_submitted_at_column',
];
/**
* Instantiate class.
*/
public function __construct() {
parent::__construct();
add_action( 'admin_init', [ $this, 'maybe_trigger_recreate_table' ], 9 );
add_action( 'init', [ $this, 'maybe_upgrade' ] );
}
/**
* Setup the database schema
*
* @return void
*/
protected function set_schema() {
$this->schema = "
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
url varchar(2000) NOT NULL default '',
css longtext default NULL,
hash varchar(32) default '',
error_code varchar(32) NULL default NULL,
error_message longtext NULL default NULL,
unprocessedcss longtext NULL,
retries tinyint(1) NOT NULL default 1,
is_mobile tinyint(1) NOT NULL default 0,
job_id varchar(255) NOT NULL default '',
queue_name varchar(255) NOT NULL default '',
status varchar(255) NOT NULL default '',
modified timestamp NOT NULL default '0000-00-00 00:00:00',
last_accessed timestamp NOT NULL default '0000-00-00 00:00:00',
submitted_at timestamp NULL,
PRIMARY KEY (id),
KEY url (url(150), is_mobile),
KEY modified (modified),
KEY last_accessed (last_accessed),
INDEX `status_index` (`status`(191)),
INDEX `error_code_index` (`error_code`(32)),
KEY hash (hash)";
}
/**
* Delete all used_css which were not accessed in the last month.
*
* @return bool|int
*/
public function delete_old_used_css() {
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
/**
* Filters the old RUCSS deletion interval
*
* @param int $delete_interval Old RUCSS deletion interval in months
*/
$delete_interval = (int) apply_filters( 'rocket_rucss_delete_interval', 1 );
if ( $delete_interval <= 0 ) {
return false;
}
$prefixed_table_name = $this->apply_prefix( $this->table_name );
$query = "DELETE FROM `$prefixed_table_name` WHERE `last_accessed` <= date_sub(now(), interval $delete_interval month)";
$rows_affected = $db->query( $query );
return $rows_affected;
}
/**
* Get all used_css which were not accessed in the last month.
*
* @return array
*/
public function get_old_used_css(): array {
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
$prefixed_table_name = $this->apply_prefix( $this->table_name );
$query = "SELECT * FROM `$prefixed_table_name` WHERE `last_accessed` <= date_sub(now(), interval 1 month)";
$rows_affected = $db->get_results( $query );
return $rows_affected;
}
/**
* Add queue columns.
*
* @return bool
*/
protected function add_async_rucss_columns() {
$jobid_column_exists = $this->column_exists( 'job_id' );
$queuename_column_exists = $this->column_exists( 'queue_name' );
$status_column_exists = $this->column_exists( 'status' );
$created = true;
if ( ! $jobid_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN job_id VARCHAR(255) NULL default '' AFTER is_mobile " );
}
if ( ! $queuename_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN queue_name VARCHAR(255) NULL default '' AFTER job_id " );
}
if ( ! $status_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN status VARCHAR(255) NULL default '' AFTER queue_name " );
}
return $this->is_success( $created );
}
/**
* Make status column as index.
*
* @return bool
*/
protected function make_status_column_index() {
$queuename_column_exists = $this->column_exists( 'queue_name' );
if ( ! $queuename_column_exists ) {
return $this->is_success( false );
}
if ( $this->index_exists( 'queue_name_index' ) ) {
return $this->is_success( true );
}
$index_added = $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD INDEX `queue_name_index` (`queue_name`) " );
return $this->is_success( $index_added );
}
/**
* Add hash column and index
*
* @return bool
*/
protected function add_hash_column() {
$hash_column_exists = $this->column_exists( 'hash' );
$created = true;
if ( ! $hash_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN hash VARCHAR(32) NULL default '' AFTER css, ADD KEY hash (hash) " );
}
return $this->is_success( $created );
}
/**
* Make status column as index.
*
* @return bool
*/
protected function make_status_column_index_instead_queue_name() {
$queuename_column_exists = $this->column_exists( 'status' );
if ( ! $queuename_column_exists ) {
return $this->is_success( false );
}
if ( $this->index_exists( 'status_index' ) ) {
return $this->is_success( true );
}
if ( $this->index_exists( 'queue_name_index' ) ) {
if ( ! $this->get_db()->query( "ALTER TABLE {$this->table_name} DROP INDEX `queue_name_index`" ) ) {
return $this->is_success( false );
}
}
$index_added = $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD INDEX `status_index` (`status`(191)) " );
return $this->is_success( $index_added );
}
/**
* Remove all completed rows.
*
* @return bool|int
*/
public function remove_all_completed_rows() {
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
$prefixed_table_name = $this->apply_prefix( $this->table_name );
return $db->query( "DELETE FROM `$prefixed_table_name` WHERE status IN ( 'failed', 'completed' )" );
}
/**
* Returns name from table.
*
* @return string
*/
public function get_name() {
return $this->apply_prefix( $this->table_name );
}
/**
* Trigger recreation of cache table if not exist.
*
* @return void
*/
public function maybe_trigger_recreate_table() {
if ( $this->exists() ) {
return;
}
delete_option( $this->db_version_key );
}
/**
* Add error columns
*
* @return bool
*/
protected function add_error_columns() {
return $this->add_error_message_column() && $this->add_error_code_column() && $this->make_error_code_column_index();
}
/**
* Add error_message column and index
*
* @return bool
*/
private function add_error_message_column() {
$error_message_column_exists = $this->column_exists( 'error_message' );
$created = true;
if ( ! $error_message_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE `{$this->table_name}` ADD COLUMN error_message longtext NULL default NULL AFTER hash" );
}
return $this->is_success( $created );
}
/**
* Add error_code column and index
*
* @return bool
*/
private function add_error_code_column() {
$error_code_column_exists = $this->column_exists( 'error_code' );
$created = true;
if ( ! $error_code_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE `{$this->table_name}` ADD COLUMN error_code VARCHAR(32) NULL default NULL AFTER hash" );
}
return $this->is_success( $created );
}
/**
* Make status column as index.
*
* @return bool
*/
private function make_error_code_column_index() {
$error_code_column_exists = $this->column_exists( 'error_code' );
if ( ! $error_code_column_exists ) {
return $this->is_success( false );
}
if ( $this->index_exists( 'error_code_index' ) ) {
return $this->is_success( true );
}
$index_added = $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD INDEX `error_code_index` (`error_code`) " );
return $this->is_success( $index_added );
}
/**
* Adds the submitted_at column
*
* @return bool
*/
protected function add_submitted_at_column() {
$submitted_at_column_exists = $this->column_exists( 'submitted_at' );
$created = true;
if ( ! $submitted_at_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE `{$this->table_name}` ADD COLUMN submitted_at timestamp NULL AFTER last_accessed" );
}
return $this->is_success( $created );
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Frontend;
use WP_Rocket\Engine\Optimization\RUCSS\AbstractAPIClient;
class APIClient extends AbstractAPIClient {
/**
* SaaS main API path.
*
* @var string
*/
protected $request_path = 'rucss-job';
/**
* Calls Central SaaS API.
*
* @param string $url Page url.
* @param array $options Array with options sent to Saas API.
*
* @return array
*/
public function add_to_queue( string $url, array $options ): array {
$args = [
'body' => [
'url' => add_query_arg(
[
'nowprocket' => 1,
'no_optimize' => 1,
],
$url
),
'config' => $options,
],
'timeout' => 5,
];
$sent = $this->handle_post( $args );
if ( ! $sent ) {
return [
'code' => $this->response_code,
'message' => $this->error_message,
];
}
$default = [
'code' => 400,
'message' => 'No message. Defaulted in add_to_queue',
'contents' => [
'jobId' => '0',
'queueName' => '',
],
];
$result = json_decode( $this->response_body, true );
return wp_parse_args( (array) $result, $default );
}
/**
* Get job status from RUCSS queue.
*
* @param string $job_id Job ID.
* @param string $queue_name Queue Name.
* @param bool $is_home Is home or not.
*
* @return array
*/
public function get_queue_job_status( $job_id, $queue_name, $is_home = false ) {
$args = [
'body' => [
'id' => $job_id,
'force_queue' => $queue_name,
'is_home' => $is_home,
],
'timeout' => 5,
];
if ( ! $this->handle_get( $args ) ) {
return [
'code' => $this->response_code,
'message' => $this->error_message,
];
}
$default = [
'code' => 400,
'status' => 'failed',
'message' => 'No message. Defaulted in get_queue_job_status',
'contents' => [
'success' => false,
'shakedCSS' => '',
],
];
$result = json_decode( $this->response_body, true );
return (array) wp_parse_args( ( $result && $result['returnvalue'] ) ? (array) $result['returnvalue'] : [], $default );
}
}
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Frontend;
use WP_Rocket\Engine\Common\Context\ContextInterface;
use WP_Rocket\Engine\Optimization\RUCSS\Context\RUCSSContext;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS;
class Subscriber implements Subscriber_Interface {
/**
* UsedCss instance
*
* @var UsedCSS
*/
private $used_css;
/**
* RUCSS context.
*
* @var ContextInterface
*/
protected $context;
/**
* Instantiate the class
*
* @param UsedCSS $used_css UsedCSS instance.
* @param ContextInterface $context RUCSS context.
*/
public function __construct( UsedCSS $used_css, ContextInterface $context ) {
$this->used_css = $used_css;
$this->context = $context;
}
/**
* Return an array of events that this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_buffer' => [ 'treeshake', 1000 ],
'rocket_disable_preload_fonts' => 'maybe_disable_preload_fonts',
'rocket_first_install_options' => 'on_install',
'wp_rocket_upgrade' => [ 'on_update', 10, 2 ],
];
}
/**
* Apply TreeShaked CSS to the current HTML page.
*
* @param string $html HTML content.
*
* @return string HTML content.
*/
public function treeshake( string $html ): string {
return $this->used_css->treeshake( $html );
}
/**
* Disables the preload fonts if RUCSS is enabled
*
* @since 3.9
*
* @param bool $value Value for the disable preload fonts filter.
*
* @return bool
*/
public function maybe_disable_preload_fonts( $value ): bool {
if ( $this->context->is_allowed() ) {
return true;
}
return $value;
}
/**
* Add option on update.
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function on_update( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.15', '>=' ) ) {
return;
}
$default = 0;
if ( get_transient( 'wp_rocket_no_licence' ) ) {
$default = get_transient( 'wp_rocket_no_licence' );
delete_transient( 'wp_rocket_no_licence' );
}
update_option( 'wp_rocket_no_licence', $default );
}
/**
* Add option on installation.
*
* @param array $options WP Rocket options array.
*
* @return array
*/
public function on_install( $options ) {
update_option( 'wp_rocket_no_licence', 0 );
return $options;
}
}
@@ -0,0 +1,104 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Optimization\RUCSS\Admin\{Database, OptionSubscriber, Settings};
use WP_Rocket\Engine\Optimization\RUCSS\Admin\Subscriber as AdminSubscriber;
use WP_Rocket\Engine\Optimization\RUCSS\Context\RUCSSContext;
use WP_Rocket\Engine\Optimization\RUCSS\Context\RUCSSOptimizeContext;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Filesystem;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Queue;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS as UsedCSSController;
use WP_Rocket\Engine\Optimization\RUCSS\Cron\Subscriber as CronSubscriber;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Queries\UsedCSS as UsedCSSQuery;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Tables\UsedCSS as UsedCSSTable;
use WP_Rocket\Engine\Optimization\RUCSS\Frontend\APIClient;
use WP_Rocket\Engine\Optimization\RUCSS\Frontend\Subscriber as FrontendSubscriber;
/**
* Service provider for the WP Rocket RUCSS
*
* @since 3.9
*/
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 = [
'rucss_settings',
'rucss_database',
'rucss_option_subscriber',
'rucss_admin_subscriber',
'rucss_frontend_api_client',
'rucss_used_css',
'rucss_used_css_query',
'rucss_frontend_subscriber',
'rucss_queue',
'rucss_filesystem',
'rucss_cron_subscriber',
'rucss_used_css_controller',
];
/**
* Registers the option array in the container
*
* @return void
*/
public function register() {
$this->getContainer()->share( 'rucss_usedcss_table', UsedCSSTable::class );
$this->getContainer()->add( 'rucss_database', Database::class )
->addArgument( $this->getContainer()->get( 'rucss_usedcss_table' ) );
$this->getContainer()->add( 'rucss_settings', Settings::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'beacon' ) )
->addArgument( $this->getContainer()->get( 'rucss_usedcss_table' ) );
$this->getContainer()->add( 'rucss_used_css_query', UsedCSSQuery::class );
$this->getContainer()->add( 'rucss_frontend_api_client', APIClient::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$this->getContainer()->add( 'rucss_queue', Queue::class );
$this->getContainer()->add( 'rucss_filesystem', Filesystem::class )
->addArgument( rocket_get_constant( 'WP_ROCKET_USED_CSS_PATH' ) )
->addArgument( rocket_direct_filesystem() );
$this->getContainer()->add( 'rucss_context', RUCSSContext::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'rucss_filesystem' ) );
$this->getContainer()->add( 'rucss_optimize_context', RUCSSOptimizeContext::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$this->getContainer()->add( 'rucss_used_css_controller', UsedCSSController::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'rucss_used_css_query' ) )
->addArgument( $this->getContainer()->get( 'rucss_frontend_api_client' ) )
->addArgument( $this->getContainer()->get( 'rucss_queue' ) )
->addArgument( $this->getContainer()->get( 'dynamic_lists_defaultlists_data_manager' ) )
->addArgument( $this->getContainer()->get( 'rucss_filesystem' ) )
->addArgument( $this->getContainer()->get( 'rucss_context' ) )
->addArgument( $this->getContainer()->get( 'rucss_optimize_context' ) );
$this->getContainer()->share( 'rucss_option_subscriber', OptionSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_settings' ) );
$this->getContainer()->share( 'rucss_admin_subscriber', AdminSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_settings' ) )
->addArgument( $this->getContainer()->get( 'rucss_database' ) )
->addArgument( $this->getContainer()->get( 'rucss_used_css_controller' ) )
->addArgument( $this->getContainer()->get( 'rucss_queue' ) );
$this->getContainer()->share( 'rucss_frontend_subscriber', FrontendSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_used_css_controller' ) )
->addArgument( $this->getContainer()->get( 'rucss_context' ) );
$this->getContainer()->share( 'rucss_cron_subscriber', CronSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_used_css_controller' ) )
->addArgument( $this->getContainer()->get( 'rucss_database' ) );
}
}
@@ -0,0 +1,265 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization;
trait RegexTrait {
/**
* Array of replaced xmp tags
*
* @var array
*/
private $xmp_replace = [];
/**
* Array of replaced html tags.
*
* @var array
*/
private $html_replace = [];
/**
* Array of replaced svg tags
*
* @var array
*/
private $svg_replace = [];
/**
* Finds nodes matching the pattern in the HTML.
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @param string $modifiers Regex modifiers.
*
* @return array
*/
protected function find( string $pattern, string $html, string $modifiers = 'Umsi' ) {
preg_match_all( '/' . $pattern . '/' . $modifiers, $html, $matches, PREG_SET_ORDER );
if ( empty( $matches ) ) {
return [];
}
return $matches;
}
/**
* Hides unwanted blocks from the HTML to be parsed for optimization
*
* @since 3.1.4
*
* @param string $html HTML content.
* @return string
*/
protected function hide_comments( $html ) {
$replace = preg_replace( '#<!--\s*noptimize\s*-->.*?<!--\s*/\s*noptimize\s*-->#is', '', $html );
if ( null === $replace ) {
return $html;
}
$replace = preg_replace( '/<!--(.*)-->/Uis', '', $replace );
if ( null === $replace ) {
return $html;
}
return $replace;
}
/**
* Hides scripts from the HTML to be parsed when removing CSS from it
*
* @since 3.10.2
*
* @param string $html HTML content.
*
* @return string
*/
protected function hide_scripts( $html ) {
$replace = preg_replace( '#<script[^>]*>.*?<\/script\s*>#mis', '', $html );
if ( null === $replace ) {
return $html;
}
return $replace;
}
/**
* Hides <noscript> blocks from the HTML to be parsed.
*
* @param string $html HTML content.
*
* @return string
*/
protected function hide_noscripts( $html ) {
$replace = preg_replace( '#<noscript[^>]*>.*?<\/noscript\s*>#mis', '', $html );
if ( null === $replace ) {
return $html;
}
return $replace;
}
/**
* Replace HTML comments.
*
* @param string $html HTML content.
*
* @return string
*/
protected function replace_html_comments( string $html ): string {
$this->html_replace = [];
$regex = '#<!--.*-->#iUs';
$replaced_html = preg_replace_callback( $regex, [ $this, 'replace_html_comment' ], $html );
if ( empty( $replaced_html ) ) {
return $html;
}
return $replaced_html;
}
/**
* Replace html with comment
*
* @param array $match HTML comment.
* @return string
*/
protected function replace_html_comment( $match ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.matchFound
$key = sprintf( '<!-- %s -->', uniqid( 'WPR_HTML_COMMENT_' ) );
$this->html_replace[ $key ] = $match[0];
return $key;
}
/**
* Restore html with comment
*
* @param string $html HTML content.
* @return string
*/
protected function restore_html_comments( $html ) {
if ( empty( $this->html_replace ) ) {
return $html;
}
return str_replace( array_keys( $this->html_replace ), array_values( $this->html_replace ), $html );
}
/**
* Replace <xmp> tags in the HTML with comment
*
* @since 3.12.3
*
* @param string $html HTML content.
* @return string
*/
protected function replace_xmp_tags( $html ) {
$this->xmp_replace = [];
$regex = '#<xmp.*>.*</xmp>#Uis';
$replaced_html = preg_replace_callback( $regex, [ $this, 'replace_xmp' ], $html );
if ( empty( $replaced_html ) ) {
return $html;
}
return $replaced_html;
}
/**
* Replace <svg> tags in the HTML with comment
*
* @since 3.12.5.3
*
* @param string $html HTML content.
* @return string
*/
protected function replace_svg_tags( $html ) {
$this->svg_replace = [];
$regex = '#<\s*svg.*>.*<\s*\\\\?/\s*svg\s*>#Uis';
$replaced_html = preg_replace_callback( $regex, [ $this, 'replace_svg' ], $html );
if ( empty( $replaced_html ) ) {
return $html;
}
return $replaced_html;
}
/**
* Replace svg with comment
*
* @since 3.12.3
*
* @param array $match svg tag.
* @return string
*/
protected function replace_svg( $match ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.matchFound
$key = sprintf( '<!-- %s -->', uniqid( 'WPR_SVG_' ) );
$this->svg_replace[ $key ] = $match[0];
return $key;
}
/**
* Replace xmp with comment
*
* @since 3.12.3
*
* @param array $match xmp tag.
* @return string
*/
protected function replace_xmp( $match ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.matchFound
$key = sprintf( '<!-- %s -->', uniqid( 'WPR_XMP_' ) );
$this->xmp_replace[ $key ] = $match[0];
return $key;
}
/**
* Restore <svg> tags
*
* @since 3.12.5.3
*
* @param string $html HTML content.
* @return string
*/
protected function restore_svg_tags( $html ) {
if ( empty( $this->svg_replace ) ) {
return $html;
}
return str_replace( array_keys( $this->svg_replace ), array_values( $this->svg_replace ), $html );
}
/**
* Restore <xmp> tags
*
* @since 3.12.3
*
* @param string $html HTML content.
* @return string
*/
protected function restore_xmp_tags( $html ) {
if ( empty( $this->xmp_replace ) ) {
return $html;
}
return str_replace( array_keys( $this->xmp_replace ), array_values( $this->xmp_replace ), $html );
}
/**
* Checks if the page HTML is valid or not.
* Valid here means that it has a closing title tag.
*
* @param string $html Page HTML.
*
* @return bool
*/
private function html_has_title_tag( string $html ) {
return (bool) preg_match( '#</title>#iU', $html );
}
}
@@ -0,0 +1,85 @@
<?php
namespace WP_Rocket\Engine\Optimization;
use WP_Rocket\Buffer\Config;
use WP_Rocket\Engine\Optimization\Buffer\Optimization;
use WP_Rocket\Buffer\Tests;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Optimization\GoogleFonts\Combine;
use WP_Rocket\Engine\Optimization\GoogleFonts\CombineV2;
use WP_Rocket\Engine\Optimization\GoogleFonts\Subscriber;
use WP_Rocket\Engine\Optimization\Buffer\Subscriber as BufferSubscriber;
/**
* Service provider for the WP Rocket optimizations
*
* @since 3.3
* @since 3.6 Renamed and moved into this module.
*/
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 = [
'config',
'tests',
'buffer_optimization',
'buffer_subscriber',
'cache_dynamic_resource',
'ie_conditionals_subscriber',
'optimize_google_fonts',
'optimize_google_fonts_v2',
'combine_google_fonts_subscriber',
'minify_css_subscriber',
'minify_js_subscriber',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$options = $this->getContainer()->get( 'options' );
$filesystem = rocket_direct_filesystem();
$this->getContainer()->add( 'config', Config::class )
->addArgument( [ 'config_dir_path' => rocket_get_constant( 'WP_ROCKET_CONFIG_PATH' ) ] );
$this->getContainer()->add( 'tests', Tests::class )
->addArgument( $this->getContainer()->get( 'config' ) );
$this->getContainer()->add( 'buffer_optimization', Optimization::class )
->addArgument( $this->getContainer()->get( 'tests' ) );
$this->getContainer()->share( 'buffer_subscriber', BufferSubscriber::class )
->addArgument( $this->getContainer()->get( 'buffer_optimization' ) )
->addTag( 'front_subscriber' );
$this->getContainer()->share( 'cache_dynamic_resource', CacheDynamicResource::class )
->addArgument( $options )
->addArgument( WP_ROCKET_CACHE_BUSTING_PATH )
->addArgument( WP_ROCKET_CACHE_BUSTING_URL )
->addTag( 'front_subscriber' );
$this->getContainer()->add( 'optimize_google_fonts', Combine::class );
$this->getContainer()->add( 'optimize_google_fonts_v2', CombineV2::class );
$this->getContainer()->share( 'combine_google_fonts_subscriber', Subscriber::class )
->addArgument( $this->getContainer()->get( 'optimize_google_fonts' ) )
->addArgument( $this->getContainer()->get( 'optimize_google_fonts_v2' ) )
->addArgument( $options )
->addTag( 'front_subscriber' );
$this->getContainer()->share( 'minify_css_subscriber', Minify\CSS\Subscriber::class )
->addArgument( $options )
->addArgument( $filesystem )
->addTag( 'front_subscriber' );
$this->getContainer()->share( 'minify_js_subscriber', Minify\JS\Subscriber::class )
->addArgument( $options )
->addArgument( $filesystem )
->addTag( 'front_subscriber' );
$this->getContainer()->share( 'ie_conditionals_subscriber', IEConditionalSubscriber::class )
->addTag( 'front_subscriber' );
}
}
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization;
trait UrlTrait {
/**
* 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['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( $url, $host ) ) {
return false;
}
}
return true;
}
return false;
}
/**
* Gets the file path from an URL
*
* @param string $url File URL.
* @return bool|string
*/
protected function get_file_path( $url ) {
$url = $this->normalize_fullurl( $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 );
}
/**
* Normalize relative url to full url.
*
* @param string $url Url to be normalized.
* @param bool $remove_query Remove Query string or not.
*
* @return string Normalized url.
*/
public function normalize_fullurl( string $url, bool $remove_query = true ) {
$url = htmlspecialchars_decode( $url );
$parsed_url = wp_parse_url( $url );
if ( $remove_query && ! empty( $parsed_url['query'] ) ) {
$url = str_replace( '?' . $parsed_url['query'], '', $url );
}
if ( empty( $parsed_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 rocket_add_url_protocol( $url );
}
/**
* Gets content of a file
*
* @param string $file File path.
* @return string
*/
protected function get_file_content( $file ) {
if ( empty( $file ) ) {
return false;
}
return rocket_direct_filesystem()->get_contents( $file );
}
}