Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,35 @@
<?php
namespace WP_Rocket\Engine\Common\Ajax;
class AjaxHandler {
/**
* Validate the referer before going further.
*
* @param string $action Action to validate.
* @param string $capacities User capacity to verify.
* @return bool
*/
public function validate_referer( string $action, string $capacities ) {
check_admin_referer( $action );
if ( ! current_user_can( $capacities ) ) {
return false;
}
return true;
}
/**
* Redirect the page at the end of the logic.
*
* @param string $url URl to redirect to (by default referrer).
* @return void
*/
public function redirect( string $url = '' ) {
wp_safe_redirect( '' === $url ? wp_get_referer() : $url );
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
}
@@ -0,0 +1,36 @@
<?php
namespace WP_Rocket\Engine\Common\Cache;
interface CacheInterface extends \WP_Rocket\Dependencies\Psr\SimpleCache\CacheInterface {
/**
* Generate the real URL.
*
* @param string $url original URL.
* @return string
*/
public function generate_url( string $url ): string;
/**
* Is the root path available.
*
* @return bool
*/
public function is_accessible(): bool;
/**
* Get root path from the cache.
*
* @return string
*/
public function get_root_path(): string;
/**
* Generate a path from the URL.
*
* @param string $url URL to change to a path.
* @return string
*/
public function generate_path( string $url ): string;
}
@@ -0,0 +1,239 @@
<?php
namespace WP_Rocket\Engine\Common\Cache;
use WP_Rocket\Dependencies\Psr\SimpleCache\InvalidArgumentException;
use WP_Filesystem_Direct;
class FilesystemCache implements CacheInterface {
/**
* Root folder from the path.
*
* @var string
*/
protected $root_folder;
/**
* WordPress filesystem.
*
* @var WP_Filesystem_Direct
*/
protected $filesystem;
/**
* Class instantiation.
*
* @param string $root_folder Root folder from the path.
* @param WP_Filesystem_Direct|null $filesystem WordPress filesystem.
*/
public function __construct( string $root_folder, WP_Filesystem_Direct $filesystem = null ) {
$this->root_folder = $root_folder;
$this->filesystem = $filesystem ?: rocket_direct_filesystem();
}
/**
* Fetches a value from the cache.
*
* @param string $key The unique key of this item in the cache.
* @param mixed $default Default value to return if the key does not exist.
*
* @return mixed The value of the item from the cache, or $default in case of cache miss.
*/
public function get( $key, $default = null ) {
$path = $this->generate_path( $key );
if ( ! $this->filesystem->exists( $path ) ) {
return $default;
}
return $this->filesystem->get_contents( $path );
}
/**
* Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
*
* @param string $key The key of the item to store.
* @param mixed $value The value of the item to store, must be serializable.
* @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and
* the driver supports TTL then the library may set a default value
* for it or let the driver take care of that.
*
* @return bool True on success and false on failure.
*/
public function set( $key, $value, $ttl = null ) {
$path = $this->generate_path( $key );
$directory = dirname( $path );
rocket_mkdir_p( $directory, $this->filesystem );
return $this->filesystem->put_contents( $path, $value, rocket_get_filesystem_perms( 'file' ) );
}
/**
* Delete an item from the cache by its unique key.
*
* @param string $key The unique cache key of the item to delete.
*
* @return bool True if the item was successfully removed. False if there was an error.
*/
public function delete( $key ) {
$path = $this->generate_path( $key );
if ( ! $this->filesystem->exists( $path ) ) {
return false;
}
if ( $this->filesystem->is_dir( $path ) ) {
rocket_rrmdir( $path, [], $this->filesystem );
return true;
}
return $this->filesystem->delete( $path );
}
/**
* Wipes clean the entire cache's keys.
*
* @return bool True on success and false on failure.
*/
public function clear() {
$root_path = $this->get_root_path();
if ( ! $this->filesystem->exists( $root_path ) ) {
return false;
}
rocket_rrmdir( $root_path, [], $this->filesystem );
return true;
}
/**
* Obtains multiple cache items by their unique keys.
*
* @param iterable $keys A list of keys that can obtained in a single operation.
* @param mixed $default Default value to return for keys that do not exist.
*
* @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
*/
public function getMultiple( $keys, $default = null ) {
$results = [];
foreach ( $keys as $key ) {
$results[ $key ] = $this->get( $key, $default );
}
return $results;
}
/**
* Persists a set of key => value pairs in the cache, with an optional TTL.
*
* @param iterable $values A list of key => value pairs for a multiple-set operation.
* @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and
* the driver supports TTL then the library may set a default value
* for it or let the driver take care of that.
*
* @return bool True on success and false on failure.
*/
public function setMultiple( $values, $ttl = null ) {
$result = true;
foreach ( $values as $key => $value ) {
$result &= $this->set( $key, $value, $ttl );
}
return (bool) $result;
}
/**
* Deletes multiple cache items in a single operation.
*
* @param iterable $keys A list of string-based keys to be deleted.
*
* @return bool True if the items were successfully removed. False if there was an error.
*/
public function deleteMultiple( $keys ) {
$result = true;
foreach ( $keys as $key ) {
$result &= $this->delete( $key );
}
return (bool) $result;
}
/**
* Determines whether an item is present in the cache.
*
* NOTE: It is recommended that has() is only to be used for cache warming type purposes
* and not to be used within your live applications operations for get/set, as this method
* is subject to a race condition where your has() will return true and immediately after,
* another script can remove it making the state of your app out of date.
*
* @param string $key The cache item key.
*
* @return bool
*/
public function has( $key ) {
$path = $this->generate_path( $key );
return $this->filesystem->exists( $path );
}
/**
* Generate the real URL.
*
* @param string $url original URL.
* @return string
*/
public function generate_url( string $url ): string {
$path = $this->generate_path( $url );
if ( ! $this->filesystem->exists( $path ) ) {
return $url;
}
$wp_content_dir = rocket_get_constant( 'WP_CONTENT_DIR' );
$wp_content_url = rocket_get_constant( 'WP_CONTENT_URL' );
$relative_path = str_replace( $wp_content_dir, '', $path );
$generated_url = $wp_content_url . $relative_path;
return (string) apply_filters( 'rocket_css_url', $generated_url );
}
/**
* Generate a path from the URL.
*
* @param string $url URL to change to a path.
* @return string
*/
public function generate_path( string $url ): string {
$root_path = $this->get_root_path();
$root_path = rtrim( $root_path, '/' );
$parsed_url = get_rocket_parse_url( $url );
$parsed_url_path = trim( $parsed_url['path'], '/' );
$home_url = home_url();
$home_parsed_url = get_rocket_parse_url( $home_url );
$host = '' === $parsed_url['host'] || null === $parsed_url['host'] ? $home_parsed_url['host'] : $parsed_url['host'];
$parsed_url_host = '/' . $host;
return $root_path . $parsed_url_host . '/' . $parsed_url_path;
}
/**
* Is the root path available.
*
* @return bool
*/
public function is_accessible(): bool {
$root_path = $this->get_root_path();
if ( ! $this->filesystem->exists( $root_path ) ) {
rocket_mkdir_p( $root_path, $this->filesystem );
}
return $this->filesystem->is_writable( $root_path );
}
/**
* Get root path from the cache.
*
* @return string
*/
public function get_root_path(): string {
return rtrim( _rocket_normalize_path( rocket_get_constant( 'WP_ROCKET_CACHE_ROOT_PATH' ) ) . $this->root_folder, '/' ) . '/';
}
}
@@ -0,0 +1,76 @@
<?php
namespace WP_Rocket\Engine\Common\Context;
use WP_Rocket\Admin\Options_Data;
abstract class AbstractContext implements ContextInterface {
/**
* WPR options.
*
* @var Options_Data
*/
protected $options;
/**
* Instantiate the class.
*
* @param Options_Data $options WPR options.
*/
public function __construct( Options_Data $options ) {
$this->options = $options;
}
/**
* Run common checks.
*
* @param array $args Arguments to configure the checks.
*
* @return bool
*/
public function run_common_checks( array $args = [] ): bool {
if ( key_exists( 'do_not_optimize', $args ) && (bool) rocket_get_constant( 'DONOTROCKETOPTIMIZE' ) !== (bool) $args['do_not_optimize'] ) {
return false;
}
if ( key_exists( 'bypass', $args ) && rocket_bypass() !== (bool) $args['bypass'] ) {
return false;
}
if ( key_exists( 'option', $args ) && is_string( $args['option'] ) && ! (bool) $this->options->get( $args['option'], 0 ) ) {
return false;
}
if ( key_exists( 'password_protected', $args ) && $this->is_password_protected() !== (bool) $args['password_protected'] ) {
return false;
}
if ( key_exists( 'post_excluded', $args ) && is_string( $args['post_excluded'] ) && is_rocket_post_excluded_option( $args['post_excluded'] ) ) {
return false;
}
// Bailout if user is logged in.
if ( key_exists( 'logged_in', $args ) && is_user_logged_in() !== (bool) $args['logged_in'] ) {
return false;
}
return true;
}
/**
* Checks if on a single post and if it is password protected
*
* @since 3.11
*
* @return bool
*/
private function is_password_protected(): bool {
if ( ! is_singular() ) {
return false;
}
return post_password_required();
}
}
@@ -0,0 +1,14 @@
<?php
namespace WP_Rocket\Engine\Common\Context;
interface ContextInterface {
/**
* Determine if the action is allowed.
*
* @param array $data Data to pass to the context.
* @return bool
*/
public function is_allowed( array $data = [] ): bool;
}
@@ -0,0 +1,44 @@
<?php
namespace WP_Rocket\Engine\Common\ExtractCSS;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Common\Cache\FilesystemCache;
/**
* Service provider.
*/
class ServiceProvider extends AbstractServiceProvider {
/**
* The provided 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 = [
'lazyload_css_cache',
'common_extractcss_subscriber',
];
/**
* Registers items with the container
*
* @return void
*/
public function register() {
/**
* Background CSS cache folder.
*
* @param string $root Background CSS cache folder.
*/
$root = apply_filters( 'rocket_lazyload_css_cache_root', 'background-css' );
$this->getLeagueContainer()->add( 'lazyload_css_cache', FilesystemCache::class )
->addArgument( $root );
$this->getContainer()->share( 'common_extractcss_subscriber', Subscriber::class );
}
}
@@ -0,0 +1,166 @@
<?php
namespace WP_Rocket\Engine\Common\ExtractCSS;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Logger\LoggerAware;
use WP_Rocket\Logger\LoggerAwareInterface;
class Subscriber implements Subscriber_Interface, LoggerAwareInterface {
use RegexTrait;
use LoggerAware;
/**
* Returns an array of events that this subscriber wants to listen to.
*
* The array key is the event name. The value can be:
*
* * The method name
* * An array with the method name and priority
* * An array with the method name, priority and number of accepted arguments
*
* For instance:
*
* * array('hook_name' => 'method_name')
* * array('hook_name' => array('method_name', $priority))
* * array('hook_name' => array('method_name', $priority, $accepted_args))
* * array('hook_name' => array(array('method_name_1', $priority_1, $accepted_args_1)), array('method_name_2', $priority_2, $accepted_args_2)))
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_generate_lazyloaded_css' => [
[ 'extract_css_files_from_html', 11 ],
[ 'extract_inline_css_from_html', 14 ],
],
];
}
/**
* Extract CSS files from the HTML.
*
* @param array $data Data sent.
* @return array
*/
public function extract_css_files_from_html( array $data ): array {
if ( ! key_exists( 'html', $data ) ) {
$this->logger::notice(
'Extract CSS files bailed out',
[
'type' => 'extract_css',
'data' => $data,
]
);
return $data;
}
if ( ! key_exists( 'css_files', $data ) ) {
$data['css_files'] = [];
}
$css_links = [];
$html = $this->hide_comments( $data['html'] );
$link_styles = $this->find(
'<link\s+([^>]+[\s"\'])?href\s*=\s*[\'"]\s*?(?<url>[^\'"]+(?:\?[^\'"]*)?)\s*?[\'"]([^>]+)?\/?>',
$html,
'Uis'
);
foreach ( $link_styles as $style ) {
if (
! (bool) preg_match( '/rel=[\'"]?stylesheet[\'"]?/is', $style[0] )
&&
! ( (bool) preg_match( '/rel=[\'"]?preload[\'"]?/is', $style[0] ) && (bool) preg_match( '/as=[\'"]?style[\'"]?/is', $style[0] ) )
||
( strstr( $style['url'], '//fonts.googleapis.com/css' ) )
) {
$this->logger::notice(
"Skipped URL: {$style['url']}",
[
'type' => 'extract_css',
'data' => $style[0],
]
);
continue;
}
$css_links [] = $style['url'];
$this->logger::notice(
"Extracted URL: {$style['url']}",
[
'type' => 'extract_css',
'data' => $style[0],
]
);
}
$data['css_files'] = array_merge( $data['css_files'], $css_links );
return $data;
}
/**
* Extract inline CSS from the HTML.
*
* @param array $data Data sent.
* @return array
*/
public function extract_inline_css_from_html( array $data ): array {
if ( ! key_exists( 'html', $data ) ) {
$this->logger::notice(
'Extract CSS inline bailed out',
[
'type' => 'extract_css',
'data' => $data,
]
);
return $data;
}
if ( ! key_exists( 'css_inline', $data ) ) {
$data['css_inline'] = [];
}
$css_links = [];
$html = $this->hide_comments( $data['html'] );
$inline_styles = $this->find(
'<style(?<atts>.*)>(?<content>.*)<\/style\s*>',
$html
);
foreach ( $inline_styles as $style ) {
$content = trim( $style['content'] );
if ( empty( $content ) ) {
$this->logger::notice(
"Skipped Content: {$style['content']}",
[
'type' => 'extract_css',
'data' => $style[0],
]
);
continue;
}
$css_links [] = $content;
$this->logger::notice(
"Extracted Content: $content",
[
'type' => 'extract_css',
'data' => $style[0],
]
);
}
$data['css_inline'] = array_merge( $data['css_inline'], $css_links );
return $data;
}
}
@@ -0,0 +1,253 @@
<?php
declare( strict_types=1 );
namespace WP_Rocket\Engine\Common\Queue;
use ActionScheduler_Store;
use Exception;
use WP_Rocket\Logger\Logger;
abstract class AbstractASQueue implements QueueInterface {
/**
* Queue shared Group.
*
* @var string
*/
protected $group = 'rocket';
/**
* Enqueue an action to run one time, as soon as possible
*
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return int The action ID.
*/
public function add_async( $hook, $args = [] ) {
try {
if ( function_exists( 'as_enqueue_async_action' ) ) {
return as_enqueue_async_action( $hook, $args, $this->group );
}
return $this->schedule_single( time() + MINUTE_IN_SECONDS, $hook, $args );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
return 0;
}
}
/**
* Schedule an action to run once at some time in the future
*
* @param int $timestamp When the job will run.
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return int The action ID.
*/
public function schedule_single( $timestamp, $hook, $args = [] ) {
try {
return as_schedule_single_action( $timestamp, $hook, $args, $this->group );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
return 0;
}
}
/**
* Schedule a recurring action
*
* @param int $timestamp When the first instance of the job will run.
* @param int $interval_in_seconds How long to wait between runs.
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return int The action ID.
*/
public function schedule_recurring( $timestamp, $interval_in_seconds, $hook, $args = [] ) {
if ( $this->is_scheduled( $hook, $args ) ) {
// TODO: When v3.3.0 from Action Scheduler is commonly used use the array notation for status to reduce search queries to one.
$pending_actions = $this->search(
[
'hook' => $hook,
'status' => ActionScheduler_Store::STATUS_PENDING,
],
'ids'
);
if ( 1 < count( $pending_actions ) ) {
$this->cancel_all( $hook, $args );
return '';
}
$running_actions = $this->search(
[
'hook' => $hook,
'status' => ActionScheduler_Store::STATUS_RUNNING,
],
'ids'
);
if ( 1 === count( $pending_actions ) + count( $running_actions ) ) {
return '';
}
$this->cancel_all( $hook, $args );
}
try {
return as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $this->group );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
return 0;
}
}
/**
* Checks if the hook is scheduled.
*
* @param string $hook The hook to check.
* @param array $args Passed arguments.
*
* @return bool
*/
public function is_scheduled( $hook, $args = [] ) {
if ( ! function_exists( 'as_has_scheduled_action' ) ) {
return ! is_null( $this->get_next( $hook, $args ) );
}
try {
return as_has_scheduled_action( $hook, $args, $this->group );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
return false;
}
}
/**
* Schedule an action that recurs on a cron-like schedule.
*
* @param int $timestamp The schedule will start on or after this time.
* @param string $cron_schedule A cron-link schedule string.
* @see http://en.wikipedia.org/wiki/Cron
* * * * * * *
* ┬ ┬ ┬ ┬ ┬ ┬
* | | | | | |
* | | | | | + year [optional]
* | | | | +----- day of week (0 - 7) (Sunday=0 or 7)
* | | | +---------- month (1 - 12)
* | | +--------------- day of month (1 - 31)
* | +-------------------- hour (0 - 23)
* +------------------------- min (0 - 59)
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return int The action ID
*/
public function schedule_cron( $timestamp, $cron_schedule, $hook, $args = [] ) {
if ( $this->is_scheduled( $hook, $args ) ) {
return '';
}
try {
return as_schedule_cron_action( $timestamp, $cron_schedule, $hook, $args, $this->group );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
return 0;
}
}
/**
* Dequeue the next scheduled instance of an action with a matching hook (and optionally matching args and group).
*
* Any recurring actions with a matching hook should also be cancelled, not just the next scheduled action.
*
* While technically only the next instance of a recurring or cron action is unscheduled by this method, that will also
* prevent all future instances of that recurring or cron action from being run. Recurring and cron actions are scheduled
* in a sequence instead of all being scheduled at once. Each successive occurrence of a recurring action is scheduled
* only after the former action is run. As the next instance is never run, because it's unscheduled by this function,
* then the following instance will never be scheduled (or exist), which is effectively the same as being unscheduled
* by this method also.
*
* @param string $hook The hook that the job will trigger.
* @param array $args Args that would have been passed to the job.
*/
public function cancel( $hook, $args = [] ) {
try {
as_unschedule_action( $hook, $args, $this->group );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
}
}
/**
* Dequeue all actions with a matching hook (and optionally matching args and group) so no matching actions are ever run.
*
* @param string $hook The hook that the job will trigger.
* @param array $args Args that would have been passed to the job.
*/
public function cancel_all( $hook, $args = [] ) {
try {
as_unschedule_all_actions( $hook, $args, $this->group );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
}
}
/**
* Get the date and time for the next scheduled occurence of an action with a given hook
* (an optionally that matches certain args and group), if any.
*
* @param string $hook The hook that the job will trigger.
* @param array $args Filter to a hook with matching args that will be passed to the job when it runs.
* @return int|null The date and time for the next occurrence, or null if there is no pending, scheduled action for the given hook.
*/
public function get_next( $hook, $args = null ) {
try {
$next_timestamp = as_next_scheduled_action( $hook, $args, $this->group );
if ( is_numeric( $next_timestamp ) ) {
return $next_timestamp;
}
return null;
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
return null;
}
}
/**
* Find scheduled actions
*
* @param array $args Possible arguments, with their default values:
* 'hook' => '' - the name of the action that will be triggered
* 'args' => null - the args array that will be passed with the action
* 'date' => null - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
* 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='
* 'modified' => null - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
* 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='
* 'group' => '' - the group the action belongs to
* 'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING
* 'claimed' => null - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID
* 'per_page' => 5 - Number of results to return
* 'offset' => 0
* 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', or 'date'
* 'order' => 'ASC'.
*
* @param string $return_format OBJECT, ARRAY_A, or ids.
* @return array
*/
public function search( $args = [], $return_format = OBJECT ) {
try {
return as_get_scheduled_actions( $args, $return_format );
} catch ( Exception $exception ) {
Logger::error( $exception->getMessage(), [ 'Action Scheduler Queue' ] );
return [];
}
}
}
@@ -0,0 +1,102 @@
<?php
declare( strict_types=1 );
namespace WP_Rocket\Engine\Common\Queue;
class Cleaner extends \ActionScheduler_QueueCleaner {
/**
* The duration of clean Hour In seconds.
*
* @var int
*/
protected $hour_in_seconds = 60 * 60;
/**
* Store instance.
*
* @var \ActionScheduler_Store
*/
private $store = null;
/**
* Group name to be cleaned.
*
* @var string
*/
private $group;
/**
* Cleaner constructor.
*
* @param \ActionScheduler_Store|null $store The store instance.
* @param int $batch_size The batch size.
* @param string $group Current queue group.
*/
public function __construct( \ActionScheduler_Store $store = null, $batch_size = 20, $group = '' ) {
parent::__construct( $store, $batch_size );
$this->store = $store ? $store : \ActionScheduler_Store::instance();
$this->group = $group;
}
/**
* Overrides the base method of action scheduler to do the clean process for our actions only.
*
* @return void
*/
public function delete_old_actions() {
$lifespan = (int) apply_filters( 'action_scheduler_retention_period', $this->hour_in_seconds );// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
/**
* Filters the retention period for our tasks only.
*
* @since 3.11.0.5
*
* @param int $lifespan Lifespan in seconds.
*
* @return int
*/
$lifespan = (int) apply_filters( 'rocket_action_scheduler_retention_period', $lifespan, $this->group );
$cutoff = as_get_datetime_object( $lifespan . ' seconds ago' );
$statuses_to_purge = [
\ActionScheduler_Store::STATUS_COMPLETE,
\ActionScheduler_Store::STATUS_CANCELED,
\ActionScheduler_Store::STATUS_FAILED,
];
foreach ( $statuses_to_purge as $status ) {
$actions_to_delete = $this->store->query_actions(
[
'status' => $status,
'modified' => $cutoff,
'modified_compare' => '<=',
'per_page' => $this->get_batch_size(),
'orderby' => 'none',
'group' => $this->group,
]
);
foreach ( $actions_to_delete as $action_id ) {
try {
$this->store->delete_action( $action_id );
} catch ( \Exception $e ) {
/**
* Notify 3rd party code of exceptions when deleting a completed action older than the retention period
*
* This hook provides a way for 3rd party code to log or otherwise handle exceptions relating to their
* actions.
*
* @since 2.0.0
*
* @param int $action_id The scheduled actions ID in the data store
* @param \Exception $e The exception thrown when attempting to delete the action from the data store
* @param int $lifespan The retention period, in seconds, for old actions
* @param int $count_of_actions_to_delete The number of old actions being deleted in this batch
*/
do_action( 'action_scheduler_failed_old_action_deletion', $action_id, $e, $lifespan, count( $actions_to_delete ) );// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
}
}
}
}
}
@@ -0,0 +1,118 @@
<?php
declare( strict_types=1 );
namespace WP_Rocket\Engine\Common\Queue;
interface QueueInterface {
/**
* Enqueue an action to run one time, as soon as possible
*
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return string The action ID
*/
public function add_async( $hook, $args = [] );
/**
* Schedule an action to run once at some time in the future
*
* @param int $timestamp When the job will run.
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return string The action ID
*/
public function schedule_single( $timestamp, $hook, $args = [] );
/**
* Schedule a recurring action
*
* @param int $timestamp When the first instance of the job will run.
* @param int $interval_in_seconds How long to wait between runs.
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return string The action ID
*/
public function schedule_recurring( $timestamp, $interval_in_seconds, $hook, $args = [] );
/**
* Checks if the hook is scheduled.
*
* @param string $hook The hook to check.
* @param array $args Passed arguments.
*
* @return bool
*/
public function is_scheduled( $hook, $args = [] );
/**
* Schedule an action that recurs on a cron-like schedule.
*
* @param int $timestamp The schedule will start on or after this time.
* @param string $cron_schedule A cron-link schedule string.
* @see http://en.wikipedia.org/wiki/Cron
* * * * * * *
* ┬ ┬ ┬ ┬ ┬ ┬
* | | | | | |
* | | | | | + year [optional]
* | | | | +----- day of week (0 - 7) (Sunday=0 or 7)
* | | | +---------- month (1 - 12)
* | | +--------------- day of month (1 - 31)
* | +-------------------- hour (0 - 23)
* +------------------------- min (0 - 59)
* @param string $hook The hook to trigger.
* @param array $args Arguments to pass when the hook triggers.
* @return string The action ID
*/
public function schedule_cron( $timestamp, $cron_schedule, $hook, $args = [] );
/**
* Dequeue the next scheduled instance of an action with a matching hook (and optionally matching args and group).
*
* Any recurring actions with a matching hook should also be cancelled, not just the next scheduled action.
*
* @param string $hook The hook that the job will trigger.
* @param array $args Args that would have been passed to the job.
*/
public function cancel( $hook, $args = [] );
/**
* Dequeue all actions with a matching hook (and optionally matching args and group) so no matching actions are ever run.
*
* @param string $hook The hook that the job will trigger.
* @param array $args Args that would have been passed to the job.
*/
public function cancel_all( $hook, $args = [] );
/**
* Get the date and time for the next scheduled occurence of an action with a given hook
* (an optionally that matches certain args and group), if any.
*
* @param string $hook The hook that the job will trigger.
* @param array $args Filter to a hook with matching args that will be passed to the job when it runs.
* @return int|null The date and time for the next occurrence, or null if there is no pending, scheduled action for the given hook
*/
public function get_next( $hook, $args = null );
/**
* Find scheduled actions.
*
* @param array $args Possible arguments, with their default values.
* 'hook' => '' - the name of the action that will be triggered.
* 'args' => null - the args array that will be passed with the action.
* 'date' => null - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
* 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='.
* 'modified' => null - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
* 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='.
* 'group' => '' - the group the action belongs to.
* 'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING.
* 'claimed' => null - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID.
* 'per_page' => 5 - Number of results to return.
* 'offset' => 0.
* 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', or 'date'.
* 'order' => 'ASC'.
* @param string $return_format OBJECT, ARRAY_A, or ids.
* @return array
*/
public function search( $args = [], $return_format = OBJECT );
}
@@ -0,0 +1,279 @@
<?php
declare( strict_types=1 );
namespace WP_Rocket\Engine\Common\Queue;
use WP_Rocket\Logger\Logger;
use ActionScheduler_Abstract_QueueRunner;
class RUCSSQueueRunner extends ActionScheduler_Abstract_QueueRunner {
/**
* Cron hook name.
*/
const WP_CRON_HOOK = 'action_scheduler_run_queue_rucss';
/**
* Cron schedule interval.
*/
const WP_CRON_SCHEDULE = 'every_minute';
/**
* Async Request Queue Runner instance.
* We used the default one from AS.
*
* @var \ActionScheduler_AsyncRequest_QueueRunner Instance.
*/
protected $async_request;
/**
* Current runner instance.
*
* @var RUCSSQueueRunner Instance.
*/
private static $runner = null;
/**
* Current queue group.
*
* @var string
*/
private $group = 'rocket-rucss';
/**
* Get singleton instance.
*
* @return RUCSSQueueRunner Instance.
*/
public static function instance() {
if ( empty( self::$runner ) ) {
self::$runner = new RUCSSQueueRunner();
}
return self::$runner;
}
/**
* ActionScheduler_QueueRunner constructor.
*
* @param \ActionScheduler_Store|null $store Store Instance.
* @param \ActionScheduler_FatalErrorMonitor|null $monitor Fatal Error monitor instance.
* @param Cleaner|null $cleaner Cleaner instance.
* @param \ActionScheduler_AsyncRequest_QueueRunner|null $async_request Async Request Queue Runner instance.
*/
public function __construct( \ActionScheduler_Store $store = null, \ActionScheduler_FatalErrorMonitor $monitor = null, Cleaner $cleaner = null, \ActionScheduler_AsyncRequest_QueueRunner $async_request = null ) {
if ( is_null( $cleaner ) ) {
/**
* Filters the clean batch size.
*
* @since 3.11.0.5
*
* @param int $batch_size Batch size.
*
* @return int
*/
$batch_size = (int) apply_filters( 'rocket_action_scheduler_clean_batch_size', 100, $this->group );
$cleaner = new Cleaner( $store, $batch_size, $this->group );
}
parent::__construct( $store, $monitor, $cleaner );
if ( is_null( $async_request ) ) {
$async_request = new \ActionScheduler_AsyncRequest_QueueRunner( $this->store );
}
$this->async_request = $async_request;
}
/**
* Initialize the queue runner.
*/
public function init() {
// phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval
add_filter( 'cron_schedules', [ self::instance(), 'add_wp_cron_schedule' ] );
// Check for and remove any WP Cron hook scheduled by Action Scheduler < 3.0.0, which didn't include the $context param.
$next_timestamp = wp_next_scheduled( self::WP_CRON_HOOK );
if ( $next_timestamp ) {
wp_unschedule_event( $next_timestamp, self::WP_CRON_HOOK );
}
$cron_context = [ 'WP Cron' ];
if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) {
$schedule = apply_filters( 'rocket_action_scheduler_run_schedule', self::WP_CRON_SCHEDULE );
wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK, $cron_context );
}
add_action( self::WP_CRON_HOOK, [ self::instance(), 'run' ] );
$this->hook_dispatch_async_request();
}
/**
* Hook check for dispatching an async request.
*/
public function hook_dispatch_async_request() {
add_action( 'shutdown', [ $this, 'maybe_dispatch_async_request' ] );
}
/**
* Unhook check for dispatching an async request.
*/
public function unhook_dispatch_async_request() {
remove_action( 'shutdown', [ $this, 'maybe_dispatch_async_request' ] );
}
/**
* Check if we should dispatch an async request to process actions.
*
* This method is attached to 'shutdown', so is called frequently. To avoid slowing down
* the site, it mitigates the work performed in each request by:
* 1. checking if it's in the admin context and then
* 2. haven't run on the 'shutdown' hook within the lock time (60 seconds by default)
* 3. haven't exceeded the number of allowed batches.
*
* The order of these checks is important, because they run from a check on a value:
* 1. in memory - is_admin() maps to $GLOBALS or the WP_ADMIN constant
* 2. in memory - transients use autoloaded options by default
* 3. from a database query - has_maximum_concurrent_batches() run the query
* $this->store->get_claim_count() to find the current number of claims in the DB.
*
* If all of these conditions are met, then we request an async runner check whether it
* should dispatch a request to process pending actions.
*/
public function maybe_dispatch_async_request() {
if ( is_admin() && ! \ActionScheduler::lock()->is_locked( 'async-request-runner' ) ) {
// Only start an async queue at most once every 60 seconds.
\ActionScheduler::lock()->set( 'async-request-runner' );
$this->async_request->maybe_dispatch();
}
}
/**
* Process actions in the queue. Attached to self::WP_CRON_HOOK i.e. 'action_scheduler_run_queue'
*
* The $context param of this method defaults to 'WP Cron', because prior to Action Scheduler 3.0.0
* that was the only context in which this method was run, and the self::WP_CRON_HOOK hook had no context
* passed along with it. New code calling this method directly, or by triggering the self::WP_CRON_HOOK,
* should set a context as the first parameter. For an example of this, refer to the code seen in
*
* @see ActionScheduler_AsyncRequest_QueueRunner::handle()
*
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
* Generally, this should be capitalised and not localised as it's a proper noun.
* @return int The number of actions processed.
*/
public function run( $context = 'WP Cron' ) {
\ActionScheduler_Compatibility::raise_memory_limit();
\ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() );
do_action( 'action_scheduler_before_process_queue' );// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
$this->run_cleanup();
$processed_actions = 0;
if ( false === $this->has_maximum_concurrent_batches() ) {
$batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
do {
$processed_actions_in_batch = $this->do_batch( $batch_size, $context );
$processed_actions += $processed_actions_in_batch;
} while ( $processed_actions_in_batch > 0 && ! $this->batch_limits_exceeded( $processed_actions ) ); // keep going until we run out of actions, time, or memory.
}
do_action( 'action_scheduler_after_process_queue' );// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
return $processed_actions;
}
/**
* Process a batch of actions pending in the queue.
*
* Actions are processed by claiming a set of pending actions then processing each one until either the batch
* size is completed, or memory or time limits are reached, defined by @see $this->batch_limits_exceeded().
*
* @param int $size The maximum number of actions to process in the batch.
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
* Generally, this should be capitalised and not localised as it's a proper noun.
* @return int The number of actions processed.
*/
protected function do_batch( $size = 100, $context = '' ) {
try {
$claim = $this->store->stake_claim( $size, null, [], $this->group );
$this->monitor->attach( $claim );
$processed_actions = 0;
foreach ( $claim->get_actions() as $action_id ) {
// bail if we lost the claim.
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ), true ) ) {
break;
}
$this->process_action( $action_id, $context );
++$processed_actions;
if ( $this->batch_limits_exceeded( $processed_actions ) ) {
break;
}
}
$this->store->release_claim( $claim );
$this->monitor->detach();
$this->clear_caches();
$this->reset_group();
return $processed_actions;
} catch ( \Exception $exception ) {
Logger::debug( $exception->getMessage() );
$this->reset_group();
return 0;
}
}
/**
* Reset group in store's claim filter.
*
* @return void
*/
private function reset_group() {
if ( ! method_exists( $this->store, 'set_claim_filter' ) ) {
return;
}
$this->store->set_claim_filter( 'group', '' );
}
/**
* Running large batches can eat up memory, as WP adds data to its object cache.
*
* If using a persistent object store, this has the side effect of flushing that
* as well, so this is disabled by default. To enable:
*
* add_filter( 'action_scheduler_queue_runner_flush_cache', '__return_true' );
*/
protected function clear_caches() {
if ( ! wp_using_ext_object_cache() || apply_filters( 'action_scheduler_queue_runner_flush_cache', false ) ) {// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
wp_cache_flush();
}
}
/**
* Add the cron schedule.
*
* @param array $schedules Array of current schedules.
*
* @return array
*/
public function add_wp_cron_schedule( $schedules ) {
if ( isset( $schedules['every_minute'] ) ) {
return $schedules;
}
$schedules['every_minute'] = [
'interval' => 60, // in seconds.
'display' => __( 'Every minute', 'rocket' ),
];
return $schedules;
}
/**
* Get the number of concurrent batches a runner allows.
*
* @return int
*/
public function get_allowed_concurrent_batches() {
return 2;
}
}