This commit is contained in:
2026-10-12 20:35:25 -06:00
parent bef9999f6a
commit 225515570a
963 changed files with 273176 additions and 0 deletions
@@ -0,0 +1,63 @@
<?php
namespace WP_Rocket\Addon\Busting;
use WP_Rocket\deprecated\DeprecatedClassTrait;
use WP_Rocket\Addon\GoogleTracking\GoogleAnalytics;
use WP_Rocket\Addon\GoogleTracking\GoogleTagManager;
use WP_Rocket\Busting\Facebook_Pickles;
use WP_Rocket\Busting\Facebook_SDK;
/**
* Busting classes Factory
*
* @since 3.9 deprecated.
* @since 3.6.2
*/
class BustingFactory {
use DeprecatedClassTrait;
/**
* Base cache busting filepath.
*
* @var string
*/
private $busting_path;
/**
* Base cache busting URL.
*
* @var string
*/
private $busting_url;
/**
* Constructor
*
* @param string $busting_path Base cache busting filepath.
* @param string $busting_url Base cache busting URL.
*/
public function __construct( $busting_path, $busting_url ) {
self::deprecated_class( '3.9' );
$this->busting_path = $busting_path;
$this->busting_url = $busting_url;
}
/**
* Creator method
*
* @param string $type Type of busting class to create.
* @return Busting_Interface
*/
public function type( $type ) {
switch ( $type ) {
case 'fbpix':
return new Facebook_Pickles( $this->busting_path, $this->busting_url );
case 'fbsdk':
return new Facebook_SDK( $this->busting_path, $this->busting_url );
case 'ga':
return new GoogleAnalytics( $this->busting_path, $this->busting_url );
case 'gtm':
return new GoogleTagManager( $this->busting_path, $this->busting_url, new GoogleAnalytics( $this->busting_path, $this->busting_url ) );
}
}
}
@@ -0,0 +1,478 @@
<?php
namespace WP_Rocket\Addon\Busting;
use WP_Rocket\Logger\Logger;
trait FileBustingTrait {
/**
* Saves the content of the URL to bust to the busting file if it doesn't exist yet.
*
* @since 3.2.4
* @access public
*
* @param string $url URL to get the content from.
* @return bool
*/
public function save( $url ) {
if ( $this->get_busting_version() ) {
// We have a local copy.
Logger::debug(
'Found local file.',
[
self::LOGGER_CONTEXT,
'path' => $this->get_busting_path(),
]
);
return true;
}
if ( $this->refresh_save( $url ) ) {
// We downloaded a fresh copy.
Logger::debug(
'New copy downloaded.',
[
self::LOGGER_CONTEXT,
'path' => $this->get_busting_path(),
]
);
return true;
}
return false;
}
/**
* Deletes the busting file.
*
* @since 3.1
* @since 3.2.4 Handle versioning.
* @access public
* @author Remy Perona
* @author Grégory Viguier
*
* @return bool True on success. False on failure.
*/
public function delete() {
$files = $this->get_all_files();
if ( false === $files ) {
// Error.
return false;
}
$this->file_version = null;
if ( ! $files ) {
// No local files yet.
return true;
}
return $this->delete_files( array_keys( $files ) );
}
/** ----------------------------------------------------------------------------------------- */
/** LOCAL FILE ============================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Get the version of the current busting file.
*
* @since 3.2.4
* @access protected
* @author Grégory Viguier
*
* @return string|bool Version of the file. False if the file does not exist.
*/
protected function get_busting_version() {
if ( ! empty( $this->file_version ) ) {
return $this->file_version;
}
$files = $this->get_all_files();
if ( ! $files ) {
// Error or no local files yet.
return false;
}
// Since we're not supposed to have several files, return the first one.
$this->file_version = reset( $files );
return $this->file_version;
}
/**
* Get all cached files in the directory.
* In a perfect world, there should be only one.
*
* @since 3.2.4
* @access private
*
* @return bool|array A list of file names (as array keys) and versions (as array values). False on failure.
*/
private function get_all_files() {
$dir_path = rtrim( $this->busting_path, '\\/' );
if ( ! $this->filesystem->exists( $dir_path ) ) {
return [];
}
if ( ! $this->filesystem->is_readable( $dir_path ) ) {
Logger::error(
'Directory is not readable.',
[
self::LOGGER_CONTEXT,
'path' => $dir_path,
]
);
return false;
}
$pattern = '/' . sprintf(
$this->escape_file_name( $this->filename_pattern ),
'([a-f0-9]{32}|local)'
) . '/';
$entries = _rocket_get_dir_files_by_regex( $dir_path, $pattern );
$list = [];
foreach ( $entries as $entry ) {
$filename = $entry->getFilename();
preg_match( $pattern, $filename, $file_details_match );
if ( ! empty( $file_details_match[1] ) ) {
$list[ $filename ] = $file_details_match[1];
}
}
return $list;
}
/**
* Get the final URL for the current cache busting file.
*
* @since 3.2.4
* @access protected
*
* @return string|bool URL of the file. False if the file does not exist.
*/
public function get_busting_url() {
return $this->get_busting_file_url( $this->get_busting_version() );
}
/**
* Get the path to the current cache busting file.
*
* @since 3.2.4
* @access protected
* @author Grégory Viguier
*
* @return string|bool URL of the file. False if the file does not exist.
*/
protected function get_busting_path() {
return $this->get_busting_file_path( $this->get_busting_version() );
}
/**
* Get the final URL for a cache busting file.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param string $version The file version.
* @return string|bool URL of the file with this version. False if no versions are provided.
*/
private function get_busting_file_url( $version ) {
if ( ! $version ) {
return false;
}
$filename = $this->get_busting_file_name( $version );
// This filter is documented in inc/functions/minify.php.
return apply_filters( 'rocket_js_url', $this->busting_url . $filename );
}
/**
* Get the local file name.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param string $version The file version.
* @return string|bool The name of the file with this version. False if no versions are provided.
*/
private function get_busting_file_name( $version ) {
if ( ! $version ) {
return false;
}
return sprintf( $this->filename_pattern, $version );
}
/**
* Get the local file path.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param string $version The file version.
* @return string|bool Path to the file with this version. False if no versions are provided.
*/
private function get_busting_file_path( $version ) {
if ( ! $version ) {
return false;
}
return $this->busting_path . $this->get_busting_file_name( $version );
}
/**
* Escape a file name, to be used in a regex pattern (delimiter is `/`).
* `%s` conversion specifications are protected.
*
* @since 3.2.4
* @access private
*
* @param string $filename_pattern The file name.
* @return string
*/
private function escape_file_name( $filename_pattern ) {
return preg_quote( $filename_pattern, '/' );
}
/**
* Delete busting files.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param array $files A list of file names.
* @return bool True if files have been deleted (or no files have been provided). False on failure.
*/
private function delete_files( $files ) {
if ( ! $files ) {
// ¯\_(ツ)_/¯
return true;
}
$has_deleted = false;
$error_paths = [];
foreach ( $files as $file_name ) {
if ( ! $this->filesystem->delete( $this->busting_path . $file_name, false, 'f' ) ) {
$error_paths[] = $this->busting_path . $file_name;
} else {
$has_deleted = true;
}
}
if ( $error_paths ) {
// Group all deletion errors into one log.
Logger::error(
'Local file(s) could not be deleted.',
[
self::LOGGER_CONTEXT,
'paths' => $error_paths,
]
);
}
return $has_deleted;
}
/** ----------------------------------------------------------------------------------------- */
/** UPDATE THE LOCAL FILE =================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Add new contents to a file. If the file doesn't exist, it is created.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param string $file_path Path to the file to update.
* @param string $file_contents New contents.
* @return string|bool The file contents on success. False on failure.
*/
private function update_file_contents( $file_path, $file_contents ) {
if ( ! $this->is_busting_dir_writable() ) {
return false;
}
if ( ! rocket_put_content( $file_path, $file_contents ) ) {
Logger::error(
'Contents could not be written into file.',
[
self::LOGGER_CONTEXT,
'path' => $file_path,
]
);
return false;
}
return $file_contents;
}
/**
* Tell if the directory containing the busting file is writable.
*
* @since 3.2
* @access private
* @author Grégory Viguier
*
* @return bool
*/
private function is_busting_dir_writable() {
if ( ! $this->filesystem->exists( $this->busting_path ) ) {
rocket_mkdir_p( $this->busting_path );
}
if ( ! $this->filesystem->is_writable( $this->busting_path ) ) {
Logger::error(
'Directory is not writable.',
[
self::LOGGER_CONTEXT,
'paths' => $this->busting_path,
]
);
return false;
}
return true;
}
/** ----------------------------------------------------------------------------------------- */
/** GET LOCAL/REMOTE CONTENTS =============================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Get a file contents. If the file doesn't exist, new contents are fetched remotely.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param string $file_path Path to the file.
* @param string $file_url URL to the remote file.
* @return string|bool The contents on success, false on failure.
*/
private function get_file_or_remote_contents( $file_path, $file_url ) {
$content = $this->get_file_contents( $file_path );
if ( $content ) {
// We have a local file.
return $content;
}
return $this->get_remote_contents( $file_url );
}
/**
* Get a file contents.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param string $file_path Path to the file.
* @return string|bool The contents on success, false on failure.
*/
private function get_file_contents( $file_path ) {
if ( ! $this->filesystem->exists( $file_path ) ) {
Logger::error(
'Local file does not exist.',
[
self::LOGGER_CONTEXT,
'path' => $file_path,
]
);
return false;
}
if ( ! $this->filesystem->is_readable( $file_path ) ) {
Logger::error(
'Local file is not readable.',
[
self::LOGGER_CONTEXT,
'path' => $file_path,
]
);
return false;
}
$content = $this->filesystem->get_contents( $file_path );
if ( ! $content ) {
Logger::error(
'Local file is empty.',
[
self::LOGGER_CONTEXT,
'path' => $file_path,
]
);
return false;
}
return $content;
}
/**
* Get the contents of a URL.
*
* @since 3.2.4
* @access private
* @author Grégory Viguier
*
* @param string $url The URL to request.
* @return string|bool The contents on success. False on failure.
*/
private function get_remote_contents( $url ) {
try {
$response = wp_remote_get( $url );
} catch ( Exception $e ) {
Logger::error(
'Remote file could not be fetched.',
[
self::LOGGER_CONTEXT,
'url' => $url,
'response' => $e->getMessage(),
]
);
return false;
}
if ( is_wp_error( $response ) ) {
Logger::error(
'Remote file could not be fetched.',
[
self::LOGGER_CONTEXT,
'url' => $url,
'response' => $response->get_error_message(),
]
);
return false;
}
$contents = wp_remote_retrieve_body( $response );
if ( ! $contents ) {
Logger::error(
'Remote file could not be fetched.',
[
self::LOGGER_CONTEXT,
'url' => $url,
'response' => $response,
]
);
return false;
}
return $contents;
}
}
@@ -0,0 +1,197 @@
<?php
namespace WP_Rocket\Addon\FacebookTracking;
use WP_Rocket\deprecated\DeprecatedClassTrait;
use WP_Rocket\Addon\Busting\BustingFactory;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Admin\Options_Data as Options;
/**
* Event subscriber for Facebook tracking cache busting.
*
* @since 3.9 deprecated.
* @since 3.2
*/
class Subscriber implements Subscriber_Interface {
use DeprecatedClassTrait;
/**
* Name of the cron.
*
* @var string
* @since 3.2
*/
const CRON_NAME = 'rocket_facebook_tracking_cache_update';
/**
* Instance of the Busting Factory class.
*
* @var BustingFactory
* @since 3.2
*/
private $busting_factory;
/**
* Instance of the Option_Data class.
*
* @var Options
* @since 3.2
*/
private $options;
/**
* Constructor.
*
* @since 3.2
*
* @param BustingFactory $busting_factory Instance of the Busting Factory class.
* @param Options $options Instance of the Options_Data class.
*/
public function __construct( BustingFactory $busting_factory, Options $options ) {
self::deprecated_class( '3.9' );
$this->busting_factory = $busting_factory;
$this->options = $options;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.2
*
* @return array
*/
public static function get_subscribed_events() {
$events = [
'cron_schedules' => 'add_schedule',
'init' => 'schedule_cache_update',
self::CRON_NAME => 'update_cache',
'rocket_purge_cache' => 'delete_cache',
'rocket_buffer' => 'cache_busting_facebook_tracking',
];
return $events;
}
/**
* Add weekly interval to cron schedules.
*
* @since 3.2
*
* @param array $schedules An array of intervals used by cron jobs.
* @return array
*/
public function add_schedule( $schedules ) {
if ( ! $this->is_busting_active() ) {
return $schedules;
}
$schedules['weekly'] = [
'interval' => 604800,
'display' => __( 'weekly', 'rocket' ),
];
return $schedules;
}
/**
* (Un)Schedule the auto-update of the cache busting files.
*
* @since 3.2
*/
public function schedule_cache_update() {
$scheduled = wp_next_scheduled( self::CRON_NAME );
if ( ! $this->is_busting_active() ) {
if ( $scheduled ) {
wp_clear_scheduled_hook( self::CRON_NAME );
}
return;
}
if ( ! $scheduled ) {
wp_schedule_event( time(), 'weekly', self::CRON_NAME );
}
}
/**
* Update the Facebook Pixel cache busting files.
*
* @since 3.2
*
* @return bool
*/
public function update_cache() {
if ( ! $this->is_busting_active() ) {
return false;
}
$html = $this->busting_factory->type( 'fbsdk' )->refresh();
return $this->busting_factory->type( 'fbpix' )->refresh_all();
}
/**
* Delete Facebook Pixel cache busting files.
*
* @since 3.2
* @since 3.6 Argument replacement.
*
* @param string $type Type of cache clearance: 'all', 'post', 'term', 'user', 'url'.
* @return bool
*/
public function delete_cache( $type ) {
if ( 'all' !== $type || ! $this->is_busting_active() ) {
return false;
}
$html = $this->busting_factory->type( 'fbsdk' )->delete();
return $this->busting_factory->type( 'fbpix' )->delete_all();
}
/**
* Process the cache busting on the HTML contents.
*
* @since 3.2
*
* @param string $html HTML contents.
* @return string
*/
public function cache_busting_facebook_tracking( $html ) {
if ( ! $this->is_allowed() ) {
return $html;
}
$html = $this->busting_factory->type( 'fbsdk' )->replace_url( $html );
return $this->busting_factory->type( 'fbpix' )->replace_url( $html );
}
/**
* Tell if the cache busting should happen.
*
* @since 3.2
*
* @return bool
*/
private function is_allowed() {
if ( defined( 'DONOTROCKETOPTIMIZE' ) && DONOTROCKETOPTIMIZE ) {
return false;
}
return $this->is_busting_active();
}
/**
* Tell if the cache busting option is active.
*
* @since 3.2
*
* @return bool
*/
private function is_busting_active() {
return (bool) $this->options->get( 'facebook_pixel_cache', 0 );
}
}
@@ -0,0 +1,250 @@
<?php
namespace WP_Rocket\Addon\GoogleTracking;
use WP_Rocket\deprecated\DeprecatedClassTrait;
use WP_Rocket\Addon\Busting\FileBustingTrait;
use WP_Rocket\Busting\Abstract_Busting;
use WP_Rocket\Logger\Logger;
/**
* Manages the cache busting of the Google Analytics file.
*
* @since 3.9 deprecated
* @since 3.1
*/
class GoogleAnalytics extends Abstract_Busting {
use FileBustingTrait;
use DeprecatedClassTrait;
/**
* Context used for the logger.
*
* @var string
* @since 3.2.4
* @author Grégory Viguier
*/
const LOGGER_CONTEXT = 'gg analytics';
/**
* Google Analytics URL.
*
* @var string
* @since 3.1
* @access protected
* @author Remy Perona
*/
protected $url = 'https://www.google-analytics.com/analytics.js';
/**
* File name (local).
* %s is a "version": a md5 hash of the file contents.
*
* @var string
* @since 3.2.4
* @access protected
* @author Grégory Viguier
*/
protected $filename_pattern = 'ga-%s.js';
/**
* Current file version (local): a md5 hash of the file contents.
*
* @var string
* @since 3.2.4
* @access protected
* @author Grégory Viguier
*/
protected $file_version;
/**
* Flag to track the replacement.
*
* @var bool
* @since 3.1
* @access protected
* @author Remy Perona
*/
protected $is_replaced = false;
/**
* Filesystem object.
*
* @var object
* @since 3.2.4
* @access protected
* @author Grégory Viguier
*/
protected $filesystem = false;
/**
* Constructor.
*
* @since 3.1
* @access public
* @author Remy Perona
*
* @param string $busting_path Path to the busting directory.
* @param string $busting_url URL of the busting directory.
*/
public function __construct( $busting_path, $busting_url ) {
self::deprecated_class( '3.9' );
$this->busting_path = $busting_path . 'google-tracking/';
$this->busting_url = $busting_url . 'google-tracking/';
$this->filesystem = rocket_direct_filesystem();
}
/** ----------------------------------------------------------------------------------------- */
/** PUBLIC METHODS ========================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Performs the replacement process.
*
* @since 3.1
* @access public
* @author Remy Perona
*
* @param string $html HTML content.
* @return string
*/
public function replace_url( $html ) {
$this->is_replaced = false;
$tag = $this->find( '<script\s*(?<attr>[^>]*)?>(?<content>.*)?<\/script>', $html );
if ( ! $tag ) {
return $html;
}
Logger::info(
'GOOGLE ANALYTICS CACHING PROCESS STARTED.',
[
self::LOGGER_CONTEXT,
'tag' => $tag,
]
);
if ( ! $this->save( $this->url ) ) {
return $html;
}
$replace_tag = preg_replace( '/(?:https?:)?\/\/www\.google-analytics\.com\/analytics\.js/i', $this->get_busting_url(), $tag );
$html = str_replace( $tag, $replace_tag, $html );
$this->is_replaced = true;
Logger::info(
'Google Analytics caching process succeeded.',
[
self::LOGGER_CONTEXT,
'file' => $this->get_busting_path(),
]
);
return $html;
}
/**
* Tell if the replacement was sucessful or not.
*
* @since 3.1
* @access public
* @author Remy Perona
*
* @return bool
*/
public function is_replaced() {
return $this->is_replaced;
}
/**
* Saves the content of the URL to cache to the busting file.
*
* @since 3.2.4
* @access public
* @author Grégory Viguier
*
* @param string $url URL to get the content from.
* @return bool
*/
public function refresh_save( $url ) {
// Before doing anything, make sure the busting file can be created.
if ( ! $this->is_busting_dir_writable() ) {
return false;
}
// Get remote content.
$content = $this->get_remote_contents( $url );
if ( ! $content ) {
// Could not get the remote contents.
return false;
}
$version = md5( $content );
$path = $this->get_busting_file_path( $version );
return $this->update_file_contents( $path, $content );
}
/** ----------------------------------------------------------------------------------------- */
/** REMOTE FILE ============================================================================= */
/** ----------------------------------------------------------------------------------------- */
/**
* Get the Google Analytics URL.
*
* @since 3.1
* @access public
* @author Remy Perona
*
* @return string
*/
public function get_url() {
return $this->url;
}
/** ----------------------------------------------------------------------------------------- */
/** VARIOUS INTERNAL TOOLS ================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Searches for element(s) in the DOM.
*
* @since 3.1
* @access public
* @author Remy Perona
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @return string
*/
protected function find( $pattern, $html ) {
preg_match_all( '/' . $pattern . '/si', $html, $all_matches, PREG_SET_ORDER );
$matches = array_map(
function( $match ) {
if (
! preg_match( '/src\s*=\s*[\'"]\s*(?:https?:)?\/\/www\.google-analytics\.com\/analytics\.js\s*[\'"]/i', $match['attr'] . $match['content'] )
&&
false === strpos( $match['content'], 'GoogleAnalyticsObject' )
) {
return;
}
return $match[0];
},
$all_matches
);
$matches = array_values( array_filter( $matches ) );
if ( ! $matches ) {
return false;
}
return $matches[0];
}
}
@@ -0,0 +1,205 @@
<?php
namespace WP_Rocket\Addon\GoogleTracking;
use WP_Rocket\deprecated\DeprecatedClassTrait;
use WP_Rocket\Addon\Busting\FileBustingTrait;
use WP_Rocket\Logger\Logger;
use WP_Rocket\Busting\Abstract_Busting;
use WP_Filesystem_Direct;
/**
* Manages the cache busting of the Google Tag Manager file
*
* @since 3.9 deprecated.
* @since 3.1
*/
class GoogleTagManager extends Abstract_Busting {
use FileBustingTrait;
use DeprecatedClassTrait;
/**
* Context used for the logger.
*
* @var string
* @since 3.2.4
*/
const LOGGER_CONTEXT = 'gg tag manager';
/**
* File name (local).
* %s is a "version": a md5 hash of the file contents.
*
* @var string
* @since 3.2.4
* @access protected
*/
protected $filename_pattern = 'gtm-%s.js';
/**
* Current file version (local): a md5 hash of the file contents.
*
* @var string
* @since 3.2.4
* @access protected
*/
protected $file_version;
/**
* Filesystem object.
*
* @var object
* @since 3.2.4
* @access protected
*/
protected $filesystem = false;
/**
* Google Analytics object.
*
* @var object
* @since 3.2.4
* @access protected
*/
protected $ga_busting = false;
/**
* Constructor.
*
* @since 3.1
* @access public
*
* @param string $busting_path Path to the busting directory.
* @param string $busting_url URL of the busting directory.
* @param GoogleAnalytics $ga_busting A GoogleAnalytics instance.
* @param WP_Filesystem_Direct $filesystem Instance of the filesystem handler.
*/
public function __construct( $busting_path, $busting_url, GoogleAnalytics $ga_busting, $filesystem = null ) {
self::deprecated_class( '3.9' );
$blog_id = get_current_blog_id();
$this->busting_path = $busting_path . $blog_id . '/';
$this->busting_url = $busting_url . $blog_id . '/';
$this->ga_busting = $ga_busting;
$this->filesystem = is_null( $filesystem ) ? rocket_direct_filesystem() : $filesystem;
}
/** ----------------------------------------------------------------------------------------- */
/** PUBLIC METHODS ========================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Performs the replacement process.
*
* @since 3.1
* @access public
*
* @param string $html HTML content.
* @return string
*/
public function replace_url( $html ) {
$script = $this->find( '<script(\s+[^>]+)?\s+src\s*=\s*[\'"]\s*?((?:https?:)?\/\/www\.googletagmanager\.com(?:.+)?)\s*?[\'"]([^>]+)?\/?>', $html );
if ( ! $script ) {
return $html;
}
// replace relative protocol // with full https://.
$gtm_url = preg_replace( '/^\/\//', 'https://', $script[2] );
Logger::info(
'GOOGLE TAG MANAGER CACHING PROCESS STARTED.',
[
self::LOGGER_CONTEXT,
'tag' => $script,
]
);
if ( ! $this->save( $gtm_url ) ) {
return $html;
}
$replace_script = str_replace( $script[2], $this->get_busting_url(), $script[0] );
$replace_script = str_replace( '<script', '<script data-no-minify="1"', $replace_script );
$html = str_replace( $script[0], $replace_script, $html );
Logger::info(
'Google Tag Manager caching process succeeded.',
[
self::LOGGER_CONTEXT,
'file' => $this->get_busting_path(),
]
);
return $html;
}
/**
* Saves the content of the URL to cache to the busting file.
*
* @since 3.2
* @access public
*
* @param string $url URL to get the content from.
* @return bool
*/
public function refresh_save( $url ) {
// Before doing anything, make sure the busting file can be created.
if ( ! $this->is_busting_dir_writable() ) {
return false;
}
// Get remote content.
$content = $this->get_remote_contents( $url );
if ( ! $content ) {
// Could not get the remote contents.
return false;
}
$version = md5( $content );
$path = $this->get_busting_file_path( $version );
$content = $this->replace_ga_url( $content );
return $this->update_file_contents( $path, $content );
}
/** ----------------------------------------------------------------------------------------- */
/** VARIOUS INTERNAL TOOLS ================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Searches for element(s) in the DOM.
*
* @since 3.1
* @access public
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @return string
*/
protected function find( $pattern, $html ) {
preg_match_all( '/' . $pattern . '/Umsi', $html, $matches, PREG_SET_ORDER );
if ( empty( $matches ) ) {
return false;
}
return $matches[0];
}
/**
* Replaces the Google Analytics URL by the local copy inside the gtm-local.js file content
*
* @since 3.1
*
* @param string $content JavaScript content.
* @return string
*/
protected function replace_ga_url( $content ) {
if ( ! $this->ga_busting->save( $this->ga_busting->get_url() ) ) {
return $content;
}
return str_replace( $this->ga_busting->get_url(), $this->ga_busting->get_busting_url(), $content );
}
}
@@ -0,0 +1,187 @@
<?php
namespace WP_Rocket\Addon\GoogleTracking;
use WP_Rocket\deprecated\DeprecatedClassTrait;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Addon\Busting\BustingFactory;
use WP_Rocket\Admin\Options_Data as Options;
/**
* Event subscriber for Google tracking cache busting
*
* @since 3.9 deprecated.
* @since 3.1
*/
class Subscriber implements Subscriber_Interface {
use DeprecatedClassTrait;
/**
* Instance of the Busting Factory class
*
* @var BustingFactory
*/
private $busting_factory;
/**
* Instance of the Option_Data class
*
* @var Options
*/
private $options;
/**
* Constructor
*
* @param BustingFactory $busting_factory Instance of the Busting Factory class.
* @param Options $options Instance of the Option_Data class.
*/
public function __construct( BustingFactory $busting_factory, Options $options ) {
self::deprecated_class( '3.9' );
$this->busting_factory = $busting_factory;
$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() {
$events = [
'cron_schedules' => 'add_schedule',
'init' => 'schedule_tracking_cache_update',
'rocket_google_tracking_cache_update' => 'update_tracking_cache',
'rocket_purge_cache' => 'delete_tracking_cache',
'rocket_buffer' => 'cache_busting_google_tracking',
];
return $events;
}
/**
* Processes the cache busting on the HTML content
*
* Google Analytics replacement is performed first, and if no replacement occured, Google Tag Manager replacement is performed.
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function cache_busting_google_tracking( $html ) {
if ( ! $this->is_allowed() ) {
return $html;
}
$processor = $this->busting_factory->type( 'ga' );
$html = $processor->replace_url( $html );
$processor = $this->busting_factory->type( 'gtm' );
$html = $processor->replace_url( $html );
return $html;
}
/**
* Schedules the auto-update of Google Analytics cache busting file
*
* @since 3.1
*
* @return void
*/
public function schedule_tracking_cache_update() {
if ( ! $this->is_busting_active() ) {
return;
}
if ( ! wp_next_scheduled( 'rocket_google_tracking_cache_update' ) ) {
wp_schedule_event( time(), 'weekly', 'rocket_google_tracking_cache_update' );
}
}
/**
* Updates Google Analytics cache busting file
*
* @since 3.1
*
* @return bool
*/
public function update_tracking_cache() {
if ( ! $this->is_busting_active() ) {
return false;
}
$processor = $this->busting_factory->type( 'ga' );
return $processor->refresh_save( $processor->get_url() );
}
/**
* Adds weekly interval to cron schedules
*
* @since 3.1
*
* @param Array $schedules An array of intervals used by cron jobs.
* @return Array
*/
public function add_schedule( $schedules ) {
if ( ! $this->is_busting_active() ) {
return $schedules;
}
$schedules['weekly'] = [
'interval' => 604800,
'display' => __( 'weekly', 'rocket' ),
];
return $schedules;
}
/**
* Deletes the GA busting file.
*
* @since 3.1
* @since 3.6 Argument replacement.
*
* @param string $type Type of cache clearance: 'all', 'post', 'term', 'user', 'url'.
* @return bool
*/
public function delete_tracking_cache( $type ) {
if ( 'all' !== $type || ! $this->is_busting_active() ) {
return false;
}
$this->busting_factory->type( 'gtm' )->delete();
return $this->busting_factory->type( 'ga' )->delete();
}
/**
* Checks if the cache busting should happen
*
* @since 3.1
*
* @return boolean
*/
private function is_allowed() {
if ( rocket_get_constant( 'DONOTROCKETOPTIMIZE' ) ) {
return false;
}
return $this->is_busting_active();
}
/**
* Tell if the cache busting option is active.
*
* @since 3.6
*
* @return bool
*/
private function is_busting_active() {
return (bool) $this->options->get( 'google_analytics_cache', 0 );
}
}