Subir proyecto

This commit is contained in:
Gabriel
2026-10-08 10:39:09 -06:00
commit 3a971d1d0b
8344 changed files with 2765102 additions and 0 deletions
@@ -0,0 +1,269 @@
<?php
namespace WP_Rocket\Engine\Cache;
use WP_Filesystem_Direct;
use WP_Rocket\Event_Management\Event_Manager;
use WP_Rocket\Event_Management\Event_Manager_Aware_Subscriber_Interface;
/**
* Subscriber for the cache admin events
*
* @since 3.5.5
*/
class AdminSubscriber implements Event_Manager_Aware_Subscriber_Interface {
/**
* Event Manager instance
*
* @var Event_Manager;
*/
protected $event_manager;
/**
* AdvancedCache instance
*
* @var AdvancedCache
*/
private $advanced_cache;
/**
* WPCache instance
*
* @var WPCache
*/
private $wp_cache;
/**
* WordPress filesystem.
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Instantiate the class
*
* @param AdvancedCache $advanced_cache AdvancedCache instance.
* @param WPCache $wp_cache WPCache instance.
* @param WP_Filesystem_Direct|null $filesystem WordPress filesystem.
*/
public function __construct( AdvancedCache $advanced_cache, WPCache $wp_cache, $filesystem = null ) {
$this->advanced_cache = $advanced_cache;
$this->wp_cache = $wp_cache;
$this->filesystem = ! empty( $filesystem ) ? $filesystem : rocket_direct_filesystem();
}
/**
* Returns an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
$slug = rocket_get_constant( 'WP_ROCKET_SLUG' );
return [
'admin_init' => [
[ 'register_terms_row_action' ],
[ 'maybe_set_wp_cache' ],
],
'admin_notices' => [
[ 'notice_advanced_cache_permissions' ],
[ 'notice_wp_config_permissions' ],
],
"update_option_{$slug}" => [ 'maybe_set_wp_cache', 12 ],
'site_status_tests' => 'add_wp_cache_status_test',
'wp_rocket_upgrade' => [ 'on_update', 10, 2 ],
'rocket_domain_changed' => [
[ 'regenerate_configs' ],
[ 'delete_old_configs' ],
[ 'clear_cache', 10, 2 ],
],
];
}
/**
* Sets the event manager for the subscriber.
*
* @param Event_Manager $event_manager Event Manager instance.
*/
public function set_event_manager( Event_Manager $event_manager ) {
$this->event_manager = $event_manager;
}
/**
* Registers the action for each public taxonomy
*
* @since 3.5.5
*
* @return void
*/
public function register_terms_row_action() {
$taxonomies = get_taxonomies(
[
'public' => true,
'publicly_queryable' => true,
]
);
foreach ( $taxonomies as $taxonomy ) {
$this->event_manager->add_callback( "{$taxonomy}_row_actions", [ $this, 'add_purge_term_link' ], 10, 2 );
}
}
/**
* Adds a link "Purge this cache" in the terms list table
*
* @param array $actions An array of action links to be displayed.
* @param WP_Term $term Term object.
*
* @return array
*/
public function add_purge_term_link( $actions, $term ) {
if ( ! current_user_can( 'rocket_purge_terms' ) ) {
return $actions;
}
$url = wp_nonce_url(
admin_url( "admin-post.php?action=purge_cache&type=term-{$term->term_id}&taxonomy={$term->taxonomy}" ),
"purge_cache_term-{$term->term_id}"
);
$actions['rocket_purge'] = sprintf(
'<a href="%1$s">%2$s</a>',
$url,
__( 'Clear this cache', 'rocket' )
);
return $actions;
}
/**
* Displays the notice for advanced-cache.php permissions
*
* @since 3.6
*
* @return void
*/
public function notice_advanced_cache_permissions() {
$this->advanced_cache->notice_permissions();
}
/**
* Set WP_CACHE constant to true if needed
*
* @since 3.6.1
*
* @return void
*/
public function maybe_set_wp_cache() {
$this->wp_cache->maybe_set_wp_cache();
}
/**
* Displays the notice for wp-config.php permissions
*
* @since 3.6.1
*
* @return void
*/
public function notice_wp_config_permissions() {
$this->wp_cache->notice_wp_config_permissions();
}
/**
* Adds a Site Health check for the WP_CACHE constant value
*
* @since 3.6.1
*
* @param array $tests An array of tests to perform.
* @return array
*/
public function add_wp_cache_status_test( $tests ) {
return $this->wp_cache->add_wp_cache_status_test( $tests );
}
/**
* Regenerate configs.
*
* @return void
*/
public function regenerate_configs() {
rocket_generate_advanced_cache_file();
flush_rocket_htaccess();
rocket_generate_config_file();
}
/**
* Delete old config files.
*
* @return void
*/
public function delete_old_configs() {
$configs = [];
if ( is_multisite() ) {
foreach ( get_sites( [ 'fields' => 'ids' ] ) as $site_id ) {
switch_to_blog( $site_id );
$configs[] = $this->generate_config_path();
restore_current_blog();
}
} else {
$configs[] = $this->generate_config_path();
}
$contents = $this->filesystem->dirlist( WP_ROCKET_CONFIG_PATH );
foreach ( $contents as $content ) {
$content = WP_ROCKET_CONFIG_PATH . $content['name'];
if ( ! preg_match( '#\.php$#', $content ) || ! $this->filesystem->is_file( $content ) || in_array(
$content,
$configs,
true
) ) {
continue;
}
if ( false === strpos( $this->filesystem->get_contents( $content ), '$rocket_cookie_hash' ) ) {
continue;
}
$this->filesystem->delete( $content );
}
}
/**
* Generate the path to the config for the current website.
*
* @return string
*/
protected function generate_config_path() {
$file = get_rocket_parse_url( untrailingslashit( home_url() ) );
$file['path'] = ( ! empty( $file['path'] ) ) ? str_replace( '/', '.', untrailingslashit( $file['path'] ) ) : '';
return WP_ROCKET_CONFIG_PATH . strtolower( $file['host'] ) . $file['path'] . '.php';
}
/**
* Clear cache.
*
* @param string $current_url current URL from the website.
* @param string $old_url old URL from the website.
*
* @return void
*/
public function clear_cache( string $current_url, string $old_url ) {
rocket_clean_files( [ $old_url, $current_url ], null, false );
}
/**
* Regenerate the advanced cache file 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;
}
rocket_generate_advanced_cache_file();
}
}
@@ -0,0 +1,206 @@
<?php
namespace WP_Rocket\Engine\Cache;
use WP_Filesystem_Direct;
use WP_Rocket\Engine\Activation\ActivationInterface;
use WP_Rocket\Engine\Deactivation\DeactivationInterface;
class AdvancedCache implements ActivationInterface, DeactivationInterface {
/**
* Absolute path to template files
*
* @var string
*/
private $template_path;
/**
* WP Content directory path
*
* @var string
*/
private $content_dir;
/**
* Instance of the filesystem handler.
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Instantiate of the class.
*
* @param string $template_path Absolute path to template files.
* @param WP_Filesystem_Direct $filesystem Instance of the filesystem handler.
*/
public function __construct( $template_path, $filesystem ) {
$this->template_path = $template_path;
$this->content_dir = rocket_get_constant( 'WP_CONTENT_DIR' );
$this->filesystem = $filesystem;
}
/**
* Actions to perform on plugin activation
*
* @since 3.6.3
*
* @return void
*/
public function activate() {
add_action( 'rocket_activation', [ $this, 'update_advanced_cache' ] );
}
/**
* Actions to perform on plugin deactivation
*
* @since 3.6.3
*
* @return void
*/
public function deactivate() {
add_action( 'rocket_deactivation', [ $this, 'update_advanced_cache' ] );
}
/**
* Generates the advanced-cache.php file with its content
*
* @since 3.6.3
*
* @param int $sites_number Number of WP Rocket config files found.
* @return void
*/
public function update_advanced_cache( $sites_number = 0 ) {
/**
* Filters whether to generate the advanced-cache.php file.
*
* @since 3.6.3
*
* @param bool True (default) to go ahead with advanced cache file generation; false to stop generation.
*/
if ( ! (bool) apply_filters( 'rocket_generate_advanced_cache_file', true ) ) {
return;
}
$content = $this->get_advanced_cache_content();
if ( 'rocket_deactivation' === current_filter() ) {
if ( is_multisite() && 0 !== $sites_number ) {
return;
}
$content = '';
}
$this->filesystem->put_contents(
"{$this->content_dir}/advanced-cache.php",
$content,
rocket_get_filesystem_perms( 'file' )
);
}
/**
* Gets the content for the advanced-cache.php file
*
* @since 3.6
*
* @return string
*/
public function get_advanced_cache_content() {
$content = $this->filesystem->get_contents( $this->template_path . 'advanced-cache.php' );
$mobile = is_rocket_generate_caching_mobile_files() ? '$1' : '';
$content = preg_replace( "/'{{MOBILE_CACHE}}';(\X*)'{{\/MOBILE_CACHE}}';/", $mobile, $content );
$replacements = [
'{{WP_ROCKET_PHP_VERSION}}' => rocket_get_constant( 'WP_ROCKET_PHP_VERSION' ),
'{{WP_ROCKET_PATH}}' => rocket_get_constant( 'WP_ROCKET_PATH' ),
'{{WP_ROCKET_CONFIG_PATH}}' => rocket_get_constant( 'WP_ROCKET_CONFIG_PATH' ),
'{{WP_ROCKET_CACHE_PATH}}' => rocket_get_constant( 'WP_ROCKET_CACHE_PATH' ),
];
foreach ( $replacements as $key => $value ) {
$content = str_replace( $key, $value, $content );
}
/**
* Filter the content of advanced-cache.php file.
*
* @since 2.1
*
* @param string $content The content that will be printed in advanced-cache.php.
*/
return (string) apply_filters( 'rocket_advanced_cache_file', $content );
}
/**
* This warning is displayed when the advanced-cache.php file isn't writeable
*
* @since 3.6 Moved to a method in AdvancedCache
* @since 2.0
*
* @return void
*/
public function notice_permissions() {
if ( ! $this->is_user_allowed() ) {
return;
}
// This filter is documented in inc/functions/files.php.
if ( ! (bool) apply_filters( 'rocket_generate_advanced_cache_file', true ) ) {
return;
}
if (
$this->filesystem->is_writable( "{$this->content_dir}/advanced-cache.php" )
||
rocket_get_constant( 'WP_ROCKET_ADVANCED_CACHE' )
) {
return;
}
$notice_name = 'rocket_warning_advanced_cache_permissions';
if (
in_array(
$notice_name,
(array) get_user_meta( get_current_user_id(), 'rocket_boxes', true ),
true
)
) {
return;
}
rocket_notice_html(
[
'status' => 'error',
'dismissible' => '',
'message' => $this->get_notice_message(),
'dismiss_button' => $notice_name,
'readonly_content' => $this->get_advanced_cache_content(),
]
);
}
/**
* Checks if current user can see the notices
*
* @since 3.6
*
* @return bool
*/
private function is_user_allowed() {
return current_user_can( 'rocket_manage_options' ) && rocket_valid_key();
}
/**
* Gets the message to display in the notice
*
* @since 3.6
*
* @return string
*/
private function get_notice_message() {
return rocket_notice_writing_permissions( basename( $this->content_dir ) . '/advanced-cache.php' );
}
}
@@ -0,0 +1,108 @@
<?php
namespace WP_Rocket\Engine\Cache\Config;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Admin\Options;
/**
* Subscriber for the Cache Config
*/
class ConfigSubscriber implements Subscriber_Interface {
/**
* Options Data instance.
*
* @var Options_Data
*/
private $options;
/**
* Options instance.
*
* @var Options
*/
private $options_api;
/**
* Creates an instance of the Cache Config Subscriber.
*
* @param Options_Data $options WP Rocket options instance.
* @param Options $options_api Options instance.
*/
public function __construct( Options_Data $options, Options $options_api ) {
$this->options = $options;
$this->options_api = $options_api;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'permalink_structure_changed' => 'regenerate_config_file',
'pre_update_option_' . rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' ) => [ 'change_cache_reject_uri_with_permalink', 10, 2 ],
];
}
/**
* Returns a matching user added patterns with permalink structure
*
* @param array $patterns user pattern.
* @return array
*/
private function match_pattern_with_permalink_structure( array $patterns ): array {
if ( empty( $patterns ) ) {
return $patterns;
}
$patterns = array_map(
function ( $uri ) {
if ( false !== strpos( $uri, 'index.php' ) || '/' === $uri ) {
return $uri;
}
return user_trailingslashit( $uri );
},
$patterns
);
return $patterns;
}
/**
* Regenerate config file.
*
* @return void
*/
public function regenerate_config_file() {
$cache_reject_uri = $this->match_pattern_with_permalink_structure( $this->options->get( 'cache_reject_uri', [] ) );
$this->options->set( 'cache_reject_uri', $cache_reject_uri );
$this->options_api->set( 'settings', $this->options->get_options() );
rocket_generate_config_file();
}
/**
* Modify cache_reject_uri values.
*
* @param mixed $value The new, unserialized option value.
* @param mixed $old_value The old option value.
* @return array
*/
public function change_cache_reject_uri_with_permalink( $value, $old_value ): array {
if ( ! isset( $old_value['cache_reject_uri'], $value['cache_reject_uri'] ) ) {
return $value;
}
if ( $old_value['cache_reject_uri'] === $value['cache_reject_uri'] ) {
return $value;
}
$value['cache_reject_uri'] = $this->match_pattern_with_permalink_structure( $value['cache_reject_uri'] );
return $value;
}
}
@@ -0,0 +1,30 @@
<?php
namespace WP_Rocket\Engine\Cache\Config;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Subscriber for the Cache Config
*/
class Subscriber implements Subscriber_Interface {
/**
* Return an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'permalink_structure_changed' => 'regenerate_config_file',
];
}
/**
* Regenerate config file.
*
* @return void
*/
public function regenerate_config_file() {
rocket_generate_config_file();
}
}
@@ -0,0 +1,307 @@
<?php
namespace WP_Rocket\Engine\Cache;
use WP_Rocket\Engine\Preload\Database\Queries\Cache;
use DirectoryIterator;
use Exception;
use WP_Term;
use WP_Post;
/**
* Cache Purge handling class
*/
class Purge {
/**
* Filesystem instance
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Cache Query
*
* @var Cache
*/
protected $query;
/**
* Initialize the class.
*
* @param WP_Filesystem_Direct $filesystem Filesystem instance.
* @param Cache $query Cache query instance.
*/
public function __construct( $filesystem, Cache $query ) {
$this->filesystem = $filesystem;
$this->query = $query;
}
/**
* Purges cache for the dates archives of a post
*
* @param WP_Post $post Post object.
* @return void
*/
public function purge_dates_archives( $post ) {
foreach ( $this->get_dates_archives( $post ) as $url ) {
$this->purge_url( $url, true );
}
}
/**
* Purge URL cache.
*
* @param string $url URL to be purged.
* @param boolean $pagination Purge also pagination.
* @return void
*/
public function purge_url( $url, $pagination = false ) {
if ( ! is_string( $url ) ) {
return;
}
global $wp_rewrite;
$parsed_url = $this->parse_url( $url );
foreach ( _rocket_get_cache_dirs( $parsed_url['host'] ) as $dir ) {
$path = $dir . $parsed_url['path'];
if ( ! $this->filesystem->exists( $path ) ) {
continue;
}
foreach ( $this->get_iterator( $path ) as $item ) {
if ( $item->isFile() ) {
$this->filesystem->delete( $item->getPathname() );
}
}
if ( $pagination ) {
$this->maybe_remove_dir( $path . DIRECTORY_SEPARATOR . $wp_rewrite->pagination_base );
}
}
}
/**
* Gets the dates archives URLs for the provided post
*
* @param WP_Post $post Post object.
* @return array
*/
private function get_dates_archives( $post ) {
$time = get_the_time( 'Y-m-d', $post );
if ( empty( $time ) ) {
return [];
}
$date = explode( '-', $time );
$urls = [
get_year_link( $date[0] ),
get_month_link( $date[0], $date[1] ),
get_day_link( $date[0], $date[1], $date[2] ),
];
/**
* Filter the list of dates URLs.
*
* @since 1.1.0
*
* @param array $urls List of dates URLs.
*/
return (array) apply_filters( 'rocket_post_dates_urls', $urls );
}
/**
* Parses URL and return the parts array
*
* @since 3.6.1
*
* @param string $url URL to parse.
* @return array
*/
private function parse_url( $url ) {
$parsed_url = get_rocket_parse_url( $url );
/** This filter is documented in inc/front/htaccess.php */
if ( apply_filters( 'rocket_url_no_dots', false ) ) {
$parsed_url['host'] = str_replace( '.', '_', $parsed_url['host'] );
}
return $parsed_url;
}
/**
* Gets the iterator for the given path
*
* @since 3.6.1
*
* @param string $path Absolute path.
* @return DirectoryIterator|array
*/
private function get_iterator( $path ) {
try {
$iterator = new DirectoryIterator( $path );
} catch ( Exception $e ) {
// No action required, as logging not enabled.
$iterator = [];
}
return $iterator;
}
/**
* Recursively remove the provided directory and its content
*
* @since 3.6.1
*
* @param string $dir Absolute path for the directory.
* @return void
*/
private function maybe_remove_dir( $dir ) {
if ( $this->filesystem->is_dir( $dir ) ) {
rocket_rrmdir( $dir, [], $this->filesystem );
}
}
/**
* Purge all terms archives urls associated to a specific post.
*
* @since 3.6.1
*
* @param WP_Post $post Post object.
*/
public function purge_post_terms_urls( WP_Post $post ) {
$urls = $this->get_post_terms_urls( $post );
foreach ( $urls as $url ) {
$this->purge_url( $url, true );
}
/**
* Action to preload urls after cleaning cache.
*
* @param array urls to preload.
*/
do_action( 'rocket_after_clean_terms', $urls );
}
/**
* Get all terms archives urls associated to a specific post.
*
* @since 3.6.1
*
* @param WP_Post $post Post object.
*
* @return array $urls List of taxonomies URLs
*/
private function get_post_terms_urls( WP_Post $post ) {
$urls = [];
$taxonomies = get_object_taxonomies( get_post_type( $post->ID ), 'objects' );
/**
* Filters the taxonomies excluded from post purge
*
* @since 3.9.1
*
* @param array $excluded_taxonomies Array of excluded taxonomies names.
*/
$excluded_taxonomies = apply_filters( 'rocket_exclude_post_taxonomy', [] );
foreach ( $taxonomies as $taxonomy ) {
if (
! $taxonomy->public
||
in_array( $taxonomy->name, $excluded_taxonomies, true )
) {
continue;
}
// Get the terms related to post.
$terms = get_the_terms( $post->ID, $taxonomy->name );
if ( empty( $terms ) || is_wp_error( $terms ) ) {
continue;
}
foreach ( $terms as $term ) {
$term_url = get_term_link( $term->slug, $taxonomy->name );
if ( ! is_wp_error( $term_url ) ) {
$urls[] = $term_url;
}
if ( ! is_taxonomy_hierarchical( $taxonomy->name ) ) {
continue;
}
$ancestors = (array) get_ancestors( $term->term_id, $taxonomy->name );
foreach ( $ancestors as $ancestor ) {
$ancestor_object = get_term( $ancestor, $taxonomy->name );
if ( ! $ancestor_object instanceof WP_Term ) {
continue;
}
$ancestor_term_url = get_term_link( $ancestor_object->slug, $taxonomy->name );
if ( ! is_wp_error( $ancestor_term_url ) ) {
$urls[] = $ancestor_term_url;
}
}
}
}
// Remove entries with empty values in array.
$urls = array_filter( $urls, 'is_string' );
/**
* Filter the list of taxonomies URLs
*
* @since 1.1.0
*
* @param array $urls List of taxonomies URLs
*/
return apply_filters( 'rocket_post_terms_urls', $urls );
}
/**
* Purge single cache file(s) added in the Never Cache URL(s).
*
* @param array $old_value An array of previous values for the settings.
* @param array $value An array of submitted values for the settings.
* @return void
*/
public function purge_cache_reject_uri_partially( array $old_value, array $value ): void {
// Bail out if cache_reject_uri key is not in the settings array.
if ( ! array_key_exists( 'cache_reject_uri', $old_value ) || ! array_key_exists( 'cache_reject_uri', $value ) ) {
return;
}
// Get change in uris.
$diff = array_diff( $value['cache_reject_uri'], $old_value['cache_reject_uri'] );
// Bail out if values has not changed.
if ( empty( $diff ) ) {
return;
}
$urls = [];
$wildcard = '(.*)';
foreach ( $diff as $path ) {
// Check if string is a path or pattern.
if ( strpos( $path, $wildcard ) !== false ) {
$pattern = preg_replace( '#\(\.\*\).*#', '*', $path );
$results = $this->query->query(
[
'search' => $pattern,
'search_columns' => [ 'url' ],
'status' => 'completed',
]
);
foreach ( $results as $result ) {
$urls[] = $result->url;
}
continue;
}
// Get full url of never cache path.
$urls[] = home_url( $path );
}
rocket_clean_files( array_unique( $urls ) );
}
}
@@ -0,0 +1,212 @@
<?php
namespace WP_Rocket\Engine\Cache;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Logger\Logger;
/**
* Subscriber for the cache purge actions
*
* @since 3.5
*/
class PurgeActionsSubscriber implements Subscriber_Interface {
/**
* WP Rocket options instance
*
* @var Options_Data
*/
private $options;
/**
* Purge instance
*
* @var Purge
*/
private $purge;
/**
* Constructor
*
* @param Options_Data $options WP Rocket options instance.
* @param Purge $purge Purge instance.
*/
public function __construct( Options_Data $options, Purge $purge ) {
$this->options = $options;
$this->purge = $purge;
}
/**
* {@inheritdoc}
*/
public static function get_subscribed_events() {
$slug = rocket_get_constant( 'WP_ROCKET_SLUG' );
return [
'profile_update' => 'purge_user_cache',
'delete_user' => 'purge_user_cache',
'create_term' => [ 'maybe_purge_cache_on_term_change', 10, 3 ],
'edit_term' => [ 'maybe_purge_cache_on_term_change', 10, 3 ],
'delete_term' => [ 'maybe_purge_cache_on_term_change', 10, 3 ],
'after_rocket_clean_post' => [
[ 'purge_dates_archives' ],
[ 'purge_post_terms_urls' ],
],
'rocket_rucss_complete_job_status' => [ 'purge_url_cache', 100 ],
'rocket_rucss_after_clearing_usedcss' => 'purge_url_cache',
'rocket_after_save_dynamic_lists' => 'purge_cache_after_saving_dynamic_lists',
'update_option_' . $slug => [ 'purge_cache_reject_uri_partially', 10, 2 ],
'update_option_blog_public' => 'purge_cache',
'wp_rocket_upgrade' => [ 'on_update', 10, 2 ],
];
}
/**
* Purges the cache of the corresponding user
*
* @since 3.5
*
* @param int $user_id User ID.
* @return void
*/
public function purge_user_cache( $user_id ) {
if ( ! $this->should_purge_user_cache() ) {
return;
}
rocket_clean_user( $user_id );
}
/**
* Purges the cache when a public term is created|updated|deleted
*
* @since 3.5.5
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
* @param string $taxonomy Taxonomy slug.
* @return void
*/
public function maybe_purge_cache_on_term_change( $term_id, $tt_id, $taxonomy ) {
if ( ! $this->is_taxonomy_public( $taxonomy ) ) {
return;
}
rocket_clean_domain();
}
/**
* Purges cache for the dates archives of a post after cleaning the post
*
* @param WP_Post $post Post object.
* @return void
*/
public function purge_dates_archives( $post ) {
$this->purge->purge_dates_archives( $post );
}
/**
* Purge all terms archives urls associated to a specific post.
*
* @param WP_Post $post Post object.
* @return void
*/
public function purge_post_terms_urls( $post ) {
$this->purge->purge_post_terms_urls( $post );
}
/**
* Checks if the given taxonomy is public
*
* @param string $name Taxonomy name.
* @return bool
*/
private function is_taxonomy_public( $name ) {
$taxonomy = get_taxonomy( $name );
if ( false === $taxonomy ) {
return false;
}
return ( $taxonomy->public && $taxonomy->publicly_queryable );
}
/**
* Checks if the user cache should be purged
*
* @since 3.5
*
* @return boolean
*/
private function should_purge_user_cache() {
if ( ! $this->options->get( 'cache_logged_user', 0 ) ) {
return false;
}
// This filter is documented in /inc/functions/files.php.
return ! (bool) apply_filters( 'rocket_common_cache_logged_users', false );
}
/**
* Purge cache after RUCSS
*
* @param string $url URL to be purged.
*
* @return void
*/
public function purge_url_cache( string $url ) {
// Flush cache for this url.
Logger::debug( 'RUCSS: Purge the cache for url: ' . $url );
$this->purge->purge_url( $url );
}
/**
* Clean the whole cache
*
* @return void
*/
public function purge_cache() {
rocket_clean_domain();
}
/**
* Purge single cache file(s) added in the Never Cache URL(s).
*
* @param array $old_value An array of previous values for the settings.
* @param array $value An array of submitted values for the settings.
* @return void
*/
public function purge_cache_reject_uri_partially( array $old_value, array $value ): void {
$this->purge->purge_cache_reject_uri_partially( $old_value, $value );
}
/**
* Purge cache after saving dynamic lists.
*
* @param bool $should_purge Should purge or not.
*
* @return void
*/
public function purge_cache_after_saving_dynamic_lists( $should_purge = true ) {
if ( ! $should_purge ) {
return;
}
$this->purge_cache();
}
/**
* Regenerate the advanced cache file 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.3', '>=' ) ) {
return;
}
rocket_generate_advanced_cache_file();
}
}
@@ -0,0 +1,404 @@
<?php
namespace WP_Rocket\Engine\Cache\PurgeExpired;
use WP_Rocket\Buffer\Cache;
/**
* Purge expired cache files based on the defined lifespan
*
* @since 3.4
*/
class PurgeExpiredCache {
/**
* Path to the global cache folder.
*
* @since 3.4
*
* @var string
*/
private $cache_path;
/**
* Filesystem object.
*
* @since 3.4
*
* @var \WP_Filesystem_Direct
*/
private $filesystem;
/**
* Constructor
*
* @param string $cache_path Path to the global cache folder.
*/
public function __construct( $cache_path ) {
$this->cache_path = $cache_path;
}
/**
* Perform the event action.
*
* @since 3.4
*
* @param int $lifespan The cache lifespan in seconds.
*/
public function purge_expired_files( $lifespan ) {
if ( ! $lifespan ) {
// Uh?
return;
}
$urls = get_rocket_i18n_uri();
$file_age_limit = time() - $lifespan;
/**
* Filter home URLs that will be searched for old cache files.
*
* @since 3.4
*
* @param array $urls URLs that will be searched for old cache files.
* @param int $file_age_limit Timestamp of the maximum age files must have.
*/
$urls = apply_filters( 'rocket_automatic_cache_purge_urls', $urls, $file_age_limit );
if ( ! is_array( $urls ) ) {
// I saw what you did ಠ_ಠ.
$urls = get_rocket_i18n_uri();
}
$urls = array_filter( $urls, 'is_string' );
$urls = array_filter( $urls );
if ( ! $urls ) {
return;
}
$urls = array_unique( $urls );
if ( empty( $this->filesystem ) ) {
$this->filesystem = rocket_direct_filesystem();
}
$deleted = [];
$cache_enabled = Cache::can_generate_caching_files();
foreach ( $urls as $url ) {
/**
* Fires before purging a cache directory.
*
* @since 3.4
*
* @param string $url The home url.
* @param int $file_age_limit Timestamp of the maximum age files must have.
*/
do_action( 'rocket_before_automatic_cache_purge_dir', $url, $file_age_limit );
$url_deleted = [];
if ( $cache_enabled ) {
// Get the directory names.
$file = get_rocket_parse_url( $url );
/** This filter is documented in inc/front/htaccess.php */
if ( apply_filters( 'rocket_url_no_dots', false ) ) {
$file['host'] = str_replace( '.', '_', $file['host'] );
}
$sub_dir = rtrim( $file['path'], '/' );
$files = $this->get_cache_files_in_dir( $file );
foreach ( $files as $item ) {
$dir_path = $item->getPathname();
$sub_dir_path = $dir_path . $sub_dir;
// Time to cut old leaves.
$item_paths = $this->purge_dir( $sub_dir_path, $file_age_limit );
if ( $item_paths ) {
$url_deleted[] = [
'home_url' => $url,
'home_path' => $sub_dir_path,
'logged_in' => $dir_path !== $this->cache_path . $file['host'],
'files' => $item_paths,
];
}
if ( $this->is_dir_empty( $dir_path ) ) {
// If the folder is empty, remove it.
$this->filesystem->delete( $dir_path );
}
}
if ( $url_deleted ) {
$deleted = array_merge( $deleted, $url_deleted );
}
}
$args = [
'url' => $url,
'lifespan' => $lifespan,
'file_age_limit' => $file_age_limit,
];
/**
* Fires after a cache directory is purged.
*
* @since 3.4
*
* @param array $deleted {
* An array of arrays sharing the same home URL, described like: {
* @type string $home_url The home URL. This is the same as $args['url'].
* @type string $home_path Path to home.
* @type bool $logged_in True if the home path corresponds to a logged in user’s folder.
* @type array $files A list of paths of files that have been deleted.
* }
* Ex:
* [
* [
* 'home_url' => 'http://example.com/home1',
* 'home_path' => '/path-to/home1/wp-content/cache/wp-rocket/example.com/home1',
* 'logged_in' => false,
* 'files' => [
* '/path-to/home1/wp-content/cache/wp-rocket/example.com/home1/deleted-page',
* '/path-to/home1/wp-content/cache/wp-rocket/example.com/home1/very-dead-page',
* ],
* ],
* [
* 'home_url' => 'http://example.com/home1',
* 'home_path' => '/path-to/home1/wp-content/cache/wp-rocket/example.com-Greg-594d03f6ae698691165999/home1',
* 'logged_in' => true,
* 'files' => [
* '/path-to/home1/wp-content/cache/wp-rocket/example.com-Greg-594d03f6ae698691165999/home1/how-to-prank-your-coworkers',
* '/path-to/home1/wp-content/cache/wp-rocket/example.com-Greg-594d03f6ae698691165999/home1/best-source-of-gifs',
* ],
* ],
* ]
* @param array $args {
* @type string $url The home url.
* @type int $lifespan Files lifespan in seconds.
* @type int $file_age_limit Timestamp of the maximum age files must have. This is basically `time() - $lifespan`.
* }
*/
do_action( 'rocket_after_automatic_cache_purge_dir', $url_deleted, $args );
}
$args = [
'lifespan' => $lifespan,
'file_age_limit' => $file_age_limit,
];
/**
* Fires after cache directories are purged.
*
* @since 3.4
*
* @param array $deleted {
* An array of arrays, described like: {
* @type string $home_url The home URL.
* @type string $home_path Path to home.
* @type bool $logged_in True if the home path corresponds to a logged in user’s folder.
* @type array $files A list of paths of files that have been deleted.
* }
* Ex:
* [
* [
* 'home_url' => 'http://example.com/home1',
* 'home_path' => '/path-to/home1/wp-content/cache/wp-rocket/example.com/home1',
* 'logged_in' => false,
* 'files' => [
* '/path-to/home1/wp-content/cache/wp-rocket/example.com/home1/deleted-page',
* '/path-to/home1/wp-content/cache/wp-rocket/example.com/home1/very-dead-page',
* ],
* ],
* [
* 'home_url' => 'http://example.com/home1',
* 'home_path' => '/path-to/home1/wp-content/cache/wp-rocket/example.com-Greg-594d03f6ae698691165999/home1',
* 'logged_in' => true,
* 'files' => [
* '/path-to/home1/wp-content/cache/wp-rocket/example.com-Greg-594d03f6ae698691165999/home1/how-to-prank-your-coworkers',
* '/path-to/home1/wp-content/cache/wp-rocket/example.com-Greg-594d03f6ae698691165999/home1/best-source-of-gifs',
* ],
* ],
* [
* 'home_url' => 'http://example.com/home4',
* 'home_path' => '/path-to/home4/wp-content/cache/wp-rocket/example.com-Greg-71edg8d6af865569979569/home4',
* 'logged_in' => true,
* 'files' => [
* '/path-to/home4/wp-content/cache/wp-rocket/example.com-Greg-71edg8d6af865569979569/home4/easter-eggs-in-code-your-best-opportunities',
* ],
* ],
* ]
* }
* @param array $args {
* @type int $lifespan Files lifespan in seconds.
* @type int $file_age_limit Timestamp of the maximum age files must have. This is basically `time() - $lifespan`.
* }
*/
do_action( 'rocket_after_automatic_cache_purge', $deleted, $args );
}
/** ----------------------------------------------------------------------------------------- */
/** TOOLS =================================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Get all cache files for the provided URL
*
* @since 3.4
*
* @param array $file An array of the parsed URL parts.
* @return array|\CallbackFilterIterator
*/
private function get_cache_files_in_dir( $file ) {
// Grab cache folders.
$host_pattern = '@^' . preg_quote( $file['host'], '@' ) . '@';
$sub_dir = rtrim( $file['path'], '/' );
try {
$iterator = new \DirectoryIterator( $this->cache_path );
}
catch ( \Exception $e ) {
return [];
}
return new \CallbackFilterIterator(
$iterator,
function ( $current ) use ( $host_pattern, $sub_dir ) {
if ( ! $current->isDir() || $current->isDot() ) {
// We look for folders only, and don't want '.' nor '..'.
return false;
}
if ( ! preg_match( $host_pattern, $current->getFilename() ) ) {
// Not the right host.
return false;
}
if ( '' !== $sub_dir && ! $this->filesystem->exists( $current->getPathname() . $sub_dir ) ) {
// Not the right path.
return false;
}
return true;
}
);
}
/**
* Purge a folder from old files.
*
* @since 3.4
*
* @param string $dir_path Path to the folder to purge.
* @param int $file_age_limit Timestamp of the maximum age files must have.
* @return array A list of files that have been deleted.
*/
private function purge_dir( $dir_path, $file_age_limit ) {
$deleted = [];
try {
$iterator = new \DirectoryIterator( $dir_path );
}
catch ( \Exception $e ) {
return [];
}
foreach ( $iterator as $item ) {
if ( $item->isDot() ) {
continue;
}
if ( $item->isDir() ) {
/**
* A folder, let’s see what’s in there.
* Maybe there’s a dinosaur fossil or a hidden treasure.
*/
$dir_deleted = $this->purge_dir( $item->getPathname(), $file_age_limit );
$deleted = array_merge( $deleted, $dir_deleted );
} elseif ( $item->isFile() && $item->getMTime() < $file_age_limit ) {
$file_path = $item->getPathname();
/**
* The file is older than our limit.
* This will also delete the file if `$item->getMTime()` fails.
*/
if ( ! $this->filesystem->delete( $file_path ) ) {
continue;
}
/**
* A page can have mutiple cache files:
* index(-mobile)(-https)(-dynamic-cookie-key){0,*}.html(_gzip).
*/
$dir_path = dirname( $file_path );
if ( ! in_array( $dir_path, $deleted, true ) ) {
$deleted[] = $dir_path;
}
}
}
if ( $this->is_dir_empty( $dir_path ) ) {
// If the folder is empty, remove it.
$this->filesystem->delete( $dir_path );
}
return $deleted;
}
/**
* Tell if a folder is empty.
*
* @since 3.4
*
* @param string $dir_path Path to the folder to purge.
* @return bool True if empty. False if it contains files.
*/
private function is_dir_empty( $dir_path ) {
try {
$iterator = new \DirectoryIterator( $dir_path );
}
catch ( \Exception $e ) {
return [];
}
foreach ( $iterator as $item ) {
if ( $item->isDot() ) {
continue;
}
return false;
}
return true;
}
/**
* Update lifespan option to convert old minutes to hours.
*
* @since 3.8
*
* @param int $old_lifespan Old value in minutes.
* @param int $old_lifespan_unit Old value of unit.
*
* @return void
*/
public function update_lifespan_value( $old_lifespan, $old_lifespan_unit ) {
if ( 'MINUTE_IN_SECONDS' !== $old_lifespan_unit ) {
return;
}
$options = get_option( 'wp_rocket_settings', [] );
if ( $old_lifespan > 0 && $old_lifespan < 60 ) {
$old_lifespan = 60;
}
$options['purge_cron_unit'] = 'HOUR_IN_SECONDS';
$options['purge_cron_interval'] = round( $old_lifespan / 60 );
update_option( 'wp_rocket_settings', $options );
}
}
@@ -0,0 +1,184 @@
<?php
namespace WP_Rocket\Engine\Cache\PurgeExpired;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Event subscriber to clear cached files after lifespan.
*
* @since 3.4
*/
class Subscriber implements Subscriber_Interface {
/**
* Cron name.
*
* @since 3.4
*
* @var string
*/
const EVENT_NAME = 'rocket_purge_time_event';
/**
* WP Rocket Options instance.
*
* @since 3.4
*
* @var Options_Data
*/
private $options;
/**
* Expired Cache Purge instance.
*
* @since 3.4
*
* @var PurgeExpiredCache
*/
private $purge;
/**
* Constructor.
*
* @param Options_Data $options Options instance.
* @param PurgeExpiredCache $purge Purge instance.
*/
public function __construct( Options_Data $options, PurgeExpiredCache $purge ) {
$this->options = $options;
$this->purge = $purge;
}
/**
* {@inheritdoc}
*/
public static function get_subscribed_events() {
return [
'init' => 'schedule_event',
'rocket_deactivation' => 'unschedule_event',
static::EVENT_NAME => 'purge_expired_files',
'cron_schedules' => 'custom_cron_schedule',
'wp_rocket_upgrade' => [ 'update_lifespan_option_on_update', 13, 2 ],
];
}
/**
* Adds a custom cron schedule based on purge lifespan interval.
*
* @since 3.4.3
*
* @param array $schedules An array of non-default cron schedules.
*/
public function custom_cron_schedule( $schedules ) {
$schedules['rocket_expired_cache_cron_interval'] = [
'interval' => $this->get_interval(),
'display' => __( 'WP Rocket Expired Cache Interval', 'rocket' ),
];
return $schedules;
}
/** ----------------------------------------------------------------------------------------- */
/** HOOK CALLBACKS ========================================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Scheduling the cron event.
* If the task is not programmed, it is automatically added.
*
* @since 3.4
*/
public function schedule_event() {
if ( $this->get_cache_lifespan() && ! wp_next_scheduled( static::EVENT_NAME ) ) {
$interval = $this->get_interval();
wp_schedule_event( time() + $interval, 'rocket_expired_cache_cron_interval', static::EVENT_NAME );
}
}
/**
* Gets the interval when the scheduled clean cache purge needs to run.
* If Minutes option is selected, then the interval will be set to minutes.
* If Hours / Days options are selected, then it will be set to 1 hour.
*
* @since 3.4.3
*
* @return int $interval Interval time in seconds.
*/
private function get_interval() {
$unit = $this->options->get( 'purge_cron_unit' );
$lifespan = $this->options->get( 'purge_cron_interval', 10 );
$interval = HOUR_IN_SECONDS;
if ( ! $unit || ! defined( $unit ) ) {
$unit = 'HOUR_IN_SECONDS';
}
if ( 'MINUTE_IN_SECONDS' === $unit ) {
$interval = $lifespan * MINUTE_IN_SECONDS;
}
return $interval;
}
/**
* Unschedule the event.
*
* @since 3.4
*/
public function unschedule_event() {
wp_clear_scheduled_hook( static::EVENT_NAME );
}
/**
* Perform the event action.
*
* @since 3.4
*/
public function purge_expired_files() {
$this->purge->purge_expired_files( $this->get_cache_lifespan() );
}
/**
* Get the cache lifespan in seconds.
* If no value is filled in the settings, return 0. It means the purge is disabled.
* If the value from the settings is filled but invalid, fallback to the initial value (10 hours).
*
* @since 3.4
*
* @return int The cache lifespan in seconds.
*/
public function get_cache_lifespan() {
$lifespan = $this->options->get( 'purge_cron_interval' );
if ( ! $lifespan ) {
return 0;
}
$unit = $this->options->get( 'purge_cron_unit' );
if ( $lifespan < 0 || ! $unit || ! defined( $unit ) ) {
return 10 * HOUR_IN_SECONDS;
}
return $lifespan * constant( $unit );
}
/**
* Update lifespan option to remove minutes with WP Rocket Update.
*
* @since 3.8
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function update_lifespan_option_on_update( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.8', '>' ) ) {
return;
}
$this->purge->update_lifespan_value(
$this->options->get( 'purge_cron_interval' ),
$this->options->get( 'purge_cron_unit' )
);
}
}
@@ -0,0 +1,79 @@
<?php
namespace WP_Rocket\Engine\Cache;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Cache\PurgeExpired\PurgeExpiredCache;
use WP_Rocket\Engine\Cache\PurgeExpired\Subscriber;
use WP_Rocket\Engine\Preload\Database\Queries\Cache as CacheQuery;
use WP_Rocket\Logger\Logger;
use WP_Rocket\Engine\Cache\Config\ConfigSubscriber;
/**
* Service Provider for cache subscribers
*
* @since 3.5.5
*/
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 = [
'advanced_cache',
'wp_cache',
'purge',
'purge_actions_subscriber',
'admin_cache_subscriber',
'expired_cache_purge',
'expired_cache_purge_subscriber',
'preload_caches_query',
'cache_config',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
$filesystem = rocket_direct_filesystem();
$this->getContainer()->add( 'preload_caches_query', CacheQuery::class )
->addArgument( new Logger() );
$cache_query = $this->getContainer()->get( 'preload_caches_query' );
$this->getContainer()->add( 'advanced_cache', AdvancedCache::class )
->addArgument( $this->getContainer()->get( 'template_path' ) . '/cache/' )
->addArgument( $filesystem );
$this->getContainer()->add( 'wp_cache', WPCache::class )
->addArgument( $filesystem );
$this->getContainer()->add( 'purge', Purge::class )
->addArgument( $filesystem )
->addArgument( $cache_query );
$this->getContainer()->share( 'purge_actions_subscriber', PurgeActionsSubscriber::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'purge' ) )
->addTag( 'common_subscriber' );
$this->getContainer()->share( 'admin_cache_subscriber', AdminSubscriber::class )
->addArgument( $this->getContainer()->get( 'advanced_cache' ) )
->addArgument( $this->getContainer()->get( 'wp_cache' ) )
->addTag( 'admin_subscriber' );
$this->getContainer()->add( 'expired_cache_purge', PurgeExpiredCache::class )
->addArgument( rocket_get_constant( 'WP_ROCKET_CACHE_PATH' ) );
$this->getContainer()->share( 'expired_cache_purge_subscriber', Subscriber::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'expired_cache_purge' ) )
->addTag( 'common_subscriber' );
$this->getContainer()->add( 'cache_config', ConfigSubscriber::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'options_api' ) )
->addTag( 'common_subscriber' );
}
}
@@ -0,0 +1,392 @@
<?php
namespace WP_Rocket\Engine\Cache;
use WP_Rocket\Engine\Activation\ActivationInterface;
use WP_Rocket\Engine\Deactivation\DeactivationInterface;
class WPCache implements ActivationInterface, DeactivationInterface {
/**
* Filesystem instance.
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Instantiate the class
*
* @param WP_Filesystem_Direct $filesystem Filesystem instance.
*/
public function __construct( $filesystem ) {
$this->filesystem = $filesystem;
}
/**
* Performs these actions during the plugin activation
*
* @return void
*/
public function activate() {
add_action( 'rocket_activation', [ $this, 'update_wp_cache' ] );
}
/**
* Performs these actions during the plugin deactivation
*
* @return void
*/
public function deactivate() {
add_action( 'rocket_deactivation', [ $this, 'update_wp_cache' ] );
add_filter( 'rocket_prevent_deactivation', [ $this, 'maybe_prevent_deactivation' ] );
}
/**
* Sets the WP_CACHE constant on (de)activation
*
* @since 3.6.3
*
* @param int $sites_number Number of WP Rocket config files found.
* @return void
*/
public function update_wp_cache( $sites_number = 0 ) {
if ( ! rocket_valid_key() ) {
return;
}
$value = true;
if ( 'rocket_deactivation' === current_filter() ) {
if ( is_multisite() && 0 !== $sites_number ) {
return;
}
$value = false;
}
$this->set_wp_cache_constant( $value );
}
/**
* Updates the causes array on deactivation if needed
*
* @since 3.6.3
*
* @param array $causes Array of causes to pass to the notice.
*/
public function maybe_prevent_deactivation( $causes ) {
if (
$this->find_wpconfig_path()
||
// This filter is documented in inc/Engine/Cache/WPCache.php.
! (bool) apply_filters( 'rocket_set_wp_cache_constant', true )
) {
return $causes;
}
$causes[] = 'wpconfig';
return $causes;
}
/**
* Set WP_CACHE constant to true if needed
*
* @since 3.6.1
*
* @return void
*/
public function maybe_set_wp_cache() {
if (
rocket_get_constant( 'DOING_AJAX' )
||
rocket_get_constant( 'DOING_AUTOSAVE' )
) {
return;
}
if ( rocket_get_constant( 'WP_CACHE' ) ) {
return;
}
$this->set_wp_cache_constant( true );
}
/**
* Sets the value of the WP_CACHE constant in wp-config.php
*
* @since 3.6.1
*
* @param bool $value The value to set for WP_CACHE constant.
* @return bool true on success, false otherwise.
*/
public function set_wp_cache_constant( $value ) {
if ( ! $this->should_set_wp_cache_constant( $value ) ) {
return false;
}
$config_file_path = $this->find_wpconfig_path();
if ( ! $config_file_path ) {
return false;
}
$config_file_contents = $this->filesystem->get_contents( $config_file_path );
$value = $value ? 'true' : 'false';
/**
* Filter allow to change the value of WP_CACHE constant
*
* @since 2.1
*
* @param string $value The value of WP_CACHE constant.
*/
$value = apply_filters( 'set_rocket_wp_cache_define', $value ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
$wp_cache_found = preg_match( '/^\s*define\(\s*\'WP_CACHE\'\s*,\s*(?<value>[^\s\)]*)\s*\)/m', $config_file_contents, $matches );
if (
! empty( $matches['value'] )
&&
$matches['value'] === $value
) {
return false;
}
$constant = $this->get_wp_cache_content( $value );
if ( ! $wp_cache_found ) {
$config_file_contents = preg_replace( '/(<\?php)/i', "<?php\r\n{$constant}\r\n", $config_file_contents, 1 );
} elseif ( ! empty( $matches['value'] ) && $matches['value'] !== $value ) {
$config_file_contents = preg_replace( '/^\s*define\(\s*\'WP_CACHE\'\s*,\s*([^\s\)]*)\s*\).+/m', $constant, $config_file_contents );
}
return $this->filesystem->put_contents( $config_file_path, $config_file_contents, rocket_get_filesystem_perms( 'file' ) );
}
/**
* Checks if we should set the WP_CACHE constant
*
* @since 3.6.1
*
* @param bool $value The value to set for WP_CACHE constant.
* @return bool
*/
private function should_set_wp_cache_constant( $value ) {
if ( ! $this->is_user_allowed() ) {
return false;
}
if (
true === $value
&&
rocket_get_constant( 'WP_CACHE' )
) {
return false;
}
/**
* Filters the writing of the WP_CACHE constant in wp-config.php
*
* @since 3.6.1
* @param bool $set True to allow writing, false otherwise.
*/
return (bool) apply_filters( 'rocket_set_wp_cache_constant', true );
}
/**
* Try to find the correct wp-config.php file, support one level up in file tree.
*
* @since 3.6.1
*
* @return string|bool The path of wp-config.php file or false if not found.
*/
private function find_wpconfig_path() {
/**
* Filter the wp-config's filename.
*
* @since 2.11
*
* @param string $filename The WP Config filename, without the extension.
*/
$config_file_name = apply_filters( 'rocket_wp_config_name', 'wp-config' );
$abspath = rocket_get_constant( 'ABSPATH' );
$config_file = "{$abspath}{$config_file_name}.php";
if ( $this->filesystem->is_writable( $config_file ) ) {
return $config_file;
}
$abspath_parent = dirname( $abspath ) . DIRECTORY_SEPARATOR;
$config_file_alt = "{$abspath_parent}{$config_file_name}.php";
if (
$this->filesystem->exists( $config_file_alt )
&&
$this->filesystem->is_writable( $config_file_alt )
&&
! $this->filesystem->exists( "{$abspath_parent}wp-settings.php" )
) {
return $config_file_alt;
}
// No writable file found.
return false;
}
/**
* This warning is displayed when the wp-config.php file isn't writable
*
* @since 3.6.1
*
* @return void
*/
public function notice_wp_config_permissions() {
global $pagenow;
if (
'plugins.php' === $pagenow
||
isset( $_GET['activate'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
) {
return;
}
if ( ! $this->is_user_allowed() ) {
return;
}
if ( rocket_get_constant( 'WP_CACHE' ) ) {
return;
}
// This filter is documented in inc/Engine/Cache/WPCache.php.
if ( ! (bool) apply_filters( 'rocket_set_wp_cache_constant', true ) ) {
return;
}
if ( $this->find_wpconfig_path() ) {
return;
}
$notice_name = 'rocket_warning_wp_config_permissions';
if (
in_array(
$notice_name,
(array) get_user_meta( get_current_user_id(), 'rocket_boxes', true ),
true
)
) {
return;
}
rocket_notice_html(
[
'status' => 'error',
'dismissible' => '',
'message' => rocket_notice_writing_permissions( 'wp-config.php' ),
'dismiss_button' => $notice_name,
'readonly_content' => $this->get_wp_cache_content(),
]
);
}
/**
* Checks if current user can perform the action
*
* @since 3.6.1
*
* @return bool
*/
private function is_user_allowed() {
return ( rocket_get_constant( 'WP_CLI', false ) || current_user_can( 'rocket_manage_options' ) ) && rocket_valid_key();
}
/**
* Gets the content to add to the wp-config.php file
*
* @since 3.6.1
*
* @param string $value Value for the WP_CACHE constant.
* @return string
*/
private function get_wp_cache_content( $value = 'true' ) {
$plugin_name = rocket_get_constant( 'WP_ROCKET_PLUGIN_NAME' );
return "define( 'WP_CACHE', {$value} ); // Added by {$plugin_name}";
}
/**
* Adds a Site Health check for the WP_CACHE constant value
*
* @since 3.6.1
*
* @param array $tests An array of tests to perform.
* @return array
*/
public function add_wp_cache_status_test( $tests ) {
// This filter is documented in inc/Engine/Cache/WPCache.php.
if ( ! (bool) apply_filters( 'rocket_set_wp_cache_constant', true ) ) {
return $tests;
}
$tests['direct']['wp_cache_status'] = [
'label' => __( 'WP_CACHE value', 'rocket' ),
'test' => [ $this, 'check_wp_cache_value' ],
];
return $tests;
}
/**
* Checks the WP_CACHE constant value and return the result for Site Health
*
* @since 3.6.1
*
* @return array
*/
public function check_wp_cache_value() {
$result = [
'badge' => [
'label' => __( 'Cache', 'rocket' ),
],
'description' => sprintf(
'<p>%s</p>',
__( 'The WP_CACHE constant needs to be set to true for WP Rocket cache to work properly', 'rocket' )
),
'actions' => '',
'test' => 'wp_cache_status',
];
$value = rocket_get_constant( 'WP_CACHE' );
if ( true === $value ) {
$result['label'] = __( 'WP_CACHE is set to true', 'rocket' );
$result['status'] = 'good';
$result['badge']['color'] = 'green';
return $result;
}
if ( null === $value ) {
$result['label'] = __( 'WP_CACHE is not set', 'rocket' );
$result['status'] = 'critical';
$result['badge']['color'] = 'red';
return $result;
}
if ( false === $value ) {
$result['label'] = __( 'WP_CACHE is set to false', 'rocket' );
$result['status'] = 'critical';
$result['badge']['color'] = 'red';
return $result;
}
return $result;
}
}