Commit inicial powerservice
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'FlywheelNginxCompat' ) ) {
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'hosting/flywheel.php';
|
||||
}
|
||||
|
||||
if ( defined( 'DB_HOST' ) && strpos( DB_HOST, '.wpserveur.net' ) !== false ) {
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'hosting/wp-serveur.php';
|
||||
}
|
||||
|
||||
if ( rocket_is_plugin_active( 'sg-cachepress/sg-cachepress.php' ) ) {
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'hosting/siteground.php';
|
||||
}
|
||||
|
||||
if ( defined( 'PL_INSTANCE_REF' ) && class_exists( '\Presslabs\Cache\CacheHandler' ) && file_exists( WP_CONTENT_DIR . '/advanced-cache.php' ) ) {
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'hosting/presslabs.php';
|
||||
}
|
||||
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'hosting/pagely.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'hosting/nginx.php';
|
||||
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/slider/meta-slider.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/slider/soliloquy.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/i18n/polylang.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/aelia-currencyswitcher.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/aelia-prices-by-country.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/aelia-tax-display-by-country.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/woocommerce-multilingual.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/woocommerce-currency-converter-widget.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/edd-software-licencing.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/easy-digital-downloads.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/ithemes-exchange.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/jigoshop.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/wpshop.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/ecommerce/give.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/autoptimize.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/envira-gallery.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/cookies/cookie-notice.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/cookies/uk-cookie-consent.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/cookies/eu-cookie-law.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/cookies/weepie-cookie-allow.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/cookies/gdpr.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/rating/kk-star-ratings.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/rating/wp-postratings.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/wp-print.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/buddypress.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/disqus.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/custom-login.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/mobile/wp-appkit.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/seo/premium-seo-pack.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/wp-rest-api.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/page-builder/thrive-visual-editor.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/page-builder/visual-composer.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/security/secupress.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/security/sf-move-login.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/security/wps-hide-login.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/varnish-http-purge.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/thrive-leads.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/mailchimp.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/advanced-custom-fields.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/wp-offload-s3.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/wp-offload-s3-assets.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/s2member.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/sumome.php';
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'plugins/nginx-helper.php';
|
||||
|
||||
require WP_ROCKET_3RD_PARTY_PATH . 'themes/studiopress.php';
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Changes the text on the Varnish one-click block.
|
||||
*
|
||||
* @since 3.0
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $settings Field settings data.
|
||||
*
|
||||
* @return array modified field settings data.
|
||||
*/
|
||||
function rocket_flywheel_varnish_field( $settings ) {
|
||||
$settings['varnish_auto_purge']['title'] = sprintf(
|
||||
// Translators: %s = Hosting name.
|
||||
__( 'Your site is hosted on %s, we have enabled Varnish auto-purge for compatibility.', 'rocket' ),
|
||||
'Flywheel'
|
||||
);
|
||||
|
||||
return $settings;
|
||||
}
|
||||
add_filter( 'rocket_varnish_field_settings', 'rocket_flywheel_varnish_field' );
|
||||
|
||||
add_filter( 'rocket_display_input_varnish_auto_purge', '__return_false' );
|
||||
|
||||
/**
|
||||
* Allow to purge Varnish on Flywheel websites
|
||||
*
|
||||
* @since 2.6.8
|
||||
*/
|
||||
add_filter( 'do_rocket_varnish_http_purge', '__return_true' );
|
||||
add_filter( 'do_rocket_generate_caching_files', '__return_false' );
|
||||
|
||||
// Prevent mandatory cookies on hosting with server cache.
|
||||
add_filter( 'rocket_cache_mandatory_cookies', '__return_empty_array', PHP_INT_MAX );
|
||||
|
||||
/**
|
||||
* Set up the right Varnish IP for Flywheel
|
||||
*
|
||||
* @since 2.6.8
|
||||
* @param array $varnish_ip Varnish IP.
|
||||
*/
|
||||
function rocket_varnish_ip_on_flywheel( $varnish_ip ) {
|
||||
$varnish_ip[] = '127.0.0.1';
|
||||
|
||||
return $varnish_ip;
|
||||
}
|
||||
add_filter( 'rocket_varnish_ip', 'rocket_varnish_ip_on_flywheel' );
|
||||
|
||||
/**
|
||||
* Remove WP Rocket functions on WP core action hooks to prevent triggering a double cache clear.
|
||||
*
|
||||
* @since 3.3.1
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_flywheel_remove_partial_purge_hooks() {
|
||||
// WP core action hooks rocket_clean_post() gets hooked into.
|
||||
$clean_post_hooks = [
|
||||
// Disables the refreshing of partial cache when content is edited.
|
||||
'wp_trash_post',
|
||||
'delete_post',
|
||||
'clean_post_cache',
|
||||
'wp_update_comment_count',
|
||||
];
|
||||
|
||||
// Remove rocket_clean_post() from core action hooks.
|
||||
array_map(
|
||||
function ( $hook ) {
|
||||
remove_action( $hook, 'rocket_clean_post' );
|
||||
},
|
||||
$clean_post_hooks
|
||||
);
|
||||
|
||||
remove_filter( 'rocket_clean_files', 'rocket_clean_files_users' );
|
||||
}
|
||||
add_action( 'wp_rocket_loaded', 'rocket_flywheel_remove_partial_purge_hooks' );
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with an usual NGINX configuration which include:
|
||||
* try_files $uri $uri/ /index.php?q=$uri&$args
|
||||
*
|
||||
* @since 2.3.9
|
||||
*
|
||||
* @param array $query_strings Array of query strings to cache.
|
||||
*
|
||||
* @return array Updated array of query strings.
|
||||
*/
|
||||
function rocket_better_nginx_compatibility( $query_strings ) {
|
||||
global $is_nginx;
|
||||
|
||||
if ( $is_nginx ) {
|
||||
$query_strings[] = 'q';
|
||||
}
|
||||
|
||||
return $query_strings;
|
||||
}
|
||||
add_filter( 'rocket_cache_query_strings', 'rocket_better_nginx_compatibility' );
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Call the cache server to purge the cache with Pagely hosting.
|
||||
*
|
||||
* @since 2.5.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clean_pagely() {
|
||||
if ( class_exists( 'PagelyCachePurge' ) ) {
|
||||
$purger = new PagelyCachePurge();
|
||||
$purger->purgeAll();
|
||||
}
|
||||
}
|
||||
add_action( 'after_rocket_clean_domain', 'rocket_clean_pagely' );
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
require_once WP_CONTENT_DIR . '/advanced-cache.php';
|
||||
|
||||
add_action( 'pl_pre_cache_refresh', 'rocket_clean_files', 0 );
|
||||
add_filter( 'rocket_display_varnish_options_tab', '__return_false' );
|
||||
add_filter( 'do_rocket_generate_caching_files', '__return_false', PHP_INT_MAX );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', '__return_empty_array', PHP_INT_MAX );
|
||||
add_action( 'after_rocket_clean_home', 'rocket_pl_clean_home', 10, 2 );
|
||||
add_action( 'after_rocket_clean_file', 'rocket_pl_clean_post', 2 );
|
||||
add_action( 'pl_pre_url_button_cache_refresh', 'rocket_clean_files' );
|
||||
add_action( 'wp_rocket_loaded', 'rocket_pl_remove_partial_purge_hooks' );
|
||||
|
||||
/**
|
||||
* We clear the cache only on the post, homepage and listings when creating/updating/deleting posts.
|
||||
*
|
||||
* @since 3.3
|
||||
*
|
||||
* @param object $post The Post object itself for which the action occured.
|
||||
* @param array $permalink A list of permalinks to be flushed from cache.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_pl_clean_post( $post = false, $permalink = false ) {
|
||||
if ( ! $post || ! $permalink ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cache_handler = new \Presslabs\Cache\CacheHandler();
|
||||
|
||||
$cache_handler->invalidate_url( $permalink[0], true );
|
||||
$cache_handler->invalidate_url( home_url( '/' ), true );
|
||||
$cache_handler->purge_cache( 'listing' );
|
||||
}
|
||||
|
||||
/**
|
||||
* We clear the cache for the homepage URL when using "Purge this URL" from the admin bar on the front end.
|
||||
*
|
||||
* @since 3.3
|
||||
*
|
||||
* @param string $root WP Rocket root cache path.
|
||||
* @param string $lang Current language.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_pl_clean_home( $root = false, $lang = false ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
|
||||
if ( ! $post || ! $permalink ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cache_handler = new \Presslabs\Cache\CacheHandler();
|
||||
$cache_handler->invalidate_url( home_url( '/' ), true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove WP Rocket functions on WP core action hooks to prevent triggering a double cache clear.
|
||||
*
|
||||
* @since 3.3
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_pl_remove_partial_purge_hooks() {
|
||||
// WP core action hooks rocket_clean_post() gets hooked into.
|
||||
$clean_post_hooks = [
|
||||
// Disables the refreshing of partial cache when content is edited.
|
||||
'wp_trash_post',
|
||||
'delete_post',
|
||||
'clean_post_cache',
|
||||
'wp_update_comment_count',
|
||||
];
|
||||
// Remove rocket_clean_post() from core action hooks.
|
||||
array_map(
|
||||
function ( $hook ) {
|
||||
remove_action( $hook, 'rocket_clean_post' );
|
||||
},
|
||||
$clean_post_hooks
|
||||
);
|
||||
remove_filter( 'rocket_clean_files', 'rocket_clean_files_users' );
|
||||
}
|
||||
|
||||
if ( ! defined( 'DISABLE_CDN_OFFLOAD' ) && defined( 'PL_CDN_HOST' ) ) {
|
||||
/**
|
||||
* If we have CDN enabled we'll add our HOST to the list.
|
||||
*
|
||||
* @since 3.3
|
||||
*
|
||||
* @param array $hosts Array of CDN hosts.
|
||||
*
|
||||
* @return array Updated array of CDN hosts
|
||||
*/
|
||||
function rocket_add_pl_cdn( $hosts ) {
|
||||
$hosts[] = constant( 'PL_CDN_HOST' );
|
||||
return $hosts;
|
||||
}
|
||||
add_filter( 'rocket_cdn_cnames', 'rocket_add_pl_cdn', 1 );
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Returns the current version of the SG Optimizer plugin.
|
||||
*
|
||||
* @since 3.2.3.1
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @return string version number.
|
||||
*/
|
||||
function rocket_get_sg_optimizer_version() {
|
||||
static $version;
|
||||
|
||||
if ( isset( $version ) ) {
|
||||
return $version;
|
||||
}
|
||||
|
||||
$sg_optimizer = get_file_data( WP_PLUGIN_DIR . '/sg-cachepress/sg-cachepress.php', [ 'Version' => 'Version' ] );
|
||||
$version = $sg_optimizer['Version'];
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if SG Optimizer Supercache is active.
|
||||
*
|
||||
* @since 3.2.3.1
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
function rocket_is_supercacher_active() {
|
||||
if ( ! version_compare( rocket_get_sg_optimizer_version(), '5.0' ) < 0 ) {
|
||||
global $sg_cachepress_environment;
|
||||
|
||||
return isset( $sg_cachepress_environment ) && $sg_cachepress_environment instanceof SG_CachePress_Environment && $sg_cachepress_environment->cache_is_enabled();
|
||||
}
|
||||
|
||||
return (bool) get_option( 'siteground_optimizer_enable_cache', 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Call the cache server to purge the cache with SuperCacher (SiteGround).
|
||||
*
|
||||
* @since 2.3
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clean_supercacher() {
|
||||
if ( ! rocket_is_supercacher_active() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! version_compare( rocket_get_sg_optimizer_version(), '5.0' ) < 0 ) {
|
||||
SiteGround_Optimizer\Supercacher\Supercacher::purge_cache();
|
||||
} elseif ( isset( $sg_cachepress_supercacher ) && $sg_cachepress_supercacher instanceof SG_CachePress_Supercacher ) {
|
||||
$sg_cachepress_supercacher->purge_cache();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean WP Rocket cache when cleaning SG cache
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_sg_clear_cache() {
|
||||
if ( empty( $_GET['_wpnonce'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'sg-cachepress-purge' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'rocket_purge_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
rocket_clean_domain();
|
||||
}
|
||||
|
||||
if ( rocket_is_supercacher_active() ) {
|
||||
add_action( 'admin_post_sg-cachepress-purge', 'rocket_sg_clear_cache', 0 );
|
||||
add_action( 'after_rocket_clean_domain', 'rocket_clean_supercacher' );
|
||||
add_filter( 'rocket_display_varnish_options_tab', '__return_false' );
|
||||
// Prevent mandatory cookies on hosting with server cache.
|
||||
add_filter( 'rocket_cache_mandatory_cookies', '__return_empty_array', PHP_INT_MAX );
|
||||
|
||||
/**
|
||||
* Force WP Rocket caching on SG Optimizer versions before 4.0.5.
|
||||
*
|
||||
* @since 3.0.4
|
||||
* @author Arun Basil Lal
|
||||
*
|
||||
* @link https://github.com/wp-media/wp-rocket/issues/925
|
||||
*/
|
||||
if ( version_compare( rocket_get_sg_optimizer_version(), '4.0.5' ) < 0 ) {
|
||||
add_filter( 'do_rocket_generate_caching_files', '__return_true', 11 );
|
||||
}
|
||||
|
||||
if ( version_compare( rocket_get_sg_optimizer_version(), '5.0' ) < 0 ) {
|
||||
add_action( 'wp_ajax_sg-cachepress-purge', 'rocket_sg_clear_cache', 0 );
|
||||
} else {
|
||||
add_action( 'wp_ajax_admin_bar_purge_cache', 'rocket_sg_clear_cache', 0 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Allow to purge Varnish on WP Serveur websites.
|
||||
*
|
||||
* @since 2.6.11
|
||||
*/
|
||||
add_filter( 'do_rocket_varnish_http_purge', '__return_true' );
|
||||
// Prevent mandatory cookies on hosting with server cache.
|
||||
add_filter( 'rocket_cache_mandatory_cookies', '__return_empty_array', PHP_INT_MAX );
|
||||
|
||||
/**
|
||||
* Changes the text on the Varnish one-click block.
|
||||
*
|
||||
* @since 3.0
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $settings Field settings data.
|
||||
*
|
||||
* @return array modified field settings data.
|
||||
*/
|
||||
function rocket_wpserveur_varnish_field( $settings ) {
|
||||
$settings['varnish_auto_purge']['title'] = sprintf(
|
||||
// Translators: %s = Hosting name.
|
||||
__( 'Your site is hosted on %s, we have enabled Varnish auto-purge for compatibility.', 'rocket' ),
|
||||
'WP Serveur'
|
||||
);
|
||||
|
||||
return $settings;
|
||||
}
|
||||
add_filter( 'rocket_varnish_field_settings', 'rocket_wpserveur_varnish_field' );
|
||||
|
||||
add_filter( 'rocket_display_input_varnish_auto_purge', '__return_false' );
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Clear cache when ACF options page is updated.
|
||||
*
|
||||
* @since 2.10.7
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param string $post_id ACF options page ID is 'options'.
|
||||
*/
|
||||
function rocket_clear_cache_on_acf_options_save( $post_id ) {
|
||||
if ( 'options' === $post_id ) {
|
||||
rocket_clean_domain();
|
||||
}
|
||||
}
|
||||
add_action( 'acf/save_post', 'rocket_clear_cache_on_acf_options_save' );
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'autoptimizeCache' ) ) :
|
||||
/**
|
||||
* Deactivate WP Rocket lazyload if Autoptimize lazyload is enabled
|
||||
*
|
||||
* @since 3.3.4
|
||||
*
|
||||
* @param string $old_value Previous autoptimize option value.
|
||||
* @param string $value New autoptimize option value.
|
||||
* @return void
|
||||
*/
|
||||
function rocket_maybe_deactivate_lazyload( $old_value, $value ) {
|
||||
if ( empty( $old_value['autoptimize_imgopt_checkbox_field_3'] ) && ! empty( $value['autoptimize_imgopt_checkbox_field_3'] ) ) {
|
||||
update_rocket_option( 'lazyload', 0 );
|
||||
}
|
||||
}
|
||||
add_action( 'update_option_autoptimize_imgopt_settings', 'rocket_maybe_deactivate_lazyload', 10, 2 );
|
||||
|
||||
/**
|
||||
* Improvement with Autoptimize: clear the cache when Autoptimize's cache is cleared
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
add_action( 'autoptimize_action_cachepurged', 'rocket_clean_domain' );
|
||||
endif;
|
||||
|
||||
if ( class_exists( 'autoptimizeConfig' ) ) :
|
||||
/**
|
||||
* Deactivate WP Rocket CSS Minification if Autoptimize CSS minification is enabled
|
||||
*
|
||||
* @since 2.9.5
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param string $old_value Previous autoptimize option value.
|
||||
* @param string $value New autoptimize option value.
|
||||
*/
|
||||
function rocket_maybe_deactivate_minify_css( $old_value, $value ) {
|
||||
if ( $value !== $old_value && 'on' === $value ) {
|
||||
update_rocket_option( 'minify_css', 0 );
|
||||
}
|
||||
}
|
||||
add_action( 'update_option_autoptimize_css', 'rocket_maybe_deactivate_minify_css', 10, 2 );
|
||||
|
||||
/**
|
||||
* Deactivate WP Rocket JS Minification if Autoptimize JS minification is enabled
|
||||
*
|
||||
* @since 2.9.5
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param string $old_value Previous autoptimize option value.
|
||||
* @param string $value New autoptimize option value.
|
||||
*/
|
||||
function rocket_maybe_deactivate_minify_js( $old_value, $value ) {
|
||||
if ( $value !== $old_value && 'on' === $value ) {
|
||||
update_rocket_option( 'minify_js', 0 );
|
||||
update_rocket_option( 'minify_concatenate_js', 0 );
|
||||
}
|
||||
}
|
||||
add_action( 'update_option_autoptimize_js', 'rocket_maybe_deactivate_minify_js', 10, 2 );
|
||||
|
||||
/**
|
||||
* Deactivate WP Rocket async CSS if Autoptimize async CSS is enabled
|
||||
*
|
||||
* @since 2.10
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param string $old_value Previous autoptimize option value.
|
||||
* @param string $value New autoptimize option value.
|
||||
*/
|
||||
function rocket_maybe_deactivate_css_defer( $old_value, $value ) {
|
||||
if ( $value !== $old_value && 'on' === $value ) {
|
||||
update_rocket_option( 'autoptimize_css_defer', 0 );
|
||||
}
|
||||
}
|
||||
add_action( 'update_option_autoptimize_css_defer', 'rocket_maybe_deactivate_css_defer', 10, 2 );
|
||||
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Disable WP Rocket minification options when activating Autoptimize and values are already in the database.
|
||||
*
|
||||
* @since 2.9.5
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_activate_autoptimize() {
|
||||
if ( 'on' === get_option( 'autoptimize_css' ) ) {
|
||||
update_rocket_option( 'minify_css', 0 );
|
||||
}
|
||||
|
||||
if ( 'on' === get_option( 'autoptimize_js' ) ) {
|
||||
update_rocket_option( 'minify_js', 0 );
|
||||
update_rocket_option( 'minify_concatenate_js', 0 );
|
||||
}
|
||||
|
||||
if ( 'on' === get_option( 'autoptimize_css_defer' ) ) {
|
||||
update_rocket_option( 'async_css', 0 );
|
||||
}
|
||||
|
||||
$lazyload = get_option( 'autoptimize_imgopt_settings' );
|
||||
|
||||
if ( ! empty( $lazyload['autoptimize_imgopt_checkbox_field_3'] ) ) {
|
||||
update_rocket_option( 'lazyload', 0 );
|
||||
}
|
||||
}
|
||||
add_action( 'activate_autoptimize/autoptimize.php', 'rocket_activate_autoptimize', 11 );
|
||||
|
||||
/**
|
||||
* Disable WP Rocket lazyload fields if Autoptimize lazyload is enabled
|
||||
*
|
||||
* @since 3.3.4
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
function rocket_maybe_disable_lazyload() {
|
||||
$lazyload = get_option( 'autoptimize_imgopt_settings' );
|
||||
|
||||
if ( is_plugin_active( 'autoptimize/autoptimize.php' ) && ! empty( $lazyload['autoptimize_imgopt_checkbox_field_3'] ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable WP Rocket CSS minification field if Autoptimize CSS minification is enabled
|
||||
*
|
||||
* @since 2.9.5
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @return bool|null True if it is active
|
||||
*/
|
||||
function rocket_maybe_disable_minify_css() {
|
||||
if ( is_plugin_active( 'autoptimize/autoptimize.php' ) && 'on' === get_option( 'autoptimize_css' ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable WP Rocket JS minification field if Autoptimize JS minification is enabled
|
||||
*
|
||||
* @since 2.9.5
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @return bool|null True if it is active
|
||||
*/
|
||||
function rocket_maybe_disable_minify_js() {
|
||||
if ( is_plugin_active( 'autoptimize/autoptimize.php' ) && 'on' === get_option( 'autoptimize_js' ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable WP Rocket async CSS field if Autoptimize async CSS is enabled
|
||||
*
|
||||
* @since 2.10
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @return bool|null True if it is active
|
||||
*/
|
||||
function rocket_maybe_disable_async_css() {
|
||||
if ( is_plugin_active( 'autoptimize/autoptimize.php' ) && 'on' === get_option( 'autoptimize_css_defer' ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'BuddyPress' ) ) :
|
||||
/**
|
||||
* Conflict with BuddyPress: don't apply LazyLoad on BuddyPress profil pages & group creation
|
||||
*
|
||||
* @since 2.8.15 Improve checks for user profile & disable for cover images
|
||||
* @since 2.6.9
|
||||
*/
|
||||
if ( function_exists( 'bp_is_user_profile' ) ) :
|
||||
/**
|
||||
* Prevent lazyload if on a BuddyPress profil page
|
||||
*
|
||||
* @param Bool $run_filter Do lazyload value.
|
||||
* @return Bool False if on a BuddyPress profil page, initial value otherwise
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_buddypress_profil_pages( $run_filter ) {
|
||||
if ( bp_is_user_profile() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $run_filter;
|
||||
}
|
||||
add_filter( 'do_rocket_lazyload', 'rocket_deactivate_lazyload_on_buddypress_profil_pages' );
|
||||
add_filter( 'do_rocket_lazyload_iframes', 'rocket_deactivate_lazyload_on_buddypress_profil_pages' );
|
||||
endif;
|
||||
|
||||
if ( function_exists( 'bp_is_group_creation_step' ) && function_exists( 'bp_is_group_admin_screen' ) ) :
|
||||
/**
|
||||
* Prevent lazyload if on a BuddyPress group creation page
|
||||
*
|
||||
* @param Bool $run_filter Do lazyload value.
|
||||
* @return Bool False if on a BuddyPress profil page, initial value otherwise
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_buddypress_group_pages( $run_filter ) {
|
||||
if ( bp_is_group_creation_step( 'group-avatar' ) || bp_is_group_creation_step( 'group-cover-image' ) || bp_is_group_admin_screen( 'group-avatar' ) || bp_is_group_admin_screen( 'group-cover-image' ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $run_filter;
|
||||
}
|
||||
add_filter( 'do_rocket_lazyload', 'rocket_deactivate_lazyload_on_buddypress_group_pages' );
|
||||
add_filter( 'do_rocket_lazyload_iframes', 'rocket_deactivate_lazyload_on_buddypress_group_pages' );
|
||||
endif;
|
||||
endif;
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
/**
|
||||
* Compatibility with Cookie Notice by dFactory.
|
||||
*
|
||||
* @since 2.11.6
|
||||
* @author Arun Basil Lal
|
||||
* @link https://wordpress.org/plugins/cookie-notice/
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'Cookie_Notice' ) ) {
|
||||
// Don't add the WP Rocket rewrite rules to avoid issues.
|
||||
if ( ! class_exists( 'CC4R_options' ) || ! CC4R_options::rewrite_enabled() ) {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 56 );
|
||||
}
|
||||
// Create cache version based on value set in cookie_notice_accepted cookie.
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_cookie_notice_cookie' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the cookie name set by Cookie Notice plugin.
|
||||
*
|
||||
* @since 2.11.6
|
||||
* @author Arun Basil Lal
|
||||
*
|
||||
* @param array $cookies List of dynamic cookies.
|
||||
* @return array List of dynamic cookies with the Cookie Notice cookie appended.
|
||||
*/
|
||||
function rocket_get_cookie_notice_cookie( $cookies ) {
|
||||
$cookies[] = 'cookie_notice_accepted';
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add dynamic cookie and mandatory cookie when Cookie Notice plugin is activated.
|
||||
*
|
||||
* @since 2.11.6
|
||||
* @author Arun Basil Lal
|
||||
*/
|
||||
function rocket_add_cookie_notice_dynamic_cookie() {
|
||||
// Don't add the WP Rocket rewrite rules to avoid issues.
|
||||
if ( ! class_exists( 'CC4R_options' ) || ! CC4R_options::rewrite_enabled() ) {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 56 );
|
||||
}
|
||||
// Create cache version based on value set in cookie_notice_accepted cookie.
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_cookie_notice_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Clear WP Rocket cache.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'activate_cookie-notice/cookie-notice.php', 'rocket_add_cookie_notice_dynamic_cookie', 11 );
|
||||
|
||||
/**
|
||||
* Remove dynamic cookie when Cookie Notice plugin is deactivated.
|
||||
*
|
||||
* @since 2.11.6
|
||||
* @author Arun Basil Lal
|
||||
*/
|
||||
function rocket_remove_cookie_notice_dynamic_cookie() {
|
||||
if ( ! class_exists( 'CC4R_options' ) || ! CC4R_options::rewrite_enabled() ) {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 56 );
|
||||
}
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_cookie_notice_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Clear WP Rocket cache.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'deactivate_cookie-notice/cookie-notice.php', 'rocket_remove_cookie_notice_dynamic_cookie', 11 );
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with EU Cookie Law
|
||||
* https://wordpress.org/plugins/eu-cookie-law/
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
if ( function_exists( 'eucookie_start' ) ) :
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_eu_cookie_law_mandatory_cookie' );
|
||||
|
||||
/**
|
||||
* Update .htaccess & config files when the "Activate" and "Autoblock" options are turned on
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param Array $old_value Array of previous values.
|
||||
* @param Array $value Array of submitted values.
|
||||
*/
|
||||
function rocket_after_update_eu_cookie_law_options( $old_value, $value ) {
|
||||
if ( ( isset( $old_value['enabled'], $value['enabled'] ) && ( $old_value['enabled'] === $value['enabled'] ) ) && isset( $old_value['autoblock'], $value['autoblock'] ) && $old_value['autoblock'] === $value['autoblock'] ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Update the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'update_option_peadig_eucookie', 'rocket_after_update_eu_cookie_law_options', 10, 2 );
|
||||
|
||||
// Don't add the WP Rocket rewrite rules to avoid issues.
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 58 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add mandatory cookie when we activate the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_activate_eu_cookie_law() {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 58 );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_eu_cookie_law_mandatory_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_eu-cookie-law/eu-cookie-law.php', 'rocket_activate_eu_cookie_law', 11 );
|
||||
|
||||
/**
|
||||
* Remove mandatory cookie when we deactivate the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_deactivate_eu_cookie_law() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 58 );
|
||||
remove_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_eu_cookie_law_mandatory_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_eu-cookie-law/eu-cookie-law.php', 'rocket_deactivate_eu_cookie_law', 11 );
|
||||
|
||||
/**
|
||||
* Add the EU Cookie Law to the list of mandatory cookies before generating caching files.
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param Array $cookies Array of mandatory cookies.
|
||||
* @return Array Updated array of mandatory cookies
|
||||
*/
|
||||
function rocket_add_eu_cookie_law_mandatory_cookie( $cookies ) {
|
||||
$options = get_option( 'peadig_eucookie' );
|
||||
|
||||
if ( ! empty( $options['enabled'] ) && ! empty( $options['autoblock'] ) ) {
|
||||
$cookies['eu-cookie-law'] = 'euCookie';
|
||||
}
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
/**
|
||||
* Compatibility with GDPR by Trew Knowledge
|
||||
*
|
||||
* @link https://github.com/trewknowledge/GDPR/
|
||||
* @link https://wordpress.org/plugins/gdpr/
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'GDPR' ) ) {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 60 );
|
||||
// Create cache version based on value set in gdpr[] cookies.
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_gdpr_dynamic_cookies' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the cookie names set by GDPR plugin
|
||||
*
|
||||
* @since 3.1.4
|
||||
* @author jorditarrida
|
||||
*
|
||||
* @param array $cookies array List of dynamic cookies.
|
||||
* @return array List of dynamic cookies with the GDPR cookie appended
|
||||
*/
|
||||
function rocket_get_gdpr_mandatory_cookies( $cookies ) {
|
||||
$cookies[] = 'allowed_cookies';
|
||||
$cookies[] = 'consent_types';
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the cookie names set by GDPR plugin
|
||||
*
|
||||
* @since 3.1.4
|
||||
* @author jorditarrida
|
||||
*
|
||||
* @param array $cookies array List of dynamic cookies.
|
||||
* @return array List of dynamic cookies with the GDPR cookie appended
|
||||
*/
|
||||
function rocket_get_gdpr_dynamic_cookies( $cookies ) {
|
||||
$cookies['gdpr'] = [
|
||||
'allowed_cookies',
|
||||
'consent_types',
|
||||
];
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add dynamic cookie when GDPR plugin is activated
|
||||
*
|
||||
* @since 3.1.4
|
||||
* @author jorditarrida
|
||||
*/
|
||||
function rocket_add_gdpr_mandatory_cookies() {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 60 );
|
||||
|
||||
// Create cache version based on value set in GDPR cookies.
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_gdpr_dynamic_cookies' );
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
// Clear WP Rocket cache.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'activate_gdpr/gdpr.php', 'rocket_add_gdpr_mandatory_cookies', 11 );
|
||||
|
||||
/**
|
||||
* Remove dynamic cookie when GDPR plugin is deactivated.
|
||||
*
|
||||
* @since 3.1.4
|
||||
* @author jorditarrida
|
||||
*/
|
||||
function rocket_remove_gdpr_mandatory_cookies() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 60 );
|
||||
|
||||
// Delete the dynamic cookie filter.
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_gdpr_dynamic_cookies' );
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
// Clear WP Rocket cache.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'deactivate_gdpr/gdpr.php', 'rocket_remove_gdpr_mandatory_cookies', 11 );
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
/**
|
||||
* Compatibility with UK Cookie Consent.
|
||||
*
|
||||
* @since 3.2
|
||||
* @author TheZoker
|
||||
* @link https://wordpress.org/plugins/uk-cookie-consent/
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'CTCC_Public' ) ) {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 62 );
|
||||
// Create cache version based on value set in cookie_consent_accepted cookie.
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_cookie_uk_consent_cookie' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the cookie name set by UK Cookie Consent plugin.
|
||||
*
|
||||
* @since 3.2
|
||||
* @author TheZoker
|
||||
*
|
||||
* @param array $cookies List of dynamic cookies.
|
||||
* @return array List of dynamic cookies with the UK Cookie Consent cookie appended.
|
||||
*/
|
||||
function rocket_get_cookie_uk_consent_cookie( $cookies ) {
|
||||
$cookies[] = 'catAccCookies';
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add dynamic cookie and mandatory cookie when UK Cookie Consent plugin is activated.
|
||||
*
|
||||
* @since 3.2
|
||||
* @author TheZoker
|
||||
*/
|
||||
function rocket_add_uk_cookie_consent_dynamic_cookie() {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 62 );
|
||||
// Create cache version based on value set in cookie_consent_accepted cookie.
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_cookie_uk_consent_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Clear WP Rocket cache.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'activate_uk-cookie-consent/uk-cookie-consent.php', 'rocket_add_uk_cookie_consent_dynamic_cookie', 11 );
|
||||
|
||||
/**
|
||||
* Remove dynamic cookie when Cookie Consent plugin is deactivated.
|
||||
*
|
||||
* @since 3.2
|
||||
* @author TheZoker
|
||||
*/
|
||||
function rocket_remove_uk_cookie_consent_dynamic_cookie() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 62 );
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_get_cookie_uk_consent_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Clear WP Rocket cache.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'deactivate_uk-cookie-consent/uk-cookie-consent.php', 'rocket_remove_uk_cookie_consent_dynamic_cookie', 11 );
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with WeePie Cookie Allow
|
||||
*
|
||||
* @since 2.9
|
||||
*/
|
||||
if ( class_exists( 'WpieCookieAllow' ) ) :
|
||||
add_action( 'update_option_wpca_settings_general', 'rocket_after_update_wp_cookie_allow_options', 10, 2 );
|
||||
add_action( 'update_option_wpca_settings_style', 'rocket_after_update_wp_cookie_allow_options', 10, 2 );
|
||||
add_action( 'update_option_wpca_settings_content', 'rocket_after_update_wp_cookie_allow_options', 10, 2 );
|
||||
add_action( 'update_option_wpca_settings_consent_log', 'rocket_after_update_wp_cookie_allow_options', 10, 2 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Update .htaccess & config files when the "Enabled" and "Autoblock" options are turned on.
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $old_value Previous values for the plugin options.
|
||||
* @param array $value New values for the plugin options.
|
||||
*/
|
||||
function rocket_after_update_wp_cookie_allow_options( $old_value, $value ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
|
||||
// clear the cache because WeePie Cookie Allow plugin settings might have been changed.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add cookies when we activate the plugin.
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_activate_wp_cookie_allow() {
|
||||
// clear the cache because plugin might be enabled already before.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'activate_wp-cookie-allow/wp-cookie-allow.php', 'rocket_activate_wp_cookie_allow', 11 );
|
||||
|
||||
/**
|
||||
* Remove cookies when we deactivate the plugin
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_deactivate_wp_cookie_allow() {
|
||||
// clear the cache because the bar/box and other WeePie Cookie Allow plugin frontend HTML is not needed anymore.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'deactivate_wp-cookie-allow/wp-cookie-allow.php', 'rocket_deactivate_wp_cookie_allow', 11 );
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Exclude plugin custom login page template from cache.
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
if ( class_exists( 'Custom_Login_Page_Template' ) ) {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_custom_login_exclude_pages', 2, 2 );
|
||||
add_action( 'update_option_custom_login_page_template', 'rocket_after_update_single_options', 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add custom login page to excluded urls array
|
||||
*
|
||||
* @since 2.7
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param Array $urls Array of pages to exclude.
|
||||
* @param bool $show_safe_content show sensitive uris.
|
||||
* @return Array Updated array of pages to exclude
|
||||
*/
|
||||
function rocket_add_custom_login_exclude_pages( $urls, $show_safe_content = true ) {
|
||||
if ( ! $show_safe_content ) {
|
||||
return $urls;
|
||||
}
|
||||
|
||||
$clpt_options = get_option( 'custom_login_page_template' );
|
||||
$urls = array_merge( $urls, get_rocket_i18n_translated_post_urls( $clpt_options['login_page_id'], 'page' ) );
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add custom login page to excluded urls array on plugin activation
|
||||
*
|
||||
* @since 2.7
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_activate_custom_login_page_template() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_custom_login_exclude_pages', 2, 2 );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_custom-login-page-template/custom-login-page-template.php', 'rocket_activate_custom_login_page_template', 11 );
|
||||
|
||||
/**
|
||||
* Remove custom login page from excluded urls array on plugin activation
|
||||
*
|
||||
* @since 2.7
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_remove_custom_login_exclude_pages() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_add_custom_login_exclude_pages' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_custom-login-page-template/custom-login-page-template.php', 'rocket_remove_custom_login_exclude_pages', 11 );
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( defined( 'DISQUS_VERSION' ) ) :
|
||||
/**
|
||||
* Excludes Disqus scripts from JS minification
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param Array $excluded_js An array of JS handles enqueued in WordPress.
|
||||
* @return Array the updated array of handles
|
||||
*/
|
||||
function rocket_exclude_js_disqus( $excluded_js ) {
|
||||
$excluded_js[] = str_replace( home_url(), '', plugins_url( '/disqus-comment-system/media/js/disqus.js' ) );
|
||||
$excluded_js[] = str_replace( home_url(), '', plugins_url( '/disqus-comment-system/media/js/count.js' ) );
|
||||
|
||||
return $excluded_js;
|
||||
}
|
||||
add_filter( 'rocket_exclude_js', 'rocket_exclude_js_disqus' );
|
||||
endif;
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with Aelia Currency Switcher.
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
if ( class_exists( 'WC_Aelia_CurrencySwitcher' ) ) :
|
||||
/**
|
||||
* Update .htaccess & config files when the Geolocation option is updated
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param array $old_value Previous setting values.
|
||||
* @param array $value Submitted settings values.
|
||||
*/
|
||||
function rocket_after_update_aelia_currencyswitcher_options( $old_value, $value ) {
|
||||
if ( ( ! isset( $old_value['ipgeolocation_enabled'] ) && isset( $value['ipgeolocation_enabled'] ) ) || ( isset( $old_value['ipgeolocation_enabled'], $value['ipgeolocation_enabled'] ) && $old_value['ipgeolocation_enabled'] !== $value['ipgeolocation_enabled'] )
|
||||
) {
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Update the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
}
|
||||
add_action( 'update_option_wc_aelia_currency_switcher', 'rocket_after_update_aelia_currencyswitcher_options', 10, 2 );
|
||||
|
||||
/**
|
||||
* Generate a caching file depending on the currency cookie value
|
||||
*/
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 64 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_currencyswitcher_dynamic_cookies' );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_aelia_currencyswitcher_mandatory_cookie' );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add the Aelia Currency Switcher cookies when activating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_activate_aelia_currencyswitcher() {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 64 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_currencyswitcher_dynamic_cookies' );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_aelia_currencyswitcher_mandatory_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_woocommerce-aelia-currencyswitcher/woocommerce-aelia-currencyswitcher.php', 'rocket_activate_aelia_currencyswitcher', 11 );
|
||||
|
||||
/**
|
||||
* Remove the Aelia Currency Switcher cookies when deactivating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_deactivate_aelia_currencyswitcher() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 64 );
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_currencyswitcher_dynamic_cookies' );
|
||||
remove_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_aelia_currencyswitcher_mandatory_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_woocommerce-aelia-currencyswitcher/woocommerce-aelia-currencyswitcher.php', 'rocket_deactivate_aelia_currencyswitcher', 11 );
|
||||
|
||||
/**
|
||||
* Add the Aelia Currency Switcher cookies to the dynamic cookies list
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param array $cookies Cookies to use for dynamic caching.
|
||||
* @return array Updated cookies list
|
||||
*/
|
||||
function rocket_add_aelia_currencyswitcher_dynamic_cookies( $cookies ) {
|
||||
$cookies[] = 'aelia_cs_recalculate_cart_totals';
|
||||
$cookies[] = 'aelia_cs_selected_currency';
|
||||
$cookies[] = 'aelia_customer_country';
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the Aelia Currency Switcher to the list of mandatory cookies before generating caching files
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param array $cookies Mandatory cookies to serve the cache.
|
||||
* @return array Updated cookies list
|
||||
*/
|
||||
function rocket_add_aelia_currencyswitcher_mandatory_cookie( $cookies ) {
|
||||
$acs_options = get_option( 'wc_aelia_currency_switcher' );
|
||||
|
||||
if ( ! empty( $acs_options['ipgeolocation_enabled'] ) ) {
|
||||
$cookies[] = 'aelia_cs_selected_currency';
|
||||
}
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with Aelia Prices by Country.
|
||||
*
|
||||
* @since 2.8.15
|
||||
*/
|
||||
if ( class_exists( 'Aelia\WC\PricesByCountry\WC_Aelia_Prices_By_Country' ) ) :
|
||||
/**
|
||||
* Generate a caching file depending on the country cookie value
|
||||
*/
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 66 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_prices_by_country_dynamic_cookies' );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add cookie when we activate the plugin
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_activate_aelia_prices_by_country() {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 66 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_prices_by_country_dynamic_cookies' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_woocommerce-prices-by-country/woocommerce-prices-by-country.php', 'rocket_activate_aelia_prices_by_country', 11 );
|
||||
|
||||
/**
|
||||
* Remove cookies when we deactivate the plugin
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_deactivate_aelia_prices_by_country() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 66 );
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_prices_by_country_dynamic_cookies' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_woocommerce-prices-by-country/woocommerce-prices-by-country.php', 'rocket_deactivate_aelia_prices_by_country', 11 );
|
||||
|
||||
/**
|
||||
* Add the Aelia Prices by Country cookie to generate caching files depending on its value
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $cookies Cookies list to use for dynamic caching.
|
||||
* @return array Updated cookies list
|
||||
*/
|
||||
function rocket_add_aelia_prices_by_country_dynamic_cookies( $cookies ) {
|
||||
$cookies[] = 'aelia_customer_country';
|
||||
return $cookies;
|
||||
}
|
||||
Vendored
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with Aelia Tax Display by Country.
|
||||
*
|
||||
* @since 2.8.15
|
||||
*/
|
||||
if ( class_exists( 'Aelia\WC\TaxDisplayByCountry\WC_Aelia_Tax_Display_By_Country' ) ) :
|
||||
/**
|
||||
* Generate a caching file depending to the tax display cookie values
|
||||
*/
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 68 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_tax_display_by_country_dynamic_cookies' );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add cookies when we activate the plugin
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_activate_aelia_tax_display_by_country() {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 68 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_tax_display_by_country_dynamic_cookies' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_woocommerce-tax-display-by-country/woocommerce-tax-display-by-country.php', 'rocket_activate_aelia_tax_display_by_country', 11 );
|
||||
|
||||
/**
|
||||
* Remove cookies when we deactivate the plugin
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_deactivate_aelia_tax_display_by_country() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 68 );
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_aelia_tax_display_by_country_dynamic_cookies' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_woocommerce-tax-display-by-country/woocommerce-tax-display-by-country.php', 'rocket_deactivate_aelia_tax_display_by_country', 11 );
|
||||
|
||||
/**
|
||||
* Add the Aelia Tax Display by Country cookies to generate caching files depending on their values
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $cookies Cookies list to use for dynamic caching.
|
||||
* @return array Updated cookies list
|
||||
*/
|
||||
function rocket_add_aelia_tax_display_by_country_dynamic_cookies( $cookies ) {
|
||||
$cookies[] = 'aelia_customer_country';
|
||||
$cookies[] = 'aelia_customer_state';
|
||||
$cookies[] = 'aelia_tax_exempt';
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( function_exists( 'EDD' ) ) :
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_edd_pages' );
|
||||
add_action( 'update_option_edd_settings', 'rocket_after_update_array_options', 10, 2 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Exclude EDD pages from cache
|
||||
*
|
||||
* @param array $urls Array of URLs to exclude from cache.
|
||||
* @return array Updated array of URLs
|
||||
*/
|
||||
function rocket_exclude_edd_pages( $urls ) {
|
||||
$edd_settings = get_option( 'edd_settings' );
|
||||
if ( isset( $edd_settings['purchase_page'] ) ) {
|
||||
$checkout_urls = get_rocket_i18n_translated_post_urls( $edd_settings['purchase_page'], 'page', '(.*)' );
|
||||
$urls = array_merge( $urls, $checkout_urls );
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exclude EDD pages from cache on EDD activation.
|
||||
*/
|
||||
function rocket_activate_edd() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_edd_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_easy-digital-downloads/easy-digital-downloads.php', 'rocket_activate_edd', 11 );
|
||||
|
||||
/**
|
||||
* Remove EDD pages from cache exclusion on EDD deactivation.
|
||||
*/
|
||||
function rocket_deactivate_edd() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_exclude_edd_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_easy-digital-downloads/easy-digital-downloads.php', 'rocket_deactivate_edd', 11 );
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with Easy Digital Downloads Software Licensing addon.
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
if ( class_exists( 'EDD_Software_Licensing' ) && defined( 'EDD_SL_VERSION' ) ) :
|
||||
// Exclude EDD SL endpoint from cache on WP Rocket activation.
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_edd_sl_endpoint' );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Exclude EDD SL endpoint from cache when activating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_activate_edd_software_licensing() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_edd_sl_endpoint' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_edd-software-licensing/edd-software-licenses.php', 'rocket_activate_edd_software_licensing', 11 );
|
||||
|
||||
/**
|
||||
* Remove exclusion of EDD SL endpoint from cache when deactivating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_deactivate_edd_software_licensing() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_exclude_edd_sl_endpoint' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_edd-software-licensing/edd-software-licenses.php', 'rocket_deactivate_edd_software_licensing', 11 );
|
||||
|
||||
/**
|
||||
* Exclude EDD SL endpoint from caching
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param array $uri URLs to exclude from caching.
|
||||
* @return array Updated list of URLs to exclude
|
||||
*/
|
||||
function rocket_exclude_edd_sl_endpoint( $uri ) {
|
||||
$uri[] = '/edd-sl/(.*)';
|
||||
return $uri;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Exclude pages of Give plugin from cache.
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
if ( defined( 'GIVE_VERSION' ) && function_exists( 'give_get_settings' ) ) {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_give_exclude_pages' );
|
||||
|
||||
if ( is_admin() ) {
|
||||
add_action( 'update_option_give_settings', 'rocket_after_update_single_options', 10, 2 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add give pages to the excluded pages
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param Array $urls Array of excluded pages.
|
||||
* @return Array Updated array of excluded pages
|
||||
*/
|
||||
function rocket_add_give_exclude_pages( $urls ) {
|
||||
$give_options = give_get_settings();
|
||||
$urls = array_merge( $urls, get_rocket_i18n_translated_post_urls( $give_options['success_page'], 'page' ) );
|
||||
$urls = array_merge( $urls, get_rocket_i18n_translated_post_urls( $give_options['history_page'], 'page' ) );
|
||||
$urls = array_merge( $urls, get_rocket_i18n_translated_post_urls( $give_options['failure_page'], 'page' ) );
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add give pages to the excluded pages when activating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_activate_give() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_give_exclude_pages' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_give/give.php', 'rocket_activate_give', 11 );
|
||||
|
||||
/**
|
||||
* Remove give pages from the excluded pages when activating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_remove_give_exclude_pages() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_add_give_exclude_pages' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_give/give.php', 'rocket_remove_give_exclude_pages', 11 );
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( function_exists( 'it_exchange_get_page_type' ) && function_exists( 'it_exchange_get_page_url' ) ) :
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_ithemes_exchange_pages' );
|
||||
add_action( 'update_option_it-storage-exchange_settings_pages', 'rocket_after_update_single_options', 10, 2 );
|
||||
endif;
|
||||
|
||||
|
||||
/**
|
||||
* Exclude iThemes Exchange pages from cache.
|
||||
*
|
||||
* @param array $urls Array of URLs to exclude from cache.
|
||||
* @return array Updated array of URLs to exclude from cache
|
||||
*/
|
||||
function rocket_exclude_ithemes_exchange_pages( $urls ) {
|
||||
$pages = [
|
||||
'purchases',
|
||||
'confirmation',
|
||||
'account',
|
||||
'profile',
|
||||
'downloads',
|
||||
'purchases',
|
||||
'log-in',
|
||||
'log-out',
|
||||
];
|
||||
|
||||
foreach ( $pages as $page ) {
|
||||
if ( it_exchange_get_page_type( $page ) === 'WordPress' ) {
|
||||
$exchange_urls = get_rocket_i18n_translated_post_urls( it_exchange_get_page_wpid( $page ) );
|
||||
} else {
|
||||
$exchange_urls = [ rocket_extract_url_component( it_exchange_get_page_url( $page ), PHP_URL_PATH ) ];
|
||||
}
|
||||
|
||||
$urls = array_merge( $urls, $exchange_urls );
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Exclude iThemes Exchanges pages from cache on plugin activation.
|
||||
*/
|
||||
function rocket_activate_ithemes_exchange() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_ithemes_exchange_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_ithemes-exchange/ithemes-exchange.php', 'rocket_activate_ithemes_exchange', 11 );
|
||||
|
||||
/**
|
||||
* Remove iThemes Exchanges pages from cache exclusion on plugin deactivation.
|
||||
*/
|
||||
function rocket_deactivate_ithemes_exchange() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_exclude_ithemes_exchange_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_ithemes-exchange/ithemes-exchange.php', 'rocket_deactivate_ithemes_exchange', 11 );
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( defined( 'JIGOSHOP_VERSION' ) && function_exists( 'jigoshop_get_page_id' ) ) :
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_jigoshop_pages' );
|
||||
add_action( 'update_option_jigoshop_options', 'rocket_after_update_array_options', 10, 2 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Exclude Jigoshop pages from cache.
|
||||
*
|
||||
* @param array $urls Array of URLs to exclude from cache.
|
||||
* @return array Updated array of URLs to exclude from cache
|
||||
*/
|
||||
function rocket_exclude_jigoshop_pages( $urls ) {
|
||||
if ( jigoshop_get_page_id( 'checkout' ) && jigoshop_get_page_id( 'checkout' ) !== '-1' ) {
|
||||
$checkout_urls = get_rocket_i18n_translated_post_urls( jigoshop_get_page_id( 'checkout' ), 'page', '(.*)' );
|
||||
$urls = array_merge( $urls, $checkout_urls );
|
||||
}
|
||||
|
||||
if ( jigoshop_get_page_id( 'cart' ) && jigoshop_get_page_id( 'cart' ) !== '-1' ) {
|
||||
$cart_urls = get_rocket_i18n_translated_post_urls( jigoshop_get_page_id( 'cart' ) );
|
||||
$urls = array_merge( $urls, $cart_urls );
|
||||
}
|
||||
|
||||
if ( jigoshop_get_page_id( 'myaccount' ) && jigoshop_get_page_id( 'myaccount' ) !== '-1' ) {
|
||||
$cart_urls = get_rocket_i18n_translated_post_urls( jigoshop_get_page_id( 'myaccount' ), 'page', '(.*)' );
|
||||
$urls = array_merge( $urls, $cart_urls );
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exclude Jigoshop pages from cache on plugin activation.
|
||||
*/
|
||||
function rocket_activate_jigoshop() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_jigoshop_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_jigoshop/jigoshop.php', 'rocket_activate_jigoshop', 11 );
|
||||
|
||||
/**
|
||||
* Remove Jigoshop pages from cache exclusion on plugin deactivation.
|
||||
*/
|
||||
function rocket_deactivate_jigoshop() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_exclude_jigoshop_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_jigoshop/jigoshop.php', 'rocket_deactivate_jigoshop', 11 );
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Compatibility with WooCommerce Currency Converter Widget.
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
if ( class_exists( 'WC_Currency_Converter' ) ) :
|
||||
// Add cookie to config file when WP Rocket is activated and WooCommerce Currency Converter Widget is already active.
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 70 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_woocommerce_currency_converter_dynamic_cookies', 11 );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_woocommerce_currency_converter_mandatory_cookie', 11 );
|
||||
add_action( 'update_option_woocommerce_default_customer_address', 'rocket_after_update_single_options', 10, 2 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add cookies when we activating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_activate_woocommerce_currency_converter() {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 70 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_woocommerce_currency_converter_dynamic_cookies' );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_woocommerce_currency_converter_mandatory_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_woocommerce-currency-converter-widget/currency-converter.php', 'rocket_activate_woocommerce_currency_converter', 11 );
|
||||
|
||||
/**
|
||||
* Remove cookies when deactivating the plugin
|
||||
*
|
||||
* @since 2.7
|
||||
*/
|
||||
function rocket_deactivate_woocommerce_currency_converter() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 70 );
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_add_woocommerce_currency_converter_dynamic_cookies' );
|
||||
remove_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_woocommerce_currency_converter_mandatory_cookie' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_woocommerce-currency-converter-widget/currency-converter.php', 'rocket_deactivate_woocommerce_currency_converter', 11 );
|
||||
|
||||
/**
|
||||
* Add the WC Currency Converter Widget cookie to generate caching files depending on its value
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param array $cookies Cookies list to use for dynamic caching.
|
||||
* @return array Updated cookies list
|
||||
*/
|
||||
function rocket_add_woocommerce_currency_converter_dynamic_cookies( $cookies ) {
|
||||
$cookies[] = 'woocommerce_current_currency';
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the WC Currency Converter Widget cookie to the list of mandatory cookies before generating the caching files
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param array $cookies Mandatory cookies list.
|
||||
* @return array Updated cookies list
|
||||
*/
|
||||
function rocket_add_woocommerce_currency_converter_mandatory_cookie( $cookies ) {
|
||||
$widget_woocommerce_currency_converter = get_option( 'widget_woocommerce_currency_converter' );
|
||||
|
||||
if ( ! empty( $widget_woocommerce_currency_converter ) && 'geolocation_ajax' === get_option( 'woocommerce_default_customer_address' ) ) {
|
||||
$cookies[] = 'woocommerce_current_currency';
|
||||
}
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Check if WCML is active and has minimum requirements.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
function rocket_wcml_has_requirements() {
|
||||
return defined( 'ICL_SITEPRESS_VERSION' )
|
||||
&& version_compare( ICL_SITEPRESS_VERSION, '4.4.11', '>=' )
|
||||
&& defined( 'WCML_VERSION' )
|
||||
&& version_compare( WCML_VERSION, '4.12.6', '>=' );
|
||||
}
|
||||
|
||||
if ( rocket_wcml_has_requirements() ) :
|
||||
/**
|
||||
* Use Cookie instead of WCSession
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function rocket_wcml_use_cookie_storage() {
|
||||
return 'cookie';
|
||||
}
|
||||
add_filter( 'wcml_user_store_strategy', 'rocket_wcml_use_cookie_storage', 10, 2 );
|
||||
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_wcml_add_dynamic_cookies' );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_wcml_add_mandatory_cookies' );
|
||||
add_action( 'updated_option', 'rocket_wcml_reset_settings', 10, 3 );
|
||||
|
||||
/**
|
||||
* Reset WP Rocket settings on WCML deactivation.
|
||||
*/
|
||||
function rocket_wcml_deactivate() {
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 64 );
|
||||
remove_filter( 'rocket_cache_dynamic_cookies', 'rocket_wcml_add_dynamic_cookies' );
|
||||
remove_filter( 'rocket_cache_mandatory_cookies', 'rocket_wcml_add_mandatory_cookies' );
|
||||
flush_rocket_htaccess();
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_woocommerce-multilingual/wpml-woocommerce.php', 'rocket_wcml_deactivate', 11 );
|
||||
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 64 );
|
||||
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add dynamic cookies for WCML.
|
||||
*
|
||||
* @param array $cookies Cookies.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function rocket_wcml_add_dynamic_cookies( $cookies ) {
|
||||
$cookies[] = 'wcml_client_currency';
|
||||
$cookies[] = 'wcml_client_currency_language';
|
||||
$cookies[] = 'wcml_client_country';
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add mandatory cookies for WCML.
|
||||
*
|
||||
* @param array $cookies Cookies.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function rocket_wcml_add_mandatory_cookies( $cookies ) {
|
||||
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
|
||||
if ( apply_filters( 'wcml_geolocation_is_used', false ) ) {
|
||||
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
|
||||
$cookies[] = 'wcml_client_country';
|
||||
}
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset WP Rocket settings when a relevant WCML setting is changed.
|
||||
*
|
||||
* @param string $option Option name.
|
||||
* @param mixed $old_data Old data.
|
||||
* @param mixed $data New data.
|
||||
*/
|
||||
function rocket_wcml_reset_settings( $option, $old_data, $data ) {
|
||||
$keys_to_check = [
|
||||
'enable_multi_currency',
|
||||
'currency_mode',
|
||||
'default_currencies',
|
||||
];
|
||||
|
||||
$check_key = function ( $result, $key ) use ( $old_data, $data ) {
|
||||
$has_value_changed = function ( $key ) use ( $old_data, $data ) {
|
||||
$get_value = function ( $key, $data ) {
|
||||
return isset( $data[ $key ] ) ? $data[ $key ] : null;
|
||||
};
|
||||
|
||||
return $get_value( $key, $old_data ) !== $get_value( $key, $data );
|
||||
};
|
||||
|
||||
return $result || $has_value_changed( $key );
|
||||
};
|
||||
|
||||
if (
|
||||
'_wcml_settings' === $option
|
||||
&& array_reduce( $keys_to_check, $check_key, false )
|
||||
) {
|
||||
flush_rocket_htaccess();
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset WP Rocket settings on WCML activation.
|
||||
*/
|
||||
function rocket_wcml_activate() {
|
||||
if ( rocket_wcml_has_requirements() ) {
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 64 );
|
||||
add_filter( 'rocket_cache_dynamic_cookies', 'rocket_wcml_add_dynamic_cookies' );
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_wcml_add_mandatory_cookies' );
|
||||
flush_rocket_htaccess();
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
}
|
||||
add_action( 'activate_woocommerce-multilingual/wpml-woocommerce.php', 'rocket_wcml_activate', 11 );
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( defined( 'WPSHOP_VERSION' ) && class_exists( 'wpshop_tools' ) && method_exists( 'wpshop_tools', 'get_page_id' ) ) :
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_wpshop_pages' );
|
||||
add_action( 'update_option_wpshop_cart_page_id', 'rocket_after_update_single_options', 10, 2 );
|
||||
add_action( 'update_option_wpshop_checkout_page_id', 'rocket_after_update_single_options', 10, 2 );
|
||||
add_action( 'update_option_wpshop_payment_return_page_id', 'rocket_after_update_single_options', 10, 2 );
|
||||
add_action( 'update_option_wpshop_payment_return_nok_page_id', 'rocket_after_update_single_options', 10, 2 );
|
||||
add_action( 'update_option_wpshop_myaccount_page_id', 'rocket_after_update_single_options', 10, 2 );
|
||||
endif;
|
||||
|
||||
|
||||
/**
|
||||
* Exclude WP Shop pages from cache.
|
||||
*
|
||||
* @param array $urls Array of URLs to exclude from cache.
|
||||
* @return array Updated array of URLs to exclude from cache
|
||||
*/
|
||||
function rocket_exclude_wpshop_pages( $urls ) {
|
||||
$pages = [
|
||||
'wpshop_cart_page_id',
|
||||
'wpshop_checkout_page_id',
|
||||
'wpshop_payment_return_page_id',
|
||||
'wpshop_payment_return_nok_page_id',
|
||||
'wpshop_myaccount_page_id',
|
||||
];
|
||||
|
||||
foreach ( $pages as $page ) {
|
||||
$page_id = wpshop_tools::get_page_id( get_option( $page ) );
|
||||
if ( $page_id ) {
|
||||
$urls = array_merge( $urls, get_rocket_i18n_translated_post_urls( $page_id ) );
|
||||
}
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exclude WP Shop pages from cache on plugin activation.
|
||||
*/
|
||||
function rocket_activate_wpshop() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_wpshop_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_wpshop/wpshop.php', 'rocket_activate_wpshop', 11 );
|
||||
|
||||
/**
|
||||
* Remove WP Shop pages from cache exclusion on plugin deactivation.
|
||||
*/
|
||||
function rocket_deactivate_wpshop() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_exclude_wpshop_pages' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_wpshop/wpshop.php', 'rocket_deactivate_wpshop', 11 );
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Conflict with Envira Gallery: don't apply LazyLoad on all images
|
||||
*
|
||||
* @since 2.3.10
|
||||
*
|
||||
* @param string $attr Envira gallery image attributes.
|
||||
* @return string Updated attributes
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_envira_gallery( $attr ) {
|
||||
return $attr . ' data-no-lazy="1" ';
|
||||
}
|
||||
add_filter( 'envira_gallery_output_image_attr', 'rocket_deactivate_lazyload_on_envira_gallery', PHP_INT_MAX );
|
||||
|
||||
/**
|
||||
* Conflict with Envira Gallery: don't apply LazyLoad on all images
|
||||
*
|
||||
* @since 2.3.10
|
||||
*
|
||||
* @param string $images Envira gallery images HTML code.
|
||||
* @return string Updated HTML code
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_envira_gallery_indexable_images( $images ) {
|
||||
$images = str_replace( '<img', '<img data-no-lazy="1" ', $images );
|
||||
|
||||
return $images;
|
||||
}
|
||||
add_filter( 'envira_gallery_indexable_images', 'rocket_deactivate_lazyload_on_envira_gallery_indexable_images', PHP_INT_MAX );
|
||||
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( defined( 'POLYLANG_VERSION' ) && POLYLANG_VERSION ) :
|
||||
/**
|
||||
* Conflict with Polylang: Clear the whole cache when the "The language is set from content" option is activated.
|
||||
*
|
||||
* @since 2.6.8
|
||||
*/
|
||||
function rocket_force_clean_domain_on_polylang() {
|
||||
$pll = function_exists( 'PLL' ) ? PLL() : $GLOBALS['polylang'];
|
||||
|
||||
if ( isset( $pll ) && 0 === $pll->options['force_lang'] ) {
|
||||
rocket_clean_cache_dir();
|
||||
}
|
||||
}
|
||||
add_action( 'after_rocket_clean_domain', 'rocket_force_clean_domain_on_polylang' );
|
||||
|
||||
// Filter mandatory cookies and WP Rocket rewrite rules if Polylang module 'Detect browser language' is enabled.
|
||||
if ( function_exists( 'PLL' ) && PLL()->options['browser'] ) {
|
||||
|
||||
// Add Polylang's language cookie as a mandatory cookie.
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_polylang_mandatory_cookie' );
|
||||
|
||||
// Remove WP Rocket rewrite rules from .htaccess file.
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 74 );
|
||||
}
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add Polylang's language cookie to the mandatory cookies of WP Rocket.
|
||||
*
|
||||
* Polylang saves the users preferred language in this cookie by detecting browser language or by user choice
|
||||
* Adding this as a mandatory cookie prevents WP Rocket from serving the cache when the cookie is not set.
|
||||
*
|
||||
* @param array $cookies Array with mandatory cookies.
|
||||
* @return (array) Array of mandatory cookies with the Polylang cookie appended
|
||||
*
|
||||
* @author Arun Basil Lal
|
||||
* @since 3.0.5
|
||||
*/
|
||||
function rocket_add_polylang_mandatory_cookie( $cookies ) {
|
||||
$cookies[] = defined( 'PLL_COOKIE' ) ? PLL_COOKIE : 'pll_language';
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add mandatory cookie to WP Rocket config and remove rewrite rules from .htaccess on Polylang activation.
|
||||
*
|
||||
* Add mandatory cookie only if the Polylang module 'Detect browser language' is active.
|
||||
* Also purge the homepage cache.
|
||||
*
|
||||
* @author Arun Basil Lal
|
||||
* @since 3.0.5
|
||||
*/
|
||||
function rocket_activate_polylang() {
|
||||
// Read Polylang settings from db.
|
||||
$polylang_settings = get_option( 'polylang' );
|
||||
|
||||
if ( isset( $polylang_settings['browser'] ) && ( 1 === (int) $polylang_settings['browser'] ) ) {
|
||||
// Add Polylang's language cookie as a mandatory cookie.
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_polylang_mandatory_cookie' );
|
||||
|
||||
// Remove WP Rocket rewrite rules from .htaccess file.
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 74 );
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Regenerate .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Purge homepage cache.
|
||||
rocket_clean_home();
|
||||
}
|
||||
}
|
||||
add_action( 'activate_polylang/polylang.php', 'rocket_activate_polylang', 11 );
|
||||
|
||||
/**
|
||||
* Remove mandatory cookie and add rewrite rules back to .htaccess when Polylang is deactivated.
|
||||
*
|
||||
* @author Arun Basil Lal
|
||||
* @since 3.0.5
|
||||
*/
|
||||
function rocket_deactivate_polylang() {
|
||||
// Remove Polylang's language cookie as a mandatory cookie.
|
||||
remove_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_polylang_mandatory_cookie' );
|
||||
|
||||
// Add back WP Rocket rewrite rules from .htaccess file.
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 74 );
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Regenerate .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
}
|
||||
add_action( 'deactivate_polylang/polylang.php', 'rocket_deactivate_polylang', 11 );
|
||||
|
||||
/**
|
||||
* Update mandatory cookie in WP Rocket config file and remove rewrite rules from .htaccess
|
||||
* when Detect browser language module is enabled / disabled.
|
||||
*
|
||||
* @param array $value Array containing Polylang settings before its written to db.
|
||||
* @return array
|
||||
*
|
||||
* @author Arun Basil Lal
|
||||
* @since 3.0.5
|
||||
*/
|
||||
function rocket_detect_browser_language_status_change( $value ) {
|
||||
if ( function_exists( 'PLL' ) && PLL()->options['browser'] ) {
|
||||
|
||||
// Add Polylang's language cookie as a mandatory cookie.
|
||||
add_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_polylang_mandatory_cookie' );
|
||||
|
||||
// Remove WP Rocket rewrite rules from .htaccess file.
|
||||
add_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 74 );
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Regenerate .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Purge homepage cache.
|
||||
rocket_clean_home();
|
||||
} else {
|
||||
// Remove Polylang's language cookie as a mandatory cookie.
|
||||
remove_filter( 'rocket_cache_mandatory_cookies', 'rocket_add_polylang_mandatory_cookie' );
|
||||
|
||||
// Add back WP Rocket rewrite rules from .htaccess file.
|
||||
remove_filter( 'rocket_htaccess_mod_rewrite', '__return_false', 74 );
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
|
||||
// Regenerate .htaccess file.
|
||||
flush_rocket_htaccess();
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
add_filter( 'pre_update_option_polylang', 'rocket_detect_browser_language_status_change' );
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Conflict with MailChimp List Subscribe Form: Enqueue style without lack of performance, grrrr!!!
|
||||
*
|
||||
* @since 2.6
|
||||
*/
|
||||
function rocket_fix_mailchimp_main_css() {
|
||||
if ( ! defined( 'MCSF_VER' ) || ! function_exists( 'mailchimpSF_main_css' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$blog_id = get_current_blog_id();
|
||||
$cache_path = WP_ROCKET_MINIFY_CACHE_PATH . $blog_id . '/';
|
||||
$cache_url = WP_ROCKET_MINIFY_CACHE_URL . $blog_id . '/';
|
||||
$css_path = $cache_path . 'mailchimpSF_main_css.css';
|
||||
|
||||
if ( ! rocket_direct_filesystem()->is_dir( $cache_path ) ) {
|
||||
rocket_mkdir_p( $cache_path );
|
||||
}
|
||||
|
||||
if ( ! rocket_direct_filesystem()->exists( $css_path ) ) {
|
||||
ob_start();
|
||||
mailchimpSF_main_css();
|
||||
$content = ob_get_contents();
|
||||
ob_end_clean();
|
||||
|
||||
rocket_put_content( $css_path, $content );
|
||||
}
|
||||
|
||||
wp_deregister_style( 'mailchimpSF_main_css' );
|
||||
wp_register_style( 'mailchimpSF_main_css', $cache_url . 'mailchimpSF_main_css.css', null, MCSF_VER );
|
||||
}
|
||||
add_action( 'init', 'rocket_fix_mailchimp_main_css', PHP_INT_MAX );
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'WpAppKit' ) ) :
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_appkit_exclude_pages' );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Add WP Appkit path to cache exclusion
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $urls URLs to exclude from cache.
|
||||
* @return array Updated URLs array
|
||||
*/
|
||||
function rocket_add_appkit_exclude_pages( $urls ) {
|
||||
$urls[] = '/wp-appkit-api/(.*)';
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add WP Appkit path to cache exclusion when activating the plugin
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_activate_wp_appkit() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_appkit_exclude_pages' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_wp-appkit/wp-appkit.php', 'rocket_activate_wp_appkit', 11 );
|
||||
|
||||
/**
|
||||
* Remove Appkit path from cache exclusion when deactivating the plugin
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_deactivate_wp_appkit() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_add_appkit_exclude_pages' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_wp-appkit/wp-appkit.php', 'rocket_deactivate_wp_appkit', 11 );
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
global $nginx_helper;
|
||||
|
||||
if ( isset( $nginx_helper ) ) :
|
||||
global $nginx_purger;
|
||||
|
||||
/**
|
||||
* Clear WP Rocket cache after the NGINX cache is purged from Nginx Helper.
|
||||
*
|
||||
* @since 3.3.0.1
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clear_cache_after_nginx_helper_purge() {
|
||||
if ( ! isset( $_GET['nginx_helper_action'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! check_admin_referer( 'nginx_helper-purge_all' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( 'done' !== sanitize_text_field( wp_unslash( $_GET['nginx_helper_action'] ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'rocket_purge_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear all caching files.
|
||||
rocket_clean_domain();
|
||||
}
|
||||
add_action( 'admin_init', 'rocket_clear_cache_after_nginx_helper_purge' );
|
||||
|
||||
/**
|
||||
* Clear WP Rocket cache for the current page after the NGINX cache is purged from Nginx Helper.
|
||||
*
|
||||
* @since 3.3.0.1
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clear_current_page_after_nginx_helper_purge() {
|
||||
if ( ! isset( $_GET['nginx_helper_action'], $_GET['_wpnonce'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'nginx_helper-purge_all' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'rocket_purge_posts' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$referer = wp_get_referer();
|
||||
|
||||
if ( 0 !== strpos( $referer, 'http' ) ) {
|
||||
$parse_url = get_rocket_parse_url( untrailingslashit( home_url() ) );
|
||||
$referer = $parse_url['scheme'] . '://' . $parse_url['host'] . $referer;
|
||||
}
|
||||
|
||||
if ( home_url( '/' ) === $referer ) {
|
||||
rocket_clean_home();
|
||||
return;
|
||||
}
|
||||
|
||||
rocket_clean_files( $referer );
|
||||
}
|
||||
add_action( 'init', 'rocket_clear_current_page_after_nginx_helper_purge' );
|
||||
|
||||
/**
|
||||
* Clears NGINX cache for the homepage URL when using "Purge this URL" from the admin bar on the front end
|
||||
*
|
||||
* @since 3.3.0.1
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param string $root WP Rocket root cache path.
|
||||
* @param string $lang Current language.
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clean_nginx_cache_home( $root = '', $lang = '' ) {
|
||||
global $nginx_purger;
|
||||
|
||||
if ( ! isset( $nginx_purger ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$url = get_rocket_i18n_home_url( $lang );
|
||||
|
||||
$nginx_purger->purge_url( $url );
|
||||
}
|
||||
add_action( 'after_rocket_clean_home', 'rocket_clean_nginx_cache_home', 10, 2 );
|
||||
|
||||
/**
|
||||
* Clears NGINX cache for a specific URL when using "Purge this URL" from the admin bar on the front end
|
||||
*
|
||||
* @since 3.3.0.1
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param string $url URL to purge.
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clean_nginx_cache_url( $url ) {
|
||||
global $nginx_purger;
|
||||
|
||||
if ( ! isset( $nginx_purger ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! isset( $_GET['type'], $_GET['_wpnonce'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return;
|
||||
}
|
||||
|
||||
if ( false !== strpos( $url, 'index.html' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( 'page' === substr( $url, -4 ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$url = str_replace( '*', '', $url );
|
||||
|
||||
$nginx_purger->purge_url( $url );
|
||||
}
|
||||
add_action( 'after_rocket_clean_file', 'rocket_clean_nginx_cache_url' );
|
||||
|
||||
/**
|
||||
* Clean the NGINX cache using Nginx Helper after WP Rocket's cache is purged.
|
||||
*
|
||||
* @since 3.3.0.1
|
||||
*/
|
||||
function rocket_clean_nginx_helper_cache() {
|
||||
if ( isset( $_GET['nginx_helper_action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return;
|
||||
}
|
||||
|
||||
do_action( 'rt_nginx_helper_purge_all' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
|
||||
}
|
||||
add_action( 'after_rocket_clean_domain', 'rocket_clean_nginx_helper_cache' );
|
||||
|
||||
/**
|
||||
* Clean the NGINX cache after the Used CSS has been generated.
|
||||
*
|
||||
* @since 3.12.3
|
||||
*/
|
||||
add_action( 'rocket_rucss_after_clearing_usedcss', 'rocket_clean_nginx_cache_url' );
|
||||
add_action( 'rocket_rucss_complete_job_status', 'rocket_clean_nginx_helper_cache' );
|
||||
|
||||
endif;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( function_exists( 'tve_editor_url' ) ) {
|
||||
/**
|
||||
* Forces Thrive Visual Editor’s bot detection to assume a human visitor.
|
||||
*
|
||||
* @since 2.8.11
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param boolean|integer $bot_detection 1|0 when crawler has|not been detected, FALSE when user agent string is unavailable
|
||||
* @return integer
|
||||
*/
|
||||
add_filter( 'tve_dash_is_crawler', '__return_zero', PHP_INT_MAX );
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( defined( 'WPB_VC_VERSION' ) && class_exists( 'Vc_Manager' ) ) :
|
||||
/**
|
||||
* Disable nonce checking for Visual Composer grid
|
||||
*/
|
||||
add_filter( 'vc_grid_get_grid_data_access', '__return_true' );
|
||||
endif;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'BhittaniPlugin_kkStarRatings' ) ) :
|
||||
/**
|
||||
* Conflict with kk Star Ratings: Clear the cache when a post gets rated.
|
||||
*
|
||||
* @since 2.5.3
|
||||
*
|
||||
* @param int $post_id Post ID.
|
||||
*/
|
||||
function rocket_clear_cache_on_kksr_rate( $post_id ) {
|
||||
rocket_clean_post( $post_id );
|
||||
}
|
||||
add_action( 'kksr_rate', 'rocket_clear_cache_on_kksr_rate' );
|
||||
endif;
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( defined( 'WP_POSTRATINGS_VERSION' ) ) :
|
||||
/**
|
||||
* Conflict with WP-PostRatings: Clear the cache when a post gets rated.
|
||||
*
|
||||
* @since 2.6.6
|
||||
*
|
||||
* @param int $user_id user ID.
|
||||
* @param int $post_id post ID.
|
||||
*/
|
||||
function rocket_clear_cache_on_wp_postratings_rate( $user_id, $post_id ) {
|
||||
rocket_clean_post( $post_id );
|
||||
}
|
||||
add_action( 'rate_post', 'rocket_clear_cache_on_wp_postratings_rate', 10, 2 );
|
||||
endif;
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Excludes s2 Member dynamic file from saving as static resource
|
||||
*
|
||||
* @since 2.11.4
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $excluded_files Array of excluded files.
|
||||
*/
|
||||
function rocket_exclude_s2member_dynamic_files( $excluded_files ) {
|
||||
$excluded_files[] = rocket_clean_exclude_file( plugins_url( '/s2member/s2member-o.php' ) );
|
||||
|
||||
return $excluded_files;
|
||||
}
|
||||
add_action( 'rocket_exclude_static_dynamic_resources', 'rocket_exclude_s2member_dynamic_files' );
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action( 'update_option_secupress_users-login_settings', 'rocket_after_update_single_options', 10, 2 );
|
||||
|
||||
/**
|
||||
* Add SecuPress move login pages to cache exclusion
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $urls URLs to exclude from cache.
|
||||
* @param bool $show_safe_content show sensitive uris.
|
||||
* @return array Updated URLs to exclude
|
||||
*/
|
||||
function rocket_exclude_secupress_move_login( $urls, $show_safe_content = true ) {
|
||||
|
||||
if ( ! $show_safe_content ) {
|
||||
return $urls;
|
||||
}
|
||||
|
||||
if ( ! function_exists( 'secupress_move_login_get_slugs' ) ) {
|
||||
return $urls;
|
||||
}
|
||||
|
||||
$bases = secupress_get_rewrite_bases();
|
||||
$slugs = secupress_move_login_get_slugs();
|
||||
|
||||
foreach ( $slugs as $slug ) {
|
||||
$urls[] = $bases['base'] . ltrim( $bases['site_from'], '/' ) . $slug . '/?';
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_secupress_move_login', 2, 2 );
|
||||
|
||||
/**
|
||||
* Add SecuPress move login pages to cache exclusion when activating the plugin
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_maybe_activate_secupress() {
|
||||
if ( function_exists( 'secupress_move_login_get_slugs' ) ) {
|
||||
rocket_activate_secupress();
|
||||
}
|
||||
}
|
||||
add_action( 'secupress.plugins.activation', 'rocket_maybe_activate_secupress', 10001 );
|
||||
|
||||
/**
|
||||
* Add SecuPress move login pages to cache exclusion when activating the move login module
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_activate_secupress() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_secupress_move_login', 2, 2 );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'secupress.plugin.move_login.activate', 'rocket_activate_secupress' );
|
||||
|
||||
/**
|
||||
* Remove SecuPress move login pages from cache exclusion when deactivating the plugin
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_maybe_deactivate_secupress() {
|
||||
if ( function_exists( 'secupress_move_login_get_slugs' ) ) {
|
||||
rocket_deactivate_secupress();
|
||||
}
|
||||
}
|
||||
add_action( 'secupress.deactivation', 'rocket_maybe_deactivate_secupress', 10001 );
|
||||
|
||||
/**
|
||||
* Remove SecuPress move login pages from cache exclusion when deactivating the move login module
|
||||
*
|
||||
* @since 2.9
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_deactivate_secupress() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_exclude_secupress_move_login' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'secupress.plugin.move_login.deactivate', 'rocket_deactivate_secupress' );
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( defined( 'SFML_VERSION' ) ) :
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_sfml_exclude_pages', 2, 2 );
|
||||
add_action( 'update_option_sfml', 'rocket_after_update_single_options', 10, 2 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Exclude SF Move Login custom urls from caching
|
||||
*
|
||||
* @since 2.9.3 Moved to 3rd party file and improved
|
||||
* @since 2.6
|
||||
*
|
||||
* @param array $urls An array of URLs to exclude from cache.
|
||||
* @param bool $show_safe_content show sensitive uris.
|
||||
* @return array Updated array of URLs
|
||||
*/
|
||||
function rocket_add_sfml_exclude_pages( $urls, $show_safe_content = true ) {
|
||||
if ( ! $show_safe_content ) {
|
||||
return $urls;
|
||||
}
|
||||
if ( ! function_exists( 'sfml_get_slugs' ) ) {
|
||||
if ( file_exists( SFML_PLUGIN_DIR . 'inc/utilities.php' ) ) {
|
||||
include SFML_PLUGIN_DIR . 'inc/utilities.php';
|
||||
} else {
|
||||
return $urls;
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! class_exists( 'SFML_Options' ) && ! defined( 'SFML_NOOP_VERSION' ) ) {
|
||||
if ( file_exists( SFML_PLUGIN_DIR . 'inc/class-sfml-options.php' ) ) {
|
||||
include SFML_PLUGIN_DIR . 'inc/class-sfml-options.php';
|
||||
} else {
|
||||
return $urls;
|
||||
}
|
||||
}
|
||||
|
||||
$sfml_slugs = sfml_get_slugs();
|
||||
$sfml_slugs = array_map( 'home_url', $sfml_slugs );
|
||||
$sfml_slugs = array_map( 'trailingslashit', $sfml_slugs );
|
||||
$sfml_slugs = array_map( 'rocket_clean_exclude_file', $sfml_slugs );
|
||||
|
||||
foreach ( $sfml_slugs as $key => $slug ) {
|
||||
$sfml_slugs[ $key ] = $slug . '?';
|
||||
}
|
||||
|
||||
return array_merge( $urls, $sfml_slugs );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add SFML custom urls to caching exclusion when activating the plugin
|
||||
*
|
||||
* @since 2.9.3
|
||||
*/
|
||||
function rocket_activate_sfml() {
|
||||
if ( defined( 'SFML_VERSION' ) ) {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_add_sfml_exclude_pages', 2, 2 );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
}
|
||||
add_action( 'activate_sf-move-login/sf-move-login.php', 'rocket_activate_sfml', 11 );
|
||||
|
||||
/**
|
||||
* Remove SFML custom urls from caching exclusion when deactivating the plugin
|
||||
*
|
||||
* @since 2.9.3
|
||||
*/
|
||||
function rocket_deactivate_sfml() {
|
||||
if ( defined( 'SFML_VERSION' ) ) {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_add_sfml_exclude_pages' );
|
||||
|
||||
// Update the WP Rocket rules on the .htaccess.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Regenerate the config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
}
|
||||
add_action( 'deactivate_sf-move-login/sf-move-login.php', 'rocket_deactivate_sfml', 11 );
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'WPS_Hide_Login' ) || defined( 'WPS_HIDE_LOGIN_VERSION' ) ) :
|
||||
add_action( 'update_option_whl_page', 'rocket_after_update_single_options', 10, 2 );
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exlude_wps_hide_login_page', 2, 2 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Exclude WPS Hide Login custom url from caching
|
||||
*
|
||||
* @since 3.1 Switch implementation depending on the WPS Hide Login version
|
||||
* @since 2.11.7 Login url is retrieved using new_login_url() method of WPS_Hide_Login() class.
|
||||
* @since 2.11 Moved to 3rd party file
|
||||
* @since 2.6
|
||||
*
|
||||
* @param array $urls An array of URLs to exclude from cache.
|
||||
* @param bool $show_safe_content show sensitive uris.
|
||||
* @return array Updated array of URLs
|
||||
*/
|
||||
function rocket_exlude_wps_hide_login_page( $urls, $show_safe_content = true ) {
|
||||
if ( ! $show_safe_content ) {
|
||||
return $urls;
|
||||
}
|
||||
|
||||
if ( class_exists( 'WPS_Hide_Login' ) ) {
|
||||
$wps_hide_login = new WPS_Hide_Login();
|
||||
$urls[] = rocket_clean_exclude_file( $wps_hide_login->new_login_url() );
|
||||
} elseif ( class_exists( '\WPS\WPS_Hide_Login\Plugin' ) ) {
|
||||
$urls[] = rocket_clean_exclude_file( \WPS\WPS_Hide_Login\Plugin::get_instance()->new_login_url() );
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add WPS Hide Login custom url to caching exclusion when activating the plugin
|
||||
*
|
||||
* @since 2.11
|
||||
*/
|
||||
function rocket_activate_wps_hide_login() {
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exlude_wps_hide_login_page', 2, 2 );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Update config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'activate_wps-hide-login/wps-hide-login.php', 'rocket_activate_wps_hide_login', 11 );
|
||||
|
||||
/**
|
||||
* Remove WPS Hide Login custom url from caching exclusion when deactivating the plugin
|
||||
*
|
||||
* @since 2.11
|
||||
*/
|
||||
function rocket_deactivate_wps_hide_login() {
|
||||
remove_filter( 'rocket_cache_reject_uri', 'rocket_exlude_wps_hide_login_page' );
|
||||
|
||||
// Update .htaccess file rules.
|
||||
flush_rocket_htaccess();
|
||||
|
||||
// Update config file.
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
add_action( 'deactivate_wps-hide-login/wps-hide-login.php', 'rocket_deactivate_wps_hide_login', 11 );
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
/**
|
||||
* Compatibility with Premium SEO Pack
|
||||
*
|
||||
* @link http://premiumseopack.com
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'psp' ) ) {
|
||||
|
||||
/**
|
||||
* Dequeue the stylesheet of Premium SEO Pack on WP Rocket settings page.
|
||||
*
|
||||
* @since 2.11.6
|
||||
* @author Arun Basil Lal
|
||||
*/
|
||||
function rocket_dequeue_premium_seo_pack_stylesheet() {
|
||||
|
||||
// Retun on all pages but WP Rocket settings page.
|
||||
$screen = get_current_screen();
|
||||
if ( 'settings_page_wprocket' !== $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Dequeueing this stylesheet unfreezes WP Rocket.
|
||||
wp_dequeue_style( 'psp-main-style' );
|
||||
}
|
||||
add_action( 'admin_print_styles', 'rocket_dequeue_premium_seo_pack_stylesheet', 11 );
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Conflict with Meta Slider (Nivo Slider): don't apply LazyLoad on all images
|
||||
*
|
||||
* @since 2.4
|
||||
*
|
||||
* @param array $slide Slide attributes.
|
||||
* @return array Updated slide attributes
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_metaslider( $slide ) {
|
||||
$slide['data-no-lazy'] = 1;
|
||||
return $slide;
|
||||
}
|
||||
add_filter( 'metaslider_nivo_slider_image_attributes', 'rocket_deactivate_lazyload_on_metaslider' );
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Conflict with Soliloquy: don't apply LazyLoad on all images
|
||||
*
|
||||
* @since 2.4.2
|
||||
*
|
||||
* @param string $attr Image attributes.
|
||||
* @return string Updated attributes
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_soliloquy( $attr ) {
|
||||
return $attr . ' data-no-lazy="1" ';
|
||||
}
|
||||
add_filter( 'soliloquy_output_image_attr', 'rocket_deactivate_lazyload_on_soliloquy', PHP_INT_MAX );
|
||||
|
||||
/**
|
||||
* Conflict with Soliloquy: don't apply LazyLoad on all images
|
||||
*
|
||||
* @since 2.4.2
|
||||
*
|
||||
* @param string $images Image HTML code.
|
||||
* @return string Updated image HTML code
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_soliloquy_indexable_images( $images ) {
|
||||
$images = str_replace( '<img', '<img data-no-lazy="1" ', $images );
|
||||
|
||||
return $images;
|
||||
}
|
||||
add_filter( 'soliloquy_indexable_images', 'rocket_deactivate_lazyload_on_soliloquy_indexable_images', PHP_INT_MAX );
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/**
|
||||
* Compatibility with SumoMe
|
||||
*
|
||||
* Prevents conflict with SumoMe and the WP Rocket UI by removing SumoMe
|
||||
* styles and scripts on WP Rocket admin pages.
|
||||
*
|
||||
* @link https://wordpress.org/plugins/sumome/
|
||||
* @since 3.0.4
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'WP_Plugin_SumoMe' ) ) {
|
||||
|
||||
/**
|
||||
* Dequeue SumoMe styles
|
||||
*
|
||||
* @since 3.0.4
|
||||
* @author Arun Basil Lal
|
||||
*/
|
||||
function rocket_dequeue_sumo_me_css() {
|
||||
|
||||
// Retun on all pages but WP Rocket settings page.
|
||||
$screen = get_current_screen();
|
||||
if ( 'settings_page_wprocket' !== $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_dequeue_style( 'sumome-admin-styles' );
|
||||
wp_dequeue_style( 'sumome-admin-media' );
|
||||
}
|
||||
add_action( 'admin_enqueue_scripts', 'rocket_dequeue_sumo_me_css', PHP_INT_MAX );
|
||||
|
||||
/**
|
||||
* Dequeue SumoMe inline script
|
||||
*
|
||||
* @since 3.0.4
|
||||
* @author Arun Basil Lal
|
||||
*/
|
||||
function rocket_dequeue_sumo_me_js() {
|
||||
|
||||
// Retun on all pages but WP Rocket settings page.
|
||||
$screen = get_current_screen();
|
||||
if ( 'settings_page_wprocket' !== $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
global $wp_plugin_sumome;
|
||||
remove_action( 'admin_footer', [ $wp_plugin_sumome, 'append_admin_script_code' ] );
|
||||
}
|
||||
add_action( 'admin_head', 'rocket_dequeue_sumo_me_js' );
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Conflict with Thrive Leads: override the DONOTCACHEPAGE behavior because this plugin add this constant!
|
||||
*
|
||||
* @since 2.5
|
||||
*/
|
||||
function rocket_override_donotcachepage_on_thrive_leads() {
|
||||
return defined( 'TVE_LEADS_VERSION' ) && TVE_LEADS_VERSION > 0;
|
||||
}
|
||||
add_filter( 'rocket_override_donotcachepage', 'rocket_override_donotcachepage_on_thrive_leads' );
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( class_exists( 'VarnishPurger' ) ) :
|
||||
add_action( 'admin_init', 'rocket_clear_cache_after_varnish_http_purge' );
|
||||
/**
|
||||
* Clear WP Rocket cache after purged the Varnish cache via Varnish HTTP Purge plugin
|
||||
*
|
||||
* @since 2.5.5
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clear_cache_after_varnish_http_purge() {
|
||||
if ( isset( $_GET['vhp_flush_all'] ) && current_user_can( 'manage_options' ) && check_admin_referer( 'varnish-http-purge' ) ) {
|
||||
// Clear all caching files.
|
||||
rocket_clean_domain();
|
||||
|
||||
// Preload cache.
|
||||
run_rocket_bot();
|
||||
run_rocket_sitemap_preload();
|
||||
}
|
||||
}
|
||||
endif;
|
||||
|
||||
add_action( 'after_rocket_clean_domain', 'rocket_clean_varnish_http_purge' );
|
||||
/**
|
||||
* Call the cache server to purge the cache with Varnish HTTP Purge.
|
||||
*
|
||||
* @since 2.5.5
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clean_varnish_http_purge() {
|
||||
if ( class_exists( 'VarnishPurger' ) ) {
|
||||
$url = home_url( '/?vhp-regex' );
|
||||
$p = wp_parse_url( $url );
|
||||
$path = '';
|
||||
$pregex = '.*';
|
||||
|
||||
// Build a varniship.
|
||||
if ( defined( 'VHP_VARNISH_IP' ) && VHP_VARNISH_IP ) {
|
||||
$varniship = VHP_VARNISH_IP;
|
||||
} else {
|
||||
$varniship = get_option( 'vhp_varnish_ip' );
|
||||
}
|
||||
|
||||
if ( isset( $p['path'] ) ) {
|
||||
$path = $p['path'];
|
||||
}
|
||||
|
||||
$schema = apply_filters( 'varnish_http_purge_schema', 'http://' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
|
||||
|
||||
// If we made varniship, let it sail.
|
||||
if ( ! empty( $varniship ) ) {
|
||||
$purgeme = $schema . $varniship . $path . $pregex;
|
||||
} else {
|
||||
$purgeme = $schema . $p['host'] . $path . $pregex;
|
||||
}
|
||||
|
||||
wp_remote_request(
|
||||
$purgeme,
|
||||
[
|
||||
'method' => 'PURGE',
|
||||
'blocking' => false,
|
||||
'headers' => [
|
||||
'host' => $p['host'],
|
||||
'X-Purge-Method' => 'regex',
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
do_action( 'after_purge_url', $url, $purgeme ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( is_admin() && function_exists( 'as3cf_assets_init' ) ) :
|
||||
add_action( 'aws_init', 'rocket_as3cf_assets_compatibility', 13 );
|
||||
add_action( 'update_option_as3cf_assets', 'rocket_maybe_deactivate_cdn', 10, 2 );
|
||||
endif;
|
||||
|
||||
/**
|
||||
* Compatibility with WP Offload S3 assets addon.
|
||||
*
|
||||
* @since 2.10.7
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_as3cf_assets_compatibility() {
|
||||
global $as3cf_assets;
|
||||
|
||||
if ( isset( $as3cf_assets ) && $as3cf_assets->is_plugin_setup() && 1 === (int) $as3cf_assets->get_setting( 'enable-addon' ) ) {
|
||||
// Disable WP Rocket CDN option.
|
||||
add_filter( 'rocket_readonly_cdn_option', '__return_true' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deactivate WP Rocket CDN if WP Offload S3 assets addon copy & serve is active.
|
||||
*
|
||||
* @since 2.10.7
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param string $old_value Previous assets option value.
|
||||
* @param string $new_value New assets option value.
|
||||
*/
|
||||
function rocket_maybe_deactivate_cdn( $old_value, $new_value ) {
|
||||
if ( $old_value['enable-addon'] !== $new_value['enable-addon'] && 1 === (int) $new_value['enable-addon'] ) {
|
||||
update_rocket_option( 'cdn', 0 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( is_admin() && ( function_exists( 'as3cf_init' ) || function_exists( 'as3cf_pro_init' ) ) ) :
|
||||
add_action( 'aws_init', 'rocket_as3cf_compatibility', 12 );
|
||||
endif;
|
||||
|
||||
|
||||
/**
|
||||
* Compatibility with WP Offload S3.
|
||||
*
|
||||
* @since 2.10.7
|
||||
* @author Remy Perona
|
||||
*/
|
||||
function rocket_as3cf_compatibility() {
|
||||
global $as3cf;
|
||||
|
||||
if ( isset( $as3cf ) && $as3cf->is_plugin_setup() && 1 === (int) $as3cf->get_setting( 'serve-from-s3' ) ) {
|
||||
// Remove images option from WP Rocket CDN dropdown settings.
|
||||
add_filter( 'rocket_allow_cdn_images', '__return_false' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( function_exists( 'print_link' ) ) :
|
||||
/**
|
||||
* Conflict with WP-Print: don't apply LazyLoad on print pages
|
||||
*
|
||||
* @since 2.6.8
|
||||
*/
|
||||
function rocket_deactivate_lazyload_on_print_pages() {
|
||||
global $wp_query;
|
||||
|
||||
if ( isset( $wp_query->query_vars['print'] ) ) {
|
||||
add_filter( 'do_rocket_lazyload', '__return_false' );
|
||||
}
|
||||
}
|
||||
add_action( 'wp', 'rocket_deactivate_lazyload_on_print_pages' );
|
||||
endif;
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Add WP REST API path to cache exclusion
|
||||
*
|
||||
* @since 2.5.12
|
||||
*
|
||||
* @param array $uri URLs to exclude from cache.
|
||||
* @return array Updated URLs
|
||||
*/
|
||||
function rocket_exclude_wp_rest_api( $uri ) {
|
||||
global $wp_rewrite;
|
||||
|
||||
/**
|
||||
* By default, don't cache the WP REST API.
|
||||
*
|
||||
* @since 2.5.12
|
||||
*
|
||||
* @param bool false will force to cache the WP REST API
|
||||
*/
|
||||
$reject_wp_rest_api = apply_filters( 'rocket_cache_reject_wp_rest_api', true );
|
||||
|
||||
if ( ! $reject_wp_rest_api ) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* `(/[^/]+)?` is used instead of `(/.+)?` to match only one level.
|
||||
* This prevents to match a taxonomy term named `wp-json` (on multisite, the main site's posts and taxonomy archives are prefixed with `blog` => example.com/blog/category/wp-json/).
|
||||
*/
|
||||
$prefix = rocket_is_subfolder_install() ? '(/[^/]+)?' : '';
|
||||
$index = ! empty( $wp_rewrite->index ) ? $wp_rewrite->index : 'index.php';
|
||||
$index = preg_quote( $index, '/' );
|
||||
$suffix = rest_get_url_prefix();
|
||||
$suffix = preg_quote( trim( $suffix, '/' ), '/' );
|
||||
|
||||
/**
|
||||
* Results in:
|
||||
* - Single site: (/index\.php)?/wp\-json(/.*|$)
|
||||
* - Multisite: (/[^/]+)?(/index\.php)?/wp\-json(/.*|$)
|
||||
*/
|
||||
$uri[] = $prefix . '/(' . $index . '/)?(.*)' . $suffix . '(/.*|$)';
|
||||
|
||||
return $uri;
|
||||
}
|
||||
add_filter( 'rocket_cache_reject_uri', 'rocket_exclude_wp_rest_api' );
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action( 'admin_init', 'rocket_clear_cache_after_studiopress_accelerator' );
|
||||
/**
|
||||
* Clear WP Rocket cache after purged the StudioPress Accelerator cache
|
||||
*
|
||||
* @since 2.5.5
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clear_cache_after_studiopress_accelerator() {
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( isset( $GLOBALS['sp_accel_nginx_proxy_cache_purge'] ) && is_a( $GLOBALS['sp_accel_nginx_proxy_cache_purge'], 'SP_Accel_Nginx_Proxy_Cache_Purge' ) && isset( $_REQUEST['_wpnonce'] ) ) {
|
||||
$nonce = $_REQUEST['_wpnonce']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.NonceVerification.Recommended
|
||||
if ( wp_verify_nonce( $nonce, 'sp-accel-purge-url' ) && ! empty( $_REQUEST['cache-purge-url'] ) ) {
|
||||
$submitted_url = sanitize_text_field( wp_unslash( $_REQUEST['cache-purge-url'] ) );
|
||||
|
||||
// Clear the URL.
|
||||
rocket_clean_files( [ $submitted_url ] );
|
||||
} elseif ( wp_verify_nonce( $nonce, 'sp-accel-purge-theme' ) ) {
|
||||
// Clear all caching files.
|
||||
rocket_clean_domain();
|
||||
|
||||
// Preload cache.
|
||||
run_rocket_bot();
|
||||
run_rocket_sitemap_preload();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
add_action( 'after_rocket_clean_domain', 'rocket_clean_studiopress_accelerator' );
|
||||
/**
|
||||
* Call the cache server to purge the cache with StudioPress Accelerator.
|
||||
*
|
||||
* @since 2.5.5
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function rocket_clean_studiopress_accelerator() {
|
||||
if ( isset( $GLOBALS['sp_accel_nginx_proxy_cache_purge'] ) && is_a( $GLOBALS['sp_accel_nginx_proxy_cache_purge'], 'SP_Accel_Nginx_Proxy_Cache_Purge' ) ) {
|
||||
$GLOBALS['sp_accel_nginx_proxy_cache_purge']->cache_flush_theme();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Indicate to bypass rocket optimizations.
|
||||
*
|
||||
* Checks for "nowprocket" query string in the url to bypass rocket processes.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return bool True to indicate should bypass; false otherwise.
|
||||
*/
|
||||
function rocket_bypass() {
|
||||
static $bypass = null;
|
||||
|
||||
if ( rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ) {
|
||||
$bypass = null;
|
||||
}
|
||||
|
||||
if ( ! is_null( $bypass ) ) {
|
||||
return $bypass;
|
||||
}
|
||||
|
||||
$bypass = isset( $_GET['nowprocket'] ) && 0 !== $_GET['nowprocket']; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
|
||||
return $bypass;
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\API;
|
||||
|
||||
use WP_Error;
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
|
||||
class Client {
|
||||
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4/';
|
||||
|
||||
/**
|
||||
* Auth object
|
||||
*
|
||||
* @var AuthInterface
|
||||
*/
|
||||
private $auth;
|
||||
|
||||
/**
|
||||
* An array of arguments for wp_remote_request()
|
||||
*
|
||||
* @var mixed[]
|
||||
*/
|
||||
protected $args = [];
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param AuthInterface $auth Auth implementation.
|
||||
*/
|
||||
public function __construct( AuthInterface $auth ) {
|
||||
$this->auth = $auth;
|
||||
$this->args = [
|
||||
'sslverify' => true,
|
||||
'body' => [],
|
||||
'headers' => [],
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Change client auth.
|
||||
*
|
||||
* @param AuthInterface $auth Client auth.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set_auth( AuthInterface $auth ) {
|
||||
$this->auth = $auth;
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using GET.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param mixed[] $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'get', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using POST.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function post( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'post', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using DELETE.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function delete( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'delete', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using PATCH.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function patch( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'patch', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param string $method Type of method that should be used.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object|WP_Error
|
||||
*/
|
||||
protected function request( $path, $method = 'get', array $data = [] ) {
|
||||
if ( '/ips' !== $path ) {
|
||||
$valid = $this->auth->is_valid_credentials();
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
if ( ! $valid ) {
|
||||
return new WP_Error( 'cloudflare_invalid_credentials', 'Cloudflare credentials are invalid.' );
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->do_remote_request( $path, $method, $data );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$content = wp_remote_retrieve_body( $response );
|
||||
|
||||
if ( empty( $content ) ) {
|
||||
return new WP_Error( 'cloudflare_no_reply', __( 'Cloudflare did not provide any reply. Please try again later.', 'rocket' ) );
|
||||
}
|
||||
|
||||
$content = json_decode( $content );
|
||||
|
||||
if ( ! is_object( $content ) ) {
|
||||
return new WP_Error( 'cloudflare_content_error', __( 'Cloudflare unexpected response', 'rocket' ) );
|
||||
}
|
||||
|
||||
if ( empty( $content->success ) ) {
|
||||
return $this->set_request_error( $content );
|
||||
}
|
||||
|
||||
if ( ! property_exists( $content, 'result' ) ) {
|
||||
return new WP_Error( 'cloudflare_no_reply', __( 'Missing Cloudflare result.', 'rocket' ) );
|
||||
}
|
||||
|
||||
return $content->result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the request remote request.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param string $method Type of method that should be used.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
private function do_remote_request( string $path, string $method = 'GET', array $data = [] ) {
|
||||
$this->args['method'] = strtoupper( $method );
|
||||
|
||||
$headers = [
|
||||
'User-Agent' => 'wp-rocket/' . rocket_get_constant( 'WP_ROCKET_VERSION' ),
|
||||
'Content-Type' => 'application/json',
|
||||
];
|
||||
|
||||
if ( '/ips' !== $path ) {
|
||||
$this->args['headers'] = array_merge( $headers, $this->auth->get_headers() );
|
||||
}
|
||||
|
||||
$this->args['body'] = [];
|
||||
|
||||
if ( ! empty( $data ) ) {
|
||||
$this->args['body'] = wp_json_encode( $data );
|
||||
}
|
||||
|
||||
$response = wp_remote_request( self::CLOUDFLARE_API . $path, $this->args );
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the WP_Error when request is not successful
|
||||
*
|
||||
* @param object $content Response object.
|
||||
*
|
||||
* @return WP_Error
|
||||
*/
|
||||
private function set_request_error( $content ) {
|
||||
$errors = [];
|
||||
|
||||
foreach ( $content->errors as $error ) {
|
||||
if (
|
||||
6003 === $error->code || 9103 === $error->code ) {
|
||||
$msg = __( 'Incorrect Cloudflare email address or API key.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_incorrect_credentials', $msg );
|
||||
}
|
||||
|
||||
if ( 7003 === $error->code ) {
|
||||
$msg = __( 'Incorrect Cloudflare Zone ID.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_incorrect_zone_id', $msg );
|
||||
}
|
||||
|
||||
$errors[] = $error->message;
|
||||
}
|
||||
|
||||
return new WP_Error( 'cloudflare_request_error', wp_sprintf_l( '%l ', $errors ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\API;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
|
||||
class Endpoints {
|
||||
/**
|
||||
* Client instance
|
||||
*
|
||||
* @var Client
|
||||
*/
|
||||
private $client;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Client $client Client instance.
|
||||
*/
|
||||
public function __construct( Client $client ) {
|
||||
$this->client = $client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get zone data.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get_zones( string $zone_id ) {
|
||||
return $this->client->get( "zones/{$zone_id}" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the zone's page rules.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $status Rule status.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function list_pagerules( string $zone_id, string $status ) {
|
||||
return $this->client->get( "zones/{$zone_id}/pagerules?status={$status}" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purges the cache.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function purge( string $zone_id ) {
|
||||
return $this->client->post( "zones/{$zone_id}/purge_cache", [ 'purge_everything' => true ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purges the given URLs.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param array $urls An array of URLs that should be removed from cache.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function purge_files( string $zone_id, array $urls = [] ) {
|
||||
return $this->client->post( "zones/{$zone_id}/purge_cache", [ 'files' => $urls ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's browser cache TTL setting
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Cache TTL value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function update_browser_cache_ttl( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'browser_cache_ttl', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's rocket loader setting.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Rocket Loader value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function update_rocket_loader( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'rocket_loader', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's minify setting.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string[] $value Minify value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function update_minify( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'minify', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's cache level.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Cache level value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function change_cache_level( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'cache_level', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the zone's development mode.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Development mode value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function change_development_mode( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'development_mode', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given setting.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $setting Name of the setting to change.
|
||||
* @param mixed $value Setting value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
protected function update_setting( string $zone_id, $setting, $value ) {
|
||||
return $this->client->patch( "zones/{$zone_id}/settings/{$setting}", [ 'value' => $value ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all of the Cloudflare settings.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get_settings( string $zone_id ) {
|
||||
return $this->client->get( "zones/{$zone_id}/settings" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets Cloudflare's IPs.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get_ips() {
|
||||
return $this->client->get( '/ips' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Change client auth.
|
||||
*
|
||||
* @param AuthInterface $auth Client auth.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function change_auth( AuthInterface $auth ) {
|
||||
$this->client->set_auth( $auth );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\Admin;
|
||||
|
||||
use WP_Rocket\Engine\Admin\Settings\Settings;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
/**
|
||||
* Returns an array of events that this subscriber wants to listen to.
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'admin_notices' => [
|
||||
[ 'maybe_display_purge_notice' ],
|
||||
[ 'maybe_display_update_settings_notice' ],
|
||||
],
|
||||
'rocket_input_sanitize' => [ 'sanitize_options', 20, 2 ],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* This notice is displayed after purging the CloudFlare cache.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function maybe_display_purge_notice() {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = get_current_user_id();
|
||||
$notice = get_transient( $user_id . '_cloudflare_purge_result' );
|
||||
|
||||
if ( ! $notice ) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete_transient( $user_id . '_cloudflare_purge_result' );
|
||||
|
||||
rocket_notice_html(
|
||||
[
|
||||
'status' => $notice['result'],
|
||||
'message' => $notice['message'],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* This notice is displayed after modifying the CloudFlare settings.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function maybe_display_update_settings_notice() {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) || 'settings_page_wprocket' !== $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = get_current_user_id();
|
||||
$notices = get_transient( $user_id . '_cloudflare_update_settings' );
|
||||
|
||||
if ( ! $notices ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$errors = '';
|
||||
$success = '';
|
||||
$pre = '';
|
||||
delete_transient( $user_id . '_cloudflare_update_settings' );
|
||||
|
||||
if ( isset( $notices['pre'] ) ) {
|
||||
$pre = $notices['pre'];
|
||||
|
||||
unset( $notices['pre'] );
|
||||
}
|
||||
|
||||
foreach ( $notices as $notice ) {
|
||||
if ( 'error' === $notice['result'] ) {
|
||||
$errors .= $notice['message'] . '<br>';
|
||||
} elseif ( 'success' === $notice['result'] ) {
|
||||
$success .= $notice['message'] . '<br>';
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $success ) ) {
|
||||
rocket_notice_html(
|
||||
[
|
||||
'message' => $pre . $success,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! empty( $errors ) ) {
|
||||
rocket_notice_html(
|
||||
[
|
||||
'status' => 'error',
|
||||
'message' => $errors,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize Cloudflare options
|
||||
*
|
||||
* @param array $input gtArray of sanitized values after being submitted by the form.
|
||||
* @param Settings $settings Settings instance.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function sanitize_options( $input, $settings ) {
|
||||
$input['do_cloudflare'] = $settings->sanitize_checkbox( $input, 'do_cloudflare' );
|
||||
$input['cloudflare_devmode'] = $settings->sanitize_checkbox( $input, 'cloudflare_devmode' );
|
||||
$input['cloudflare_auto_settings'] = $settings->sanitize_checkbox( $input, 'cloudflare_auto_settings' );
|
||||
$input['cloudflare_protocol_rewrite'] = $settings->sanitize_checkbox( $input, 'cloudflare_protocol_rewrite' );
|
||||
|
||||
$input['cloudflare_email'] = isset( $input['cloudflare_email'] ) ? sanitize_email( $input['cloudflare_email'] ) : '';
|
||||
$input['cloudflare_zone_id'] = isset( $input['cloudflare_zone_id'] ) ? sanitize_text_field( $input['cloudflare_zone_id'] ) : '';
|
||||
|
||||
$input['cloudflare_api_key'] = isset( $input['cloudflare_api_key'] ) ? sanitize_text_field( $input['cloudflare_api_key'] ) : '';
|
||||
|
||||
if ( defined( 'WP_ROCKET_CF_API_KEY' ) ) {
|
||||
$input['cloudflare_api_key'] = rocket_get_constant( 'WP_ROCKET_CF_API_KEY', '' );
|
||||
}
|
||||
|
||||
return $input;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\Auth;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
class APIKey implements AuthInterface {
|
||||
/**
|
||||
* Cloudflare email
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $email = '';
|
||||
|
||||
/**
|
||||
* Cloudflare API Key
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $api_key = '';
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string $email Cloudflare email.
|
||||
* @param string $api_key Cloudflare API key.
|
||||
*/
|
||||
public function __construct( string $email = '', string $api_key = '' ) {
|
||||
$this->email = $email;
|
||||
$this->api_key = $api_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets headers for Cloudflare API request
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_headers(): array {
|
||||
return [
|
||||
'X-Auth-Email' => $this->email,
|
||||
'X-Auth-Key' => $this->api_key,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the credentials are set.
|
||||
*
|
||||
* @return bool|WP_Error true if authorized, false if not, WP_Error if either credential is empty.
|
||||
*/
|
||||
public function is_valid_credentials() {
|
||||
if (
|
||||
empty( $this->email )
|
||||
||
|
||||
empty( $this->api_key )
|
||||
) {
|
||||
return new WP_Error(
|
||||
'cloudflare_credentials_empty',
|
||||
sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Cloudflare email and/or API key are not set. Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return false !== filter_var( $this->email, FILTER_VALIDATE_EMAIL );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace WPMedia\Cloudflare\Auth;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\APIKey;
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
|
||||
class APIKeyFactory implements AuthFactoryInterface {
|
||||
|
||||
|
||||
/**
|
||||
* Options Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
protected $options;
|
||||
|
||||
/**
|
||||
* Instantiate the class.
|
||||
*
|
||||
* @param Options_Data $options Options Data instance.
|
||||
*/
|
||||
public function __construct( Options_Data $options ) {
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a new authentication instance.
|
||||
*
|
||||
* @param array $data Data to inject into the client.
|
||||
* @return AuthInterface
|
||||
*/
|
||||
public function create( array $data = [] ): AuthInterface {
|
||||
|
||||
$cf_api_key = defined( 'WP_ROCKET_CF_API_KEY' ) ? rocket_get_constant( 'WP_ROCKET_CF_API_KEY', '' ) : $this->options->get( 'cloudflare_api_key', '' );
|
||||
|
||||
$email = key_exists( 'cloudflare_email', $data ) ? $data['cloudflare_email'] : $this->options->get( 'cloudflare_email', '' );
|
||||
$api_key = key_exists( 'cloudflare_api_key', $data ) ? $data['cloudflare_api_key'] : $cf_api_key;
|
||||
|
||||
return new APIKey( $email, $api_key );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace WPMedia\Cloudflare\Auth;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
|
||||
interface AuthFactoryInterface {
|
||||
|
||||
/**
|
||||
* Create a new authentication instance.
|
||||
*
|
||||
* @param array $data Data to inject into the client.
|
||||
* @return AuthInterface
|
||||
*/
|
||||
public function create( array $data = [] ): AuthInterface;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\Auth;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
interface AuthInterface {
|
||||
/**
|
||||
* Gets headers for Cloudflare API request
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_headers(): array;
|
||||
|
||||
/**
|
||||
* Checks if the credentials are set.
|
||||
*
|
||||
* @return bool|WP_Error true if authorized, false otherwise, WP_Error if missing credentials.
|
||||
*/
|
||||
public function is_valid_credentials();
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare;
|
||||
|
||||
use CloudFlare\IpRewrite;
|
||||
use DateTimeImmutable;
|
||||
use WP_Error;
|
||||
use WP_Post;
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Addon\Cloudflare\API\Endpoints;
|
||||
|
||||
class Cloudflare {
|
||||
/**
|
||||
* Options Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Endpoints instance.
|
||||
*
|
||||
* @var Endpoints
|
||||
*/
|
||||
private $endpoints;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Options_Data $options WP Rocket options instance.
|
||||
* @param Endpoints $endpoints Endpoints instance.
|
||||
*/
|
||||
public function __construct( Options_Data $options, Endpoints $endpoints ) {
|
||||
$this->endpoints = $endpoints;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check valid connection with Cloudflare
|
||||
*
|
||||
* @param string $zone_id Cloudflare zone ID.
|
||||
* @return bool|mixed|WP_Error
|
||||
*/
|
||||
public function check_connection( string $zone_id = '' ) {
|
||||
$is_valid = get_transient( 'rocket_cloudflare_is_api_keys_valid' );
|
||||
if ( false === $is_valid ) {
|
||||
|
||||
if ( '' === $zone_id ) {
|
||||
$zone_id = $this->options->get( 'cloudflare_zone_id', '' );
|
||||
}
|
||||
|
||||
$is_valid = $this->is_auth_valid( $zone_id );
|
||||
|
||||
set_transient( 'rocket_cloudflare_is_api_keys_valid', $is_valid, 2 * WEEK_IN_SECONDS );
|
||||
}
|
||||
|
||||
return $is_valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate Cloudflare input data.
|
||||
*
|
||||
* @param string $zone_id Cloudflare zone ID.
|
||||
*
|
||||
* @return bool|WP_Error true if credentials are ok, WP_Error otherwise.
|
||||
*/
|
||||
public function is_auth_valid( string $zone_id ) {
|
||||
if ( empty( $zone_id ) ) {
|
||||
$msg = __( 'Missing Cloudflare Zone ID.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_no_zone_id', $msg );
|
||||
}
|
||||
|
||||
$result = $this->endpoints->get_zones( $zone_id );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$zone_found = false;
|
||||
$site_url = get_site_url();
|
||||
|
||||
if ( function_exists( 'domain_mapping_siteurl' ) ) {
|
||||
$site_url = domain_mapping_siteurl( $site_url );
|
||||
}
|
||||
|
||||
$parsed_url = wp_parse_url( $site_url );
|
||||
|
||||
if ( property_exists( $result, 'name' ) && false !== strpos( strtolower( $parsed_url['host'] ), $result->name ) ) {
|
||||
$zone_found = true;
|
||||
}
|
||||
|
||||
if ( ! $zone_found ) {
|
||||
$msg = __( 'It looks like your domain is not set up on Cloudflare.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_zone_not_found', $msg );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if CF has the $action_value set as a Page Rule.
|
||||
*
|
||||
* @param string $action_value Action value.
|
||||
*
|
||||
* @return mixed true/false if $action_value was found or not, WP_Error otherwise.
|
||||
*/
|
||||
public function has_page_rule( $action_value ) {
|
||||
$result = $this->endpoints->list_pagerules( $this->options->get( 'cloudflare_zone_id', '' ), 'active' );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$page_rule = wp_json_encode( $result );
|
||||
|
||||
return (bool) preg_match( '/' . $action_value . '/', $page_rule );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare cache.
|
||||
*
|
||||
* @return mixed true if the purge is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function purge_cloudflare() {
|
||||
$result = $this->endpoints->purge( $this->options->get( 'cloudflare_zone_id', '' ) );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare Cache by URL
|
||||
*
|
||||
* @param WP_Post $post The post object.
|
||||
* @param array $purge_urls URLs cache files to remove.
|
||||
* @param string $lang The post language.
|
||||
*
|
||||
* @return mixed true if the purge is successful, WP_Error otherwise
|
||||
*/
|
||||
public function purge_by_url( $post, $purge_urls, $lang ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
|
||||
$result = $this->endpoints->purge_files( $this->options->get( 'cloudflare_zone_id', '' ), $purge_urls );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Browser Cache TTL in Cloudflare.
|
||||
*
|
||||
* @param string $value Value for Cloudflare browser cache TTL.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_browser_cache_ttl( $value ) {
|
||||
$result = $this->endpoints->update_browser_cache_ttl( $this->options->get( 'cloudflare_zone_id', '' ), (int) $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $this->convert_time( (int) $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert value in seconds to seconds/minutes/hours/days
|
||||
*
|
||||
* @param int $value Value in seconds.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function convert_time( int $value ): string {
|
||||
$base = new DateTimeImmutable( '@0' );
|
||||
$time = new DateTimeImmutable( "@$value" );
|
||||
$format = '%a ' . __( 'days', 'rocket' );
|
||||
|
||||
if ( 60 > $value ) {
|
||||
$format = '%s ' . __( 'seconds', 'rocket' );
|
||||
} elseif ( 3600 > $value ) {
|
||||
$format = '%i ' . __( 'minutes', 'rocket' );
|
||||
} elseif ( 86400 > $value ) {
|
||||
$format = '%h ' . __( 'hours', 'rocket' );
|
||||
}
|
||||
|
||||
return $base->diff( $time )->format( $format );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Rocket Loader.
|
||||
*
|
||||
* @param string $value Value for Cloudflare Rocket Loader.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_rocket_loader( $value ) {
|
||||
$result = $this->endpoints->update_rocket_loader( $this->options->get( 'cloudflare_zone_id', '' ), $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Minification.
|
||||
*
|
||||
* @param string $value Value for Cloudflare minification.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_minify( $value ) {
|
||||
$cf_minify_settings = [
|
||||
'css' => $value,
|
||||
'html' => $value,
|
||||
'js' => $value,
|
||||
];
|
||||
|
||||
$result = $this->endpoints->update_minify( $this->options->get( 'cloudflare_zone_id', '' ), $cf_minify_settings );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Caching level.
|
||||
*
|
||||
* @param string $value Value for Cloudflare caching level.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_cache_level( $value ) {
|
||||
$result = $this->endpoints->change_cache_level( $this->options->get( 'cloudflare_zone_id', '' ), $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Development mode.
|
||||
*
|
||||
* @param string $value Value for Cloudflare development mode.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_devmode( $value ) {
|
||||
if ( 0 === (int) $value ) {
|
||||
$value = 'off';
|
||||
} else {
|
||||
$value = 'on';
|
||||
}
|
||||
|
||||
$result = $this->endpoints->change_development_mode( $this->options->get( 'cloudflare_zone_id', '' ), $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
switch ( $value ) {
|
||||
case 'on':
|
||||
wp_schedule_single_event( time() + 3 * HOUR_IN_SECONDS, 'rocket_cron_deactivate_cloudflare_devmode' );
|
||||
break;
|
||||
case 'off':
|
||||
$next_event = wp_next_scheduled( 'rocket_cron_deactivate_cloudflare_devmode' );
|
||||
|
||||
if ( false !== $next_event ) {
|
||||
wp_unschedule_event( $next_event, 'rocket_cron_deactivate_cloudflare_devmode' );
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the current Cloudflare settings for a given domain.
|
||||
*
|
||||
* @return array|WP_Error Array of Cloudflare settings, WP_Error if any error connection to Cloudflare.
|
||||
*/
|
||||
public function get_settings() {
|
||||
$cf_settings = $this->endpoints->get_settings( $this->options->get( 'cloudflare_zone_id', '' ) );
|
||||
|
||||
if ( is_wp_error( $cf_settings ) ) {
|
||||
return $cf_settings;
|
||||
}
|
||||
|
||||
$browser_cache_ttl = 0;
|
||||
$cache_level = '';
|
||||
$rocket_loader = '';
|
||||
$cf_minify = '';
|
||||
|
||||
foreach ( $cf_settings as $cloudflare_option ) {
|
||||
switch ( $cloudflare_option->id ) {
|
||||
case 'browser_cache_ttl':
|
||||
$browser_cache_ttl = $cloudflare_option->value;
|
||||
break;
|
||||
case 'cache_level':
|
||||
$cache_level = $cloudflare_option->value;
|
||||
break;
|
||||
case 'rocket_loader':
|
||||
$rocket_loader = $cloudflare_option->value;
|
||||
break;
|
||||
case 'minify':
|
||||
$cf_minify = $cloudflare_option->value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$cf_minify_value = 'on';
|
||||
|
||||
if (
|
||||
'off' === $cf_minify->js
|
||||
||
|
||||
'off' === $cf_minify->css
|
||||
||
|
||||
'off' === $cf_minify->html
|
||||
) {
|
||||
$cf_minify_value = 'off';
|
||||
}
|
||||
|
||||
$cf_settings_array = [
|
||||
'cache_level' => $cache_level,
|
||||
'minify' => $cf_minify_value,
|
||||
'rocket_loader' => $rocket_loader,
|
||||
'browser_cache_ttl' => $browser_cache_ttl,
|
||||
];
|
||||
|
||||
return $cf_settings_array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Cloudflare IPs. No API validation needed, all exceptions returns the default CF IPs array.
|
||||
*
|
||||
* @return object Result of API request if successful, default CF IPs otherwise.
|
||||
*/
|
||||
public function get_cloudflare_ips() {
|
||||
$cf_ips = get_transient( 'rocket_cloudflare_ips' );
|
||||
|
||||
if ( false !== $cf_ips ) {
|
||||
return $cf_ips;
|
||||
}
|
||||
|
||||
$cf_ips = $this->endpoints->get_ips();
|
||||
|
||||
if ( is_wp_error( $cf_ips ) ) {
|
||||
// Set default IPs from Cloudflare if call to Cloudflare /ips API does not contain a success.
|
||||
// Prevents from making API calls on each page load.
|
||||
$cf_ips = $this->get_default_ips();
|
||||
}
|
||||
|
||||
set_transient( 'rocket_cloudflare_ips', $cf_ips, 2 * WEEK_IN_SECONDS );
|
||||
|
||||
return $cf_ips;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default Cloudflare IPs.
|
||||
*
|
||||
* @return object Default Cloudflare connecting IPs.
|
||||
*/
|
||||
private function get_default_ips() {
|
||||
$cf_ips = (object) [
|
||||
'ipv4_cidrs' => [],
|
||||
'ipv6_cidrs' => [],
|
||||
];
|
||||
|
||||
$cf_ips->ipv4_cidrs = [
|
||||
'173.245.48.0/20',
|
||||
'103.21.244.0/22',
|
||||
'103.22.200.0/22',
|
||||
'103.31.4.0/22',
|
||||
'141.101.64.0/18',
|
||||
'108.162.192.0/18',
|
||||
'190.93.240.0/20',
|
||||
'188.114.96.0/20',
|
||||
'197.234.240.0/22',
|
||||
'198.41.128.0/17',
|
||||
'162.158.0.0/15',
|
||||
'104.16.0.0/12',
|
||||
'104.24.0.0/14',
|
||||
'172.64.0.0/13',
|
||||
'131.0.72.0/22',
|
||||
];
|
||||
|
||||
$cf_ips->ipv6_cidrs = [
|
||||
'2400:cb00::/32',
|
||||
'2606:4700::/32',
|
||||
'2803:f800::/32',
|
||||
'2405:b500::/32',
|
||||
'2405:8100::/32',
|
||||
'2a06:98c0::/29',
|
||||
'2c0f:f248::/32',
|
||||
];
|
||||
|
||||
return $cf_ips;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Cloudflare IP Rewrite
|
||||
*
|
||||
* @return IpRewrite
|
||||
*/
|
||||
public static function set_ip_rewrite() {
|
||||
static $instance = null;
|
||||
|
||||
if ( is_null( $instance ) ) {
|
||||
$instance = new IpRewrite();
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes Cloudflare Flexible SSL redirect loop
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function fix_cf_flexible_ssl() {
|
||||
$ip_rewrite = self::set_ip_rewrite();
|
||||
|
||||
if ( $ip_rewrite->isCloudFlare() ) {
|
||||
// Fixes Flexible SSL.
|
||||
if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && 'https' === $_SERVER['HTTP_X_FORWARDED_PROTO'] ) {
|
||||
$_SERVER['HTTPS'] = 'on';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change client auth.
|
||||
*
|
||||
* @param AuthInterface $auth Client auth.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function change_auth( AuthInterface $auth ) {
|
||||
$this->endpoints->change_auth( $auth );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Admin\Subscriber as CloudflareAdminSubscriber;
|
||||
use WP_Rocket\Addon\Cloudflare\API\{Client, Endpoints};
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\APIKey;
|
||||
use WP_Rocket\Addon\Cloudflare\Cloudflare;
|
||||
use WP_Rocket\Addon\Cloudflare\Subscriber as CloudflareSubscriber;
|
||||
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
|
||||
use WPMedia\Cloudflare\Auth\APIKeyFactory;
|
||||
|
||||
/**
|
||||
* Service provider for Cloudflare Addon.
|
||||
*/
|
||||
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 = [
|
||||
'cloudflare_client',
|
||||
'cloudflare_endpoints',
|
||||
'cloudflare',
|
||||
'cloudflare_subscriber',
|
||||
'cloudflare_admin_subscriber',
|
||||
];
|
||||
|
||||
/**
|
||||
* Registers items with the container
|
||||
*/
|
||||
public function register() {
|
||||
$options = $this->getContainer()->get( 'options' );
|
||||
|
||||
$this->getLeagueContainer()->add( 'cloudflare_auth_factory', APIKeyFactory::class )->addArgument( $options );
|
||||
|
||||
$this->getLeagueContainer()->add( 'cloudflare_client', Client::class )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_auth_factory' )->create() );
|
||||
$this->getLeagueContainer()->add( 'cloudflare_endpoints', Endpoints::class )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_client' ) );
|
||||
|
||||
$this->getLeagueContainer()->add( 'cloudflare', Cloudflare::class )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_endpoints' ) );
|
||||
$this->getLeagueContainer()->share( 'cloudflare_subscriber', CloudflareSubscriber::class )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare' ) )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'options_api' ) )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_auth_factory' ) )
|
||||
->addTag( 'cloudflare_subscriber' );
|
||||
$this->getLeagueContainer()->share(
|
||||
'cloudflare_admin_subscriber',
|
||||
CloudflareAdminSubscriber::class
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare;
|
||||
|
||||
use WP_Post;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
use WP_Rocket\Admin\{Options, Options_Data};
|
||||
use WPMedia\Cloudflare\Auth\AuthFactoryInterface;
|
||||
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
/**
|
||||
* Cloudflare instance.
|
||||
*
|
||||
* @var Cloudflare
|
||||
*/
|
||||
private $cloudflare;
|
||||
|
||||
/**
|
||||
* Options Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Options instance.
|
||||
*
|
||||
* @var Options
|
||||
*/
|
||||
private $options_api;
|
||||
|
||||
/**
|
||||
* Authentication factory.
|
||||
*
|
||||
* @var AuthFactoryInterface
|
||||
*/
|
||||
protected $auth_factory;
|
||||
|
||||
/**
|
||||
* Creates an instance of the Cloudflare Subscriber.
|
||||
*
|
||||
* @param Cloudflare $cloudflare Cloudflare instance.
|
||||
* @param Options_Data $options WP Rocket options instance.
|
||||
* @param Options $options_api Options instance.
|
||||
* @param AuthFactoryInterface $auth_factory Authentication factory.
|
||||
*/
|
||||
public function __construct( Cloudflare $cloudflare, Options_Data $options, Options $options_api, AuthFactoryInterface $auth_factory ) {
|
||||
$this->options = $options;
|
||||
$this->options_api = $options_api;
|
||||
$this->cloudflare = $cloudflare;
|
||||
$this->auth_factory = $auth_factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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', 'wp_rocket_settings' );
|
||||
|
||||
return [
|
||||
'rocket_varnish_ip' => 'set_varnish_localhost',
|
||||
'rocket_varnish_purge_request_host' => 'set_varnish_purge_request_host',
|
||||
'rocket_cron_deactivate_cloudflare_devmode' => 'deactivate_devmode',
|
||||
'after_rocket_clean_domain' => 'auto_purge',
|
||||
'after_rocket_clean_post' => [ 'auto_purge_by_url', 10, 3 ],
|
||||
'admin_post_rocket_purge_cloudflare' => 'purge_cache',
|
||||
'init' => [ 'set_real_ip', 1 ],
|
||||
'update_option_' . $slug => [
|
||||
[ 'save_cloudflare_options', 10, 2 ],
|
||||
[ 'update_dev_mode', 11, 2 ],
|
||||
],
|
||||
'pre_update_option_' . $slug => [
|
||||
[ 'change_auth', 8, 2 ],
|
||||
[ 'delete_connection_transient', 10, 2 ],
|
||||
[ 'save_cloudflare_old_settings', 10, 2 ],
|
||||
[ 'display_settings_notice', 11, 2 ],
|
||||
],
|
||||
'rocket_buffer' => [ 'protocol_rewrite', PHP_INT_MAX ],
|
||||
'wp_calculate_image_srcset' => [ 'protocol_rewrite_srcset', PHP_INT_MAX ],
|
||||
'rocket_cdn_helper_addons' => 'add_cdn_helper_message',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Varnish IP to localhost if Cloudflare is active.
|
||||
*
|
||||
* @param string|array $varnish_ip Varnish IP.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function set_varnish_localhost( $varnish_ip ) {
|
||||
if ( ! $this->should_filter_varnish() ) {
|
||||
return $varnish_ip;
|
||||
}
|
||||
|
||||
if ( is_string( $varnish_ip ) ) {
|
||||
$varnish_ip = (array) $varnish_ip;
|
||||
}
|
||||
|
||||
$varnish_ip[] = 'localhost';
|
||||
|
||||
return $varnish_ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Host header to the website domain if Cloudflare is active.
|
||||
*
|
||||
* @param string $host the host header value.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function set_varnish_purge_request_host( $host ) {
|
||||
if ( ! $this->should_filter_varnish() ) {
|
||||
return $host;
|
||||
}
|
||||
|
||||
return wp_parse_url( home_url(), PHP_URL_HOST );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we should filter the value for the Varnish purge.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function should_filter_varnish(): bool {
|
||||
// This filter is documented in inc/Addon/Varnish.php.
|
||||
return apply_filters( 'do_rocket_varnish_http_purge', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
|
||||
||
|
||||
$this->options->get( 'varnish_auto_purge', 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically set Cloudflare development mode value to off after 3 hours to reflect Cloudflare behaviour.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function deactivate_devmode() {
|
||||
$this->options->set( 'cloudflare_devmode', 0 );
|
||||
$this->options_api->set( 'settings', $this->options->get_options() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare cache automatically if Cache Everything is set as a Page Rule.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function auto_purge() {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$settings = $this->options_api->get( 'settings', [] );
|
||||
|
||||
$this->options->set_values( $settings );
|
||||
|
||||
$auth = $this->auth_factory->create( $settings );
|
||||
|
||||
$this->cloudflare->change_auth( $auth );
|
||||
|
||||
if ( is_wp_error( $this->cloudflare->check_connection( $this->options->get( 'cloudflare_zone_id', '' ) ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cf_cache_everything = $this->cloudflare->has_page_rule( 'cache_everything' );
|
||||
|
||||
if ( is_wp_error( $cf_cache_everything ) || ! $cf_cache_everything ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Purge CloudFlare.
|
||||
$this->cloudflare->purge_cloudflare();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare cache URLs automatically if Cache Everything is set as a Page Rule.
|
||||
*
|
||||
* @param WP_Post $post The post object.
|
||||
* @param array $purge_urls URLs cache files to remove.
|
||||
* @param string $lang The post language.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function auto_purge_by_url( $post, $purge_urls, $lang ) {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( is_wp_error( $this->cloudflare->check_connection() ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cf_cache_everything = $this->cloudflare->has_page_rule( 'cache_everything' );
|
||||
|
||||
if ( is_wp_error( $cf_cache_everything ) || ! $cf_cache_everything ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add home URL and feeds URLs to Cloudflare clean cache URLs list.
|
||||
$purge_urls[] = get_rocket_i18n_home_url( $lang );
|
||||
$feed_urls = [];
|
||||
$feed_urls[] = get_feed_link();
|
||||
$feed_urls[] = get_feed_link( 'comments_' );
|
||||
|
||||
// this filter is documented in inc/functions/files.php.
|
||||
$feed_urls = apply_filters( 'rocket_clean_home_feeds', $feed_urls );
|
||||
$purge_urls = array_unique( array_merge( $purge_urls, $feed_urls ) );
|
||||
|
||||
// Purge CloudFlare.
|
||||
$this->cloudflare->purge_by_url( $post, $purge_urls, $lang );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge CloudFlare cache.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function purge_cache_no_die() {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection();
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
$cf_purge_result = [
|
||||
'result' => 'error',
|
||||
'message' => sprintf(
|
||||
// translators: %1$s = <strong>, %2$s = </strong>, %3$s = CloudFare API return message.
|
||||
__( '%1$sWP Rocket:%2$s %3$s', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>',
|
||||
$connection->get_error_message()
|
||||
),
|
||||
];
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_purge_result', $cf_purge_result );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Purge CloudFlare.
|
||||
$cf_purge = $this->cloudflare->purge_cloudflare();
|
||||
$cf_purge_result = [
|
||||
'result' => 'success',
|
||||
'message' => sprintf(
|
||||
// translators: %1$s = <strong>, %2$s = </strong>.
|
||||
__( '%1$sWP Rocket:%2$s Cloudflare cache successfully purged.', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
),
|
||||
];
|
||||
|
||||
if ( is_wp_error( $cf_purge ) ) {
|
||||
$cf_purge_result = [
|
||||
'result' => 'error',
|
||||
'message' => sprintf(
|
||||
// translators: %1$s = <strong>, %2$s = </strong>, %3$s = CloudFare API return message.
|
||||
__( '%1$sWP Rocket:%2$s %3$s', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>',
|
||||
$cf_purge->get_error_message()
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_purge_result', $cf_purge_result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge CloudFlare cache.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function purge_cache() {
|
||||
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'rocket_purge_cloudflare' ) ) {
|
||||
wp_nonce_ays( '' );
|
||||
}
|
||||
|
||||
$this->purge_cache_no_die();
|
||||
|
||||
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
|
||||
defined( 'WPMEDIA_IS_TESTING' ) ? wp_die() : exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Real IP from CloudFlare.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set_real_ip() {
|
||||
Cloudflare::set_ip_rewrite();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare dev mode admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare dev mode.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_cloudflare_devmode( $value ) {
|
||||
$result = $this->cloudflare->set_devmode( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare development mode error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare development mode %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare cache_level admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare cache_level.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_cache_level( $value ) {
|
||||
// Set Cache Level to Aggressive.
|
||||
$result = $this->cloudflare->set_cache_level( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare cache level error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
$level = $value;
|
||||
|
||||
if ( 'aggressive' === $result ) {
|
||||
$level = _x( 'standard', 'Cloudflare caching level', 'rocket' );
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the caching level returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare cache level set to %s', 'rocket' ), $level ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare minify admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare minify.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_minify( $value ) {
|
||||
$result = $this->cloudflare->set_minify( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare minification error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare minification %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare rocket loader admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare rocket loader.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_rocket_loader( $value ) {
|
||||
$result = $this->cloudflare->set_rocket_loader( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare rocket loader error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare rocket loader %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare browser cache ttl admin option.
|
||||
*
|
||||
* @param int $value New value for Cloudflare browser cache ttl.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_browser_cache_ttl( $value ) {
|
||||
$result = $this->cloudflare->set_browser_cache_ttl( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare browser cache error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare browser cache set to %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare auto settings admin option.
|
||||
*
|
||||
* @param int $auto_settings New value for Cloudflare auto_settings.
|
||||
* @param string $old_settings Cloudflare cloudflare_old_settings.
|
||||
*
|
||||
* @return array<int, array<string>>
|
||||
*/
|
||||
private function save_cloudflare_auto_settings( $auto_settings, $old_settings ) {
|
||||
$cf_old_settings = explode( ',', $old_settings );
|
||||
|
||||
$result = [];
|
||||
|
||||
// Set Cache Level to Aggressive.
|
||||
$cf_cache_level = isset( $cf_old_settings[0] ) && 0 === $auto_settings ? $cf_old_settings[0] : 'aggressive';
|
||||
$result[] = $this->save_cache_level( $cf_cache_level );
|
||||
|
||||
// Active Minification for HTML, CSS & JS.
|
||||
$cf_minify = isset( $cf_old_settings[1] ) && 0 === $auto_settings ? $cf_old_settings[1] : 'on';
|
||||
$result[] = $this->save_minify( $cf_minify );
|
||||
|
||||
// Deactivate Rocket Loader to prevent conflicts.
|
||||
$cf_rocket_loader = isset( $cf_old_settings[2] ) && 0 === $auto_settings ? $cf_old_settings[2] : 'off';
|
||||
$result[] = $this->save_rocket_loader( $cf_rocket_loader );
|
||||
|
||||
// Set Browser cache to 1 year.
|
||||
$cf_browser_cache_ttl = isset( $cf_old_settings[3] ) && 0 === $auto_settings ? $cf_old_settings[3] : 31536000;
|
||||
$result[] = $this->save_browser_cache_ttl( $cf_browser_cache_ttl );
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the development mode value on Cloudflare
|
||||
*
|
||||
* @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 update_dev_mode( $old_value, $value ) {
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! isset( $old_value['cloudflare_devmode'], $value['cloudflare_devmode'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (int) $old_value['cloudflare_devmode'] === (int) $value['cloudflare_devmode'] ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection( $value['cloudflare_zone_id'] );
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = [
|
||||
'pre' => sprintf(
|
||||
'%1$sWP Rocket:%2$s',
|
||||
'<strong>',
|
||||
'</strong> '
|
||||
),
|
||||
];
|
||||
$update = get_transient( get_current_user_id() . '_cloudflare_update_settings' );
|
||||
|
||||
if ( false !== $update ) {
|
||||
$result = $update;
|
||||
}
|
||||
|
||||
$result[] = $this->save_cloudflare_devmode( $value['cloudflare_devmode'] );
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_update_settings', $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare admin options.
|
||||
*
|
||||
* @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 save_cloudflare_options( $old_value, $value ) {
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! isset( $old_value['cloudflare_auto_settings'], $value['cloudflare_auto_settings'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (int) $old_value['cloudflare_auto_settings'] === (int) $value['cloudflare_auto_settings'] ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection( $value['cloudflare_zone_id'] );
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = [
|
||||
'pre' => sprintf(
|
||||
// translators: %1$s = strong opening tag, %2$s = strong closing tag.
|
||||
__( '%1$sWP Rocket:%2$s Optimal settings activated for Cloudflare:', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
) . '<br>',
|
||||
];
|
||||
|
||||
if ( 0 === (int) $value['cloudflare_auto_settings'] ) {
|
||||
$result['pre'] = sprintf(
|
||||
// translators: %1$s = strong opening tag, %2$s = strong closing tag.
|
||||
__( '%1$sWP Rocket:%2$s Optimal settings deactivated for Cloudflare, reverted to previous settings:', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
) . '<br>';
|
||||
}
|
||||
|
||||
$result = array_merge( $result, $this->save_cloudflare_auto_settings( $value['cloudflare_auto_settings'], $value['cloudflare_old_settings'] ) );
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_update_settings', $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare old settings when the auto settings option is enabled.
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function save_cloudflare_old_settings( $value, $old_value ) {
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( ! isset( $value['cloudflare_auto_settings'], $old_value ['cloudflare_auto_settings'] ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( $value['cloudflare_auto_settings'] === $old_value ['cloudflare_auto_settings'] ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( 0 === (int) $value['cloudflare_auto_settings'] ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$cloudflare_zone_id = key_exists( 'cloudflare_zone_id', $value ) ? $value['cloudflare_zone_id'] : '';
|
||||
|
||||
if ( is_wp_error( $this->cloudflare->check_connection( $cloudflare_zone_id ) ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$cf_settings = $this->cloudflare->get_settings();
|
||||
$value['cloudflare_old_settings'] = ! is_wp_error( $cf_settings )
|
||||
? implode( ',', array_filter( $cf_settings ) )
|
||||
: '';
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the authentification.
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function change_auth( $value, $old_value ) {
|
||||
$auth = $this->auth_factory->create( $value );
|
||||
$this->cloudflare->change_auth( $auth );
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the transient CF connection status when API Key, Email or Zone ID is changed
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function delete_connection_transient( $value, $old_value ) {
|
||||
|
||||
$fields = [
|
||||
'cloudflare_api_key',
|
||||
'cloudflare_email',
|
||||
'cloudflare_zone_id',
|
||||
'cloudflare_devmode',
|
||||
'cloudflare_auto_settings',
|
||||
'cloudflare_protocol_rewrite',
|
||||
];
|
||||
|
||||
$change = false;
|
||||
|
||||
foreach ( $fields as $field ) {
|
||||
$change |= ! isset( $old_value[ $field ], $value[ $field ] ) || $old_value[ $field ] !== $value[ $field ];
|
||||
}
|
||||
|
||||
if ( ! $change ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
delete_transient( get_current_user_id() . '_cloudflare_update_settings' );
|
||||
delete_transient( 'rocket_cloudflare_is_api_keys_valid' );
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the error notice.
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function display_settings_notice( $value, $old_value ) {
|
||||
|
||||
if ( ! key_exists( 'cloudflare_zone_id', $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection( $value['cloudflare_zone_id'] );
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
add_settings_error( 'general', 'cloudflare_api_key_invalid', __( 'WP Rocket: ', 'rocket' ) . '</strong>' . $connection->get_error_message() . '<strong>', 'error' );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove HTTP protocol on script, link, img and form tags.
|
||||
*
|
||||
* @param string $buffer HTML content.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function protocol_rewrite( $buffer ) {
|
||||
if ( ! $this->can_protocol_rewrite() ) {
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
$return = preg_replace( "/(<(script|link|img|form)(?!.*?[\"']\bcanonical\b[\"'])([^>]*)(href|src|action)=[\"'])https?:\\/\\//i", '$1//', $buffer );
|
||||
|
||||
if ( $return ) {
|
||||
$buffer = $return;
|
||||
}
|
||||
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove HTTP protocol on srcset attribute generated by WordPress
|
||||
*
|
||||
* @param array $sources an Array of images sources for srcset.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function protocol_rewrite_srcset( $sources ) {
|
||||
if ( ! $this->can_protocol_rewrite() ) {
|
||||
return $sources;
|
||||
}
|
||||
|
||||
if ( empty( $sources ) ) {
|
||||
return $sources;
|
||||
}
|
||||
|
||||
foreach ( $sources as $i => $source ) {
|
||||
$sources[ $i ]['url'] = str_replace( [ 'http:', 'https:' ], '', $source['url'] );
|
||||
}
|
||||
|
||||
return $sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Can rewrite protocol
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function can_protocol_rewrite(): bool {
|
||||
return $this->options->get( 'do_cloudflare', 0 )
|
||||
&&
|
||||
(
|
||||
$this->options->get( 'cloudflare_protocol_rewrite', 0 )
|
||||
||
|
||||
apply_filters( 'do_rocket_protocol_rewrite', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the helper message on the CDN settings.
|
||||
*
|
||||
* @param string[] $addons Name from the addon that requires the helper message.
|
||||
* @return string[]
|
||||
*/
|
||||
public function add_cdn_helper_message( array $addons ): array {
|
||||
$addons[] = 'Cloudflare';
|
||||
return $addons;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon;
|
||||
|
||||
use WP_Rocket\Addon\Sucuri\Subscriber as SucuriSubscriber;
|
||||
use WP_Rocket\Addon\WebP\AdminSubscriber as WebPAdminSubscriber;
|
||||
use WP_Rocket\Addon\WebP\Subscriber as WebPSubscriber;
|
||||
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
|
||||
|
||||
/**
|
||||
* Service provider for WP Rocket addons.
|
||||
*/
|
||||
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 = [
|
||||
'sucuri_subscriber',
|
||||
'webp_subscriber',
|
||||
'webp_admin_subscriber',
|
||||
];
|
||||
|
||||
/**
|
||||
* Registers items with the container
|
||||
*/
|
||||
public function register() {
|
||||
$options = $this->getContainer()->get( 'options' );
|
||||
|
||||
// Sucuri Addon.
|
||||
$this->getContainer()->share( 'sucuri_subscriber', SucuriSubscriber::class )
|
||||
->addArgument( $options )
|
||||
->addTag( 'common_subscriber' );
|
||||
|
||||
$this->getContainer()->share( 'webp_admin_subscriber', WebPAdminSubscriber::class )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'cdn_subscriber' ) )
|
||||
->addArgument( $this->getContainer()->get( 'beacon' ) )
|
||||
->addTag( 'common_subscriber' );
|
||||
|
||||
$this->getContainer()->share( 'webp_subscriber', WebPSubscriber::class )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'options_api' ) )
|
||||
->addArgument( $this->getContainer()->get( 'cdn_subscriber' ) )
|
||||
->addTag( 'common_subscriber' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Sucuri;
|
||||
|
||||
use WP_Error;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
use WP_Rocket\Logger\Logger;
|
||||
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
|
||||
/**
|
||||
* URL of the API.
|
||||
*
|
||||
* %s is here for the other query args.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const API_URL = 'https://waf.sucuri.net/api?v2&%s';
|
||||
|
||||
/**
|
||||
* Instance of the Option_Data class.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Options_Data $options Instance of the Option_Data class.
|
||||
*/
|
||||
public function __construct( Options_Data $options ) {
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'after_rocket_clean_domain' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_post' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_term' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_user' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_home' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_files' => 'maybe_clean_firewall_cache',
|
||||
'admin_post_rocket_purge_sucuri' => 'do_admin_post_rocket_purge_sucuri',
|
||||
'admin_notices' => 'maybe_print_notice',
|
||||
'rocket_cdn_helper_addons' => 'add_cdn_helper_message',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Sucuri firewall cache.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
public function maybe_clean_firewall_cache() {
|
||||
static $done = false;
|
||||
|
||||
if ( $done ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$done = true;
|
||||
|
||||
if ( ! $this->options->get( 'sucury_waf_cache_sync', 0 ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->clean_firewall_cache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax callback to empty Sucury cache.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
public function do_admin_post_rocket_purge_sucuri() {
|
||||
if ( empty( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'rocket_purge_sucuri' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
|
||||
wp_nonce_ays( '' );
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'rocket_purge_sucuri_cache' ) ) {
|
||||
wp_nonce_ays( '' );
|
||||
}
|
||||
|
||||
$purged = $this->clean_firewall_cache();
|
||||
|
||||
if ( is_wp_error( $purged ) ) {
|
||||
$purged_result = [
|
||||
'result' => 'error',
|
||||
/* translators: %s is the error message returned by the API. */
|
||||
'message' => sprintf( __( 'Sucuri cache purge error: %s', 'rocket' ), $purged->get_error_message() ),
|
||||
];
|
||||
} else {
|
||||
$purged_result = [
|
||||
'result' => 'success',
|
||||
'message' => __( 'The Sucuri cache is being cleared. Note that it may take up to two minutes for it to be fully flushed.', 'rocket' ),
|
||||
];
|
||||
}
|
||||
|
||||
set_transient( get_current_user_id() . '_sucuri_purge_result', $purged_result );
|
||||
|
||||
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
|
||||
die();
|
||||
}
|
||||
|
||||
/**
|
||||
* Print an admin notice if the cache failed to be cleared.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
public function maybe_print_notice() {
|
||||
if ( ! current_user_can( 'rocket_purge_sucuri_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->options->get( 'sucury_waf_cache_sync', 0 ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = get_current_user_id();
|
||||
|
||||
$notice = get_transient( $user_id . '_sucuri_purge_result' );
|
||||
|
||||
if ( ! $notice ) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete_transient( $user_id . '_sucuri_purge_result' );
|
||||
|
||||
rocket_notice_html(
|
||||
[
|
||||
'status' => $notice['result'],
|
||||
'message' => $notice['message'],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell if an API key is well formatted.
|
||||
*
|
||||
* @since 3.2.3
|
||||
*
|
||||
* @param string $api_key An API key.
|
||||
*
|
||||
* @return array|false An array with the keys 'k' and 's' (required by the API) if valid. False otherwise.
|
||||
*/
|
||||
public static function is_api_key_valid( $api_key ) {
|
||||
if ( '' !== $api_key && preg_match( '@^(?<k>[a-z0-9]{32})/(?<s>[a-z0-9]{32})$@', $api_key, $matches ) ) {
|
||||
return $matches;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Sucuri firewall cache.
|
||||
*
|
||||
* @since 3.2
|
||||
*
|
||||
* @return true|WP_Error True on success. A WP_Error object on failure.
|
||||
*/
|
||||
private function clean_firewall_cache() {
|
||||
$api_key = $this->get_api_key();
|
||||
|
||||
if ( is_wp_error( $api_key ) ) {
|
||||
return $api_key;
|
||||
}
|
||||
|
||||
$response = $this->request_api(
|
||||
[
|
||||
'a' => 'clear_cache',
|
||||
'k' => $api_key['k'],
|
||||
's' => $api_key['s'],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
Logger::info(
|
||||
'Sucuri firewall cache cleared.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
]
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the API key.
|
||||
*
|
||||
* @since 3.2
|
||||
*
|
||||
* @return array|WP_Error An array with the keys 'k' and 's', required by the API. A WP_Error object if no key or invalid key.
|
||||
*/
|
||||
private function get_api_key() {
|
||||
$api_key = trim( $this->options->get( 'sucury_waf_api_key', '' ) );
|
||||
|
||||
if ( ! $api_key ) {
|
||||
Logger::error(
|
||||
'API key was not found.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'no_sucuri_api_key', __( 'Sucuri firewall API key was not found.', 'rocket' ) );
|
||||
}
|
||||
|
||||
$matches = self::is_api_key_valid( $api_key );
|
||||
|
||||
if ( ! $matches ) {
|
||||
Logger::error(
|
||||
'API key is invalid.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'invalid_sucuri_api_key', __( 'Sucuri firewall API key is invalid.', 'rocket' ) );
|
||||
}
|
||||
|
||||
return [
|
||||
'k' => $matches['k'],
|
||||
's' => $matches['s'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Request against the API.
|
||||
*
|
||||
* @since 3.2
|
||||
*
|
||||
* @param array $params Parameters to send.
|
||||
*
|
||||
* @return array|WP_Error The response data on success. A WP_Error object on failure.
|
||||
*/
|
||||
private function request_api( $params = [] ) {
|
||||
$params['time'] = time();
|
||||
$params = $this->build_query( $params );
|
||||
$url = sprintf( static::API_URL, $params );
|
||||
|
||||
/**
|
||||
* Filters the arguments for the Sucuri API request
|
||||
*
|
||||
* @since 3.3.4
|
||||
*
|
||||
* @param array $args Arguments for the request.
|
||||
*/
|
||||
$args = apply_filters(
|
||||
'rocket_sucuri_api_request_args',
|
||||
[
|
||||
'timeout' => 5,
|
||||
'redirection' => 5,
|
||||
'httpversion' => '1.1',
|
||||
'blocking' => true,
|
||||
// This filter is documented in wp-includes/class-wp-http-streams.php.
|
||||
'sslverify' => apply_filters( 'https_ssl_verify', true ), // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
|
||||
]
|
||||
);
|
||||
|
||||
$response = wp_remote_get( $url, $args );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
Logger::error(
|
||||
'Error when contacting the API.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response' => $response->get_error_message(),
|
||||
]
|
||||
);
|
||||
|
||||
// translators: %s is an error message.
|
||||
return new WP_Error( 'wp_error_sucuri_api', sprintf( __( 'Error when contacting Sucuri firewall API. Error message was: %s', 'rocket' ), $response->get_error_message() ) );
|
||||
}
|
||||
|
||||
$contents = wp_remote_retrieve_body( $response );
|
||||
|
||||
if ( empty( $contents ) ) {
|
||||
Logger::error(
|
||||
'Could not get a response from the API.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response' => $response,
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'sucuri_api_no_response', __( 'Could not get a response from the Sucuri firewall API.', 'rocket' ) );
|
||||
}
|
||||
|
||||
$data = json_decode( $contents, true );
|
||||
|
||||
if ( ! $data || ! is_array( $data ) ) {
|
||||
Logger::error(
|
||||
'Invalid response from the API.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response_body' => $contents,
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'sucuri_api_invalid_response', __( 'Got an invalid response from the Sucuri firewall API.', 'rocket' ) );
|
||||
}
|
||||
|
||||
if ( empty( $data['status'] ) ) {
|
||||
Logger::error(
|
||||
'The action failed.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response_data' => $data,
|
||||
]
|
||||
);
|
||||
|
||||
if ( empty( $data['messages'] ) || ! is_array( $data['messages'] ) ) {
|
||||
return new WP_Error( 'sucuri_api_error_status', __( 'The Sucuri firewall API returned an unknown error.', 'rocket' ) );
|
||||
}
|
||||
|
||||
// translators: %s is an error message.
|
||||
$message = _n( 'The Sucuri firewall API returned the following error: %s', 'The Sucuri firewall API returned the following errors: %s', count( $data['messages'] ), 'rocket' );
|
||||
$message = sprintf( $message, '<br/>' . implode( '<br/>', $data['messages'] ) );
|
||||
|
||||
return new WP_Error( 'sucuri_api_error_status', $message );
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the helper message on the CDN settings.
|
||||
*
|
||||
* @param string[] $addons Name from the addon that requires the helper message.
|
||||
* @return string[]
|
||||
*/
|
||||
public function add_cdn_helper_message( array $addons ): array {
|
||||
|
||||
if ( ! $this->options->get( 'sucury_waf_cache_sync', false ) ) {
|
||||
return $addons;
|
||||
}
|
||||
|
||||
$addons[] = 'Sucuri';
|
||||
return $addons;
|
||||
}
|
||||
|
||||
/**
|
||||
* An i18n-friendly alternative to the built-in PHP method `http_build_query()`.
|
||||
*
|
||||
* @param array|object $params An array or object containing properties.
|
||||
*
|
||||
* @return string An URL-encoded string.
|
||||
*/
|
||||
private function build_query( $params ): string {
|
||||
if ( ! $params ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$params = (array) $params;
|
||||
|
||||
foreach ( $params as $param => $value ) {
|
||||
$params[ $param ] = $param . '=' . rawurlencode( (string) $value );
|
||||
}
|
||||
|
||||
return implode( '&', $params );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon\Varnish;
|
||||
|
||||
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
|
||||
|
||||
/**
|
||||
* Service provider for Varnish Addon.
|
||||
*/
|
||||
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 = [
|
||||
'varnish',
|
||||
'varnish_subscriber',
|
||||
];
|
||||
|
||||
/**
|
||||
* Registers items with the container
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register() {
|
||||
$this->getContainer()->add( 'varnish', Varnish::class );
|
||||
$this->getContainer()->share( 'varnish_subscriber', Subscriber::class )
|
||||
->addArgument( $this->getContainer()->get( 'varnish' ) )
|
||||
->addArgument( $this->getContainer()->get( 'options' ) )
|
||||
->addTag( 'common_subscriber' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon\Varnish;
|
||||
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
|
||||
/**
|
||||
* Subscriber for the Varnish Purge.
|
||||
*
|
||||
* @since 3.5
|
||||
*/
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
/**
|
||||
* Varnish instance
|
||||
*
|
||||
* @var Varnish
|
||||
*/
|
||||
private $varnish;
|
||||
|
||||
/**
|
||||
* WP Rocket options instance
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Varnish $varnish Varnish instance.
|
||||
* @param Options_Data $options WP Rocket options instance.
|
||||
*/
|
||||
public function __construct( Varnish $varnish, Options_Data $options ) {
|
||||
$this->varnish = $varnish;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'before_rocket_clean_domain' => [ 'clean_domain', 10, 3 ],
|
||||
'before_rocket_clean_file' => [ 'clean_file' ],
|
||||
'rocket_rucss_after_clearing_usedcss' => [ 'clean_file' ],
|
||||
'before_rocket_clean_home' => [ 'clean_home', 10, 2 ],
|
||||
'rocket_rucss_complete_job_status' => [ 'clean_file' ],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if Varnish cache should be purged
|
||||
*
|
||||
* @since 3.5
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function should_purge() {
|
||||
return (
|
||||
/**
|
||||
* Filters the use of the Varnish compatibility add-on
|
||||
*
|
||||
* @param bool $varnish_purge True to use, false otherwise.
|
||||
*/
|
||||
apply_filters( 'do_rocket_varnish_http_purge', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
|
||||
||
|
||||
(bool) $this->options->get( 'varnish_auto_purge', 0 )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears Varnish cache for the whole domain
|
||||
*
|
||||
* @param string $root The path of home cache file.
|
||||
* @param string $lang The current lang to purge.
|
||||
* @param string $url The home url.
|
||||
* @return void
|
||||
*/
|
||||
public function clean_domain( $root, $lang, $url ) {
|
||||
if ( ! $this->should_purge() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->varnish->purge( trailingslashit( $url ) . '?regex' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears a specific page in Varnish cache
|
||||
*
|
||||
* @param string $url The url to purge.
|
||||
* @return void
|
||||
*/
|
||||
public function clean_file( $url ) {
|
||||
if ( ! $this->should_purge() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->varnish->purge( trailingslashit( $url ) . '?regex' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the homepage in Varnish cache
|
||||
*
|
||||
* @param string $root The path of home cache file.
|
||||
* @param string $lang The current lang to purge.
|
||||
* @return void
|
||||
*/
|
||||
public function clean_home( $root, $lang ) {
|
||||
if ( ! $this->should_purge() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$home_url = trailingslashit( get_rocket_i18n_home_url( $lang ) );
|
||||
$home_pagination_url = $home_url . trailingslashit( $GLOBALS['wp_rewrite']->pagination_base ) . '?regex';
|
||||
|
||||
$this->varnish->purge( $home_url );
|
||||
$this->varnish->purge( $home_pagination_url );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon\Varnish;
|
||||
|
||||
/**
|
||||
* Varnish cache purge
|
||||
*
|
||||
* @since 3.5
|
||||
*/
|
||||
class Varnish {
|
||||
/**
|
||||
* Send purge request to Varnish
|
||||
*
|
||||
* @since 3.5
|
||||
*
|
||||
* @param string $url The URL to purge.
|
||||
* @return void
|
||||
*/
|
||||
public function purge( $url ) {
|
||||
$parse_url = get_rocket_parse_url( $url );
|
||||
$x_purge_method = 'default';
|
||||
$regex = '';
|
||||
|
||||
if ( 'regex' === $parse_url['query'] ) {
|
||||
$x_purge_method = 'regex';
|
||||
$regex = '.*';
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the HTTP protocol (scheme)
|
||||
*
|
||||
* @since 2.7.3
|
||||
* @param string $scheme The HTTP protocol
|
||||
*/
|
||||
$scheme = apply_filters( 'rocket_varnish_http_purge_scheme', 'http' );
|
||||
|
||||
/**
|
||||
* Filters the headers to send with the Varnish purge request
|
||||
*
|
||||
* @since 3.1
|
||||
*
|
||||
* @param array $headers Headers to send.
|
||||
*/
|
||||
$headers = apply_filters(
|
||||
'rocket_varnish_purge_headers',
|
||||
[
|
||||
/**
|
||||
* Filters the host value passed in the request headers
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @param string $host The host value.
|
||||
*/
|
||||
'host' => apply_filters( 'rocket_varnish_purge_request_host', $parse_url['host'] ),
|
||||
'X-Purge-Method' => $x_purge_method,
|
||||
]
|
||||
);
|
||||
|
||||
/**
|
||||
* Filters the arguments passed to the Varnish purge request
|
||||
*
|
||||
* @since 3.5
|
||||
*
|
||||
* @param array $args Array of arguments for the request.
|
||||
*/
|
||||
$args = apply_filters(
|
||||
'rocket_varnish_purge_request_args',
|
||||
[
|
||||
'method' => 'PURGE',
|
||||
'blocking' => false,
|
||||
'redirection' => 0,
|
||||
'headers' => $headers,
|
||||
]
|
||||
);
|
||||
|
||||
foreach ( $this->get_varnish_ips() as $ip ) {
|
||||
$host = ! empty( $ip ) ? $ip : str_replace( '*', '', $parse_url['host'] );
|
||||
$purge_url_main = $scheme . '://' . $host . $parse_url['path'];
|
||||
|
||||
/**
|
||||
* Filters the purge url.
|
||||
*
|
||||
* @since 3.6.3
|
||||
*
|
||||
* @param string $purge_url_full Full url contains the main url plus regex pattern.
|
||||
* @param string $purge_url_main Main purge url without any additions params.
|
||||
* @param string $regex Regex string.
|
||||
*/
|
||||
$purge_url = apply_filters(
|
||||
'rocket_varnish_purge_url',
|
||||
$purge_url_main . $regex,
|
||||
$purge_url_main,
|
||||
$regex
|
||||
);
|
||||
|
||||
wp_remote_request( $purge_url, $args );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of Varnish IPs to send the purge request to
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_varnish_ips() {
|
||||
/**
|
||||
* Filter the Varnish IP to call
|
||||
*
|
||||
* @since 2.6.8
|
||||
* @param string|array $varnish_ip The Varnish IP
|
||||
*/
|
||||
$varnish_ip = apply_filters( 'rocket_varnish_ip', [] );
|
||||
$constant = rocket_get_constant( 'WP_ROCKET_VARNISH_IP' );
|
||||
|
||||
if (
|
||||
! empty( $constant )
|
||||
&&
|
||||
empty( $varnish_ip )
|
||||
) {
|
||||
$varnish_ip = $constant;
|
||||
}
|
||||
|
||||
if ( empty( $varnish_ip ) ) {
|
||||
$varnish_ip = [ '' ];
|
||||
} elseif ( is_string( $varnish_ip ) ) {
|
||||
$varnish_ip = (array) $varnish_ip;
|
||||
}
|
||||
|
||||
return $varnish_ip;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"name": "wp-media/module-varnish",
|
||||
"description": "Varnish Addon for WP Rocket",
|
||||
"homepage": "https://github.com/wp-media/module-varnish",
|
||||
"license": "GPL-2.0+",
|
||||
"authors": [
|
||||
{
|
||||
"name": "WP Media",
|
||||
"email": "contact@wp-media.me",
|
||||
"homepage": "https://wp-media.me"
|
||||
}
|
||||
],
|
||||
"type": "library",
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
},
|
||||
"support": {
|
||||
"issues": "https://github.com/wp-media/module-varnish/issues",
|
||||
"source": "https://github.com/wp-media/module-varnish"
|
||||
},
|
||||
"require-dev": {
|
||||
"php": "^7 || ^8",
|
||||
"brain/monkey": "^2.0",
|
||||
"coenjacobs/mozart": "^0.7",
|
||||
"dealerdirect/phpcodesniffer-composer-installer": "^0.5.0",
|
||||
"league/container": "^3.3",
|
||||
"phpcompatibility/phpcompatibility-wp": "^2.0",
|
||||
"phpstan/phpstan": "^0.12.3",
|
||||
"phpunit/phpunit": "^7",
|
||||
"psr/container": "1.0.0",
|
||||
"roave/security-advisories": "dev-master",
|
||||
"szepeviktor/phpstan-wordpress": "^0.7",
|
||||
"wp-coding-standards/wpcs": "^2",
|
||||
"wp-media/event-manager": "^3.1",
|
||||
"wp-media/options": "^3.0",
|
||||
"wp-media/phpunit": "1.1.6"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "WP_Rocket\\Addon\\Varnish\\": "." }
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"WP_Rocket\\Tests\\": "Tests/",
|
||||
"WP_Rocket\\Dependencies\\": "Dependencies/"
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"mozart": {
|
||||
"dep_namespace": "WP_Rocket\\Dependencies\\",
|
||||
"dep_directory": "/Dependencies/",
|
||||
"classmap_directory": "/classes/dependencies/",
|
||||
"classmap_prefix": "WP_Rocket_",
|
||||
"packages": [
|
||||
"league/container"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test-unit": "\"vendor/bin/wpmedia-phpunit\" unit path=Tests/Unit",
|
||||
"test-integration": "\"vendor/bin/wpmedia-phpunit\" integration path=Tests/Integration/",
|
||||
"run-tests": [
|
||||
"@test-unit",
|
||||
"@test-integration"
|
||||
],
|
||||
"install-codestandards": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin::run",
|
||||
"phpcs": "\"vendor/bin/phpcs\" .",
|
||||
"phpcs:fix": "\"vendor/bin/phpcbf\" ",
|
||||
"phpstan": "\"vendor/bin/phpstan\" analyse",
|
||||
"post-install-cmd": [
|
||||
"\"vendor/bin/mozart\" compose",
|
||||
"composer dump-autoload"
|
||||
],
|
||||
"post-update-cmd": [
|
||||
"\"vendor/bin/mozart\" compose",
|
||||
"composer dump-autoload"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\WebP;
|
||||
|
||||
use WP_Rocket\Engine\CDN\Subscriber as CDNSubscriber;
|
||||
use WP_Rocket\Subscriber\Third_Party\Plugins\Images\Webp\Webp_Interface;
|
||||
|
||||
abstract class AbstractWebp {
|
||||
/**
|
||||
* CDNSubscriber instance.
|
||||
*
|
||||
* @var CDNSubscriber
|
||||
*/
|
||||
protected $cdn_subscriber;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @param CDNSubscriber $cdn_subscriber CDNSubscriber instance.
|
||||
*/
|
||||
public function __construct( CDNSubscriber $cdn_subscriber ) {
|
||||
$this->cdn_subscriber = $cdn_subscriber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of active plugins that convert and/or serve webp images.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return array An array of Webp_Interface objects.
|
||||
*/
|
||||
protected function get_webp_plugins() {
|
||||
/**
|
||||
* Add Webp plugins.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $webp_plugins An array of Webp_Interface objects.
|
||||
*/
|
||||
$webp_plugins = (array) apply_filters( 'rocket_webp_plugins', [] );
|
||||
|
||||
if ( ! $webp_plugins ) {
|
||||
// Somebody probably messed up.
|
||||
return [];
|
||||
}
|
||||
|
||||
foreach ( $webp_plugins as $plugin_key => $plugin ) {
|
||||
if ( ! $plugin instanceof Webp_Interface ) {
|
||||
unset( $webp_plugins[ $plugin_key ] );
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! $this->is_plugin_active( $plugin->get_basename() ) ) {
|
||||
unset( $webp_plugins[ $plugin_key ] );
|
||||
}
|
||||
}
|
||||
|
||||
return $webp_plugins;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell if a plugin is active.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @param string $plugin_basename A plugin basename.
|
||||
* @return bool
|
||||
*/
|
||||
protected function is_plugin_active( string $plugin_basename ): bool {
|
||||
if ( doing_action( 'deactivate_' . $plugin_basename ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( doing_action( 'activate_' . $plugin_basename ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return rocket_is_plugin_active( $plugin_basename );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell if WP Rocket uses a CDN for images.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function is_using_cdn(): bool {
|
||||
// Don't use `$this->options_data->get( 'cdn' )` here, we need an up-to-date value when the CDN option changes.
|
||||
$use = get_rocket_option( 'cdn', 0 ) && $this->cdn_subscriber->get_cdn_hosts( [], [ 'all', 'images' ] );
|
||||
/**
|
||||
* Filter whether WP Rocket is using a CDN for webp images.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param bool $use True if WP Rocket is using a CDN for webp images. False otherwise.
|
||||
*/
|
||||
return (bool) apply_filters( 'rocket_webp_is_using_cdn', $use );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\WebP;
|
||||
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Engine\Admin\Beacon\Beacon;
|
||||
use WP_Rocket\Engine\CDN\Subscriber as CDNSubscriber;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
|
||||
class AdminSubscriber extends AbstractWebp implements Subscriber_Interface {
|
||||
/**
|
||||
* Options_Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options_data;
|
||||
|
||||
/**
|
||||
* Beacon instance
|
||||
*
|
||||
* @var Beacon
|
||||
*/
|
||||
private $beacon;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param Options_Data $options_data Options_Data instance.
|
||||
* @param CDNSubscriber $cdn_subscriber CDNSubscriber instance.
|
||||
* @param Beacon $beacon Beacon instance.
|
||||
*/
|
||||
public function __construct( Options_Data $options_data, CDNSubscriber $cdn_subscriber, Beacon $beacon ) {
|
||||
parent::__construct( $cdn_subscriber );
|
||||
|
||||
$this->options_data = $options_data;
|
||||
$this->beacon = $beacon;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'rocket_cache_webp_setting_field' => [
|
||||
[ 'maybe_disable_setting_field' ],
|
||||
[ 'webp_section_description' ],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifies the WebP section description of WP Rocket settings.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $cache_webp_field Section description.
|
||||
* @return array
|
||||
*/
|
||||
public function webp_section_description( $cache_webp_field ) {
|
||||
$webp_beacon = $this->beacon->get_suggest( 'webp' );
|
||||
$webp_plugins = $this->get_webp_plugins();
|
||||
$serving = [];
|
||||
$serving_not_compatible = [];
|
||||
$creating = [];
|
||||
|
||||
if ( $webp_plugins ) {
|
||||
$is_using_cdn = $this->is_using_cdn();
|
||||
|
||||
foreach ( $webp_plugins as $plugin ) {
|
||||
if ( $plugin->is_serving_webp() ) {
|
||||
if ( $is_using_cdn && ! $plugin->is_serving_webp_compatible_with_cdn() ) {
|
||||
// Serving WebP using a method not compatible with CDN.
|
||||
$serving_not_compatible[ $plugin->get_id() ] = $plugin->get_name();
|
||||
} else {
|
||||
// Serving WebP when no CDN or with a method compatible with CDN.
|
||||
$serving[ $plugin->get_id() ] = $plugin->get_name();
|
||||
}
|
||||
}
|
||||
if ( $plugin->is_converting_to_webp() ) {
|
||||
// Generating WebP.
|
||||
$creating[ $plugin->get_id() ] = $plugin->get_name();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $serving ) {
|
||||
// 5, 8.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to serve WebP images so you do not need to enable this option. %2$sMore info%3$s %4$s If you prefer to have WP Rocket serve WebP for you instead, please disable WebP display in %1$s.', 'You are using %1$s to serve WebP images so you do not need to enable this option. %2$sMore info%3$s %4$s If you prefer to have WP Rocket serve WebP for you instead, please disable WebP display in %1$s.', count( $serving ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $serving ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>',
|
||||
'<br>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
/** This filter is documented in inc/classes/buffer/class-cache.php */
|
||||
if ( apply_filters( 'rocket_disable_webp_cache', false ) ) {
|
||||
$cache_webp_field['description'] = esc_html__( 'WebP cache is disabled by filter.', 'rocket' );
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
if ( $serving_not_compatible ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
// 6.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', count( $serving_not_compatible ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $serving_not_compatible ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
// 7.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', count( $serving_not_compatible ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $serving_not_compatible ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
if ( $creating ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
// 3.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', count( $creating ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $creating ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
// 4.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', count( $creating ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $creating ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
// 1.
|
||||
if ( rocket_valid_key() && ! \Imagify_Partner::has_imagify_api_key() ) {
|
||||
$imagify_link = '<a href="#imagify">';
|
||||
} else {
|
||||
// The Imagify page is not displayed.
|
||||
$imagify_link = '<a href="https://wordpress.org/plugins/imagify/" target="_blank" rel="noopener noreferrer">';
|
||||
}
|
||||
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = opening <a> tag, %2$s = closing </a> tag.
|
||||
esc_html__( '%5$sWe have not detected any compatible WebP plugin!%6$s%4$s If you don’t already have WebP images on your site consider using %3$sImagify%2$s or another supported plugin. %1$sMore info%2$s %4$s If you are not using WebP do not enable this option.', 'rocket' ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>',
|
||||
$imagify_link,
|
||||
'<br>',
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
);
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
// 2.
|
||||
$cache_webp_field['description'] = esc_html__( 'WP Rocket will create separate cache files to serve your WebP images.', 'rocket' );
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable 'cache_webp' setting field if another plugin serves WebP.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $cache_webp_field Data to be added to the setting field.
|
||||
* @return array
|
||||
*/
|
||||
public function maybe_disable_setting_field( $cache_webp_field ) {
|
||||
/** This filter is documented in inc/classes/buffer/class-cache.php */
|
||||
if ( ! apply_filters( 'rocket_disable_webp_cache', false ) ) {
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
foreach ( [ 'input_attr', 'container_class' ] as $attr ) {
|
||||
if ( ! isset( $cache_webp_field[ $attr ] ) || ! is_array( $cache_webp_field[ $attr ] ) ) {
|
||||
$cache_webp_field[ $attr ] = [];
|
||||
}
|
||||
}
|
||||
|
||||
$cache_webp_field['input_attr']['disabled'] = 1;
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\WebP;
|
||||
|
||||
use WP_Rocket\Admin\Options;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
use WP_Rocket\Engine\CDN\Subscriber as CDNSubscriber;
|
||||
|
||||
/**
|
||||
* Subscriber for the WebP support.
|
||||
*
|
||||
* @since 3.4
|
||||
*/
|
||||
class Subscriber extends AbstractWebp implements Subscriber_Interface {
|
||||
/**
|
||||
* Options_Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options_data;
|
||||
|
||||
/**
|
||||
* Options instance.
|
||||
*
|
||||
* @var Options
|
||||
*/
|
||||
private $options_api;
|
||||
|
||||
/**
|
||||
* Values of $_SERVER to use for some tests.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $server;
|
||||
|
||||
/**
|
||||
* \WP_Filesystem_Direct instance.
|
||||
*
|
||||
* @var \WP_Filesystem_Direct
|
||||
*/
|
||||
private $filesystem;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param Options_Data $options_data Options_Data instance.
|
||||
* @param Options $options_api Options instance.
|
||||
* @param CDNSubscriber $cdn_subscriber CDNSubscriber instance.
|
||||
* @param array $server Values of $_SERVER to use for the tests. Default is $_SERVER.
|
||||
*/
|
||||
public function __construct( Options_Data $options_data, Options $options_api, CDNSubscriber $cdn_subscriber, $server = null ) {
|
||||
parent::__construct( $cdn_subscriber );
|
||||
|
||||
$this->options_data = $options_data;
|
||||
$this->options_api = $options_api;
|
||||
|
||||
if ( ! isset( $server ) && ! empty( $_SERVER ) && is_array( $_SERVER ) ) {
|
||||
$server = $_SERVER;
|
||||
}
|
||||
|
||||
$this->server = $server && is_array( $server ) ? $server : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'rocket_buffer' => [ 'convert_to_webp', 16 ],
|
||||
'rocket_disable_webp_cache' => 'maybe_disable_webp_cache',
|
||||
'rocket_third_party_webp_change' => 'sync_webp_cache_with_third_party_plugins',
|
||||
'rocket_preload_before_preload_url' => 'add_accept_header',
|
||||
'rocket_lazyload_youtube_thumbnail_extension' => 'change_youtube_thumbnail',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts images extension to WebP if the file exists.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param string $html HTML content.
|
||||
* @return string
|
||||
*/
|
||||
public function convert_to_webp( $html ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
/** This filter is documented in inc/classes/buffer/class-cache.php */
|
||||
if ( apply_filters( 'rocket_disable_webp_cache', false ) ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
if ( ! $this->is_browser_webp_compatible() ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$extensions = $this->get_extensions();
|
||||
$attribute_names = $this->get_attribute_names();
|
||||
|
||||
if (
|
||||
empty( $extensions )
|
||||
||
|
||||
empty( $attribute_names )
|
||||
) {
|
||||
return $html . '<!-- Rocket no webp -->';
|
||||
}
|
||||
|
||||
$extensions = implode( '|', $extensions );
|
||||
$attribute_names = implode( '|', $attribute_names );
|
||||
|
||||
if ( ! preg_match_all( '@["\'\s](?<name>(?:data-(?:[a-z0-9_-]+-)?)?(?:' . $attribute_names . '))\s*=\s*["\']\s*(?<value>(?:https?:/)?/[^"\']+\.(?:' . $extensions . ')[^"\']*?)\s*["\']@is', $html, $attributes, PREG_SET_ORDER ) ) {
|
||||
return $html . '<!-- Rocket no webp -->';
|
||||
}
|
||||
|
||||
if ( ! isset( $this->filesystem ) ) {
|
||||
$this->filesystem = \rocket_direct_filesystem();
|
||||
}
|
||||
|
||||
$has_webp = false;
|
||||
|
||||
foreach ( $attributes as $attribute ) {
|
||||
if ( preg_match( '@srcset$@i', strtolower( $attribute['name'] ) ) ) {
|
||||
// This is a srcset attribute, with probably multiple URLs.
|
||||
$new_value = $this->srcset_to_webp( $attribute['value'], $extensions );
|
||||
} else {
|
||||
// A single URL attibute.
|
||||
$new_value = $this->url_to_webp( $attribute['value'], $extensions );
|
||||
}
|
||||
|
||||
if ( ! $new_value ) {
|
||||
// No webp here.
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace in content.
|
||||
$has_webp = true;
|
||||
$new_attr = preg_replace( '@' . $attribute['name'] . '\s*=\s*["\'][^"\']+["\']@s', $attribute['name'] . '="' . $new_value . '"', $attribute[0] );
|
||||
$html = str_replace( $attribute[0], $new_attr, $html );
|
||||
}
|
||||
|
||||
$has_webp = apply_filters_deprecated( 'rocket_page_has_webp_files', [ $has_webp, $html ], '3.12.6', 'rocket_page_has_webp_files' );
|
||||
|
||||
/**
|
||||
* Tell if the page contains webp files.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param bool $has_webp True if the page contains webp files. False otherwise.
|
||||
* @param string $html The page’s html contents.
|
||||
*/
|
||||
|
||||
$has_webp = apply_filters( 'rocket_page_has_webp_files', $has_webp, $html );
|
||||
|
||||
if ( $has_webp ) {
|
||||
return $html . '<!-- Rocket has webp -->';
|
||||
}
|
||||
|
||||
return $html . '<!-- Rocket no webp -->';
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the WebP cache if a WebP plugin is in use.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param bool $disable_webp_cache True to disable WebP cache. False otherwise (default).
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function maybe_disable_webp_cache( $disable_webp_cache ): bool {
|
||||
return $disable_webp_cache || ! empty( $this->get_plugins_serving_webp() );
|
||||
}
|
||||
|
||||
/**
|
||||
* When a 3rd party plugin enables or disables its webp feature, disable or enable WPR feature accordingly.
|
||||
*
|
||||
* @since 3.4
|
||||
*/
|
||||
public function sync_webp_cache_with_third_party_plugins() {
|
||||
if (
|
||||
$this->options_data->get( 'cache_webp', 0 )
|
||||
&&
|
||||
$this->get_plugins_serving_webp()
|
||||
) {
|
||||
// Disable the cache webp option.
|
||||
$this->options_data->set( 'cache_webp', 0 );
|
||||
$this->options_api->set( 'settings', $this->options_data->get_options() );
|
||||
}
|
||||
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add WebP to the HTTP_ACCEPT headers on preload request when the WebP option is active
|
||||
*
|
||||
* @param array $requests Requests to make.
|
||||
* @return array
|
||||
*/
|
||||
public function add_accept_header( $requests ) {
|
||||
if ( ! is_array( $requests ) || ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
return $requests;
|
||||
}
|
||||
|
||||
return array_map(
|
||||
function ( $request ) {
|
||||
$request['headers']['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
|
||||
$request['headers']['headers']['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
|
||||
return $request;
|
||||
},
|
||||
$requests
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the browser is WebP compatible
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function is_browser_webp_compatible(): bool {
|
||||
// Only to supporting browsers.
|
||||
$http_accept = isset( $this->server['HTTP_ACCEPT'] ) ? $this->server['HTTP_ACCEPT'] : '';
|
||||
|
||||
if (
|
||||
empty( $http_accept )
|
||||
&&
|
||||
function_exists( 'apache_request_headers' )
|
||||
) {
|
||||
$headers = apache_request_headers();
|
||||
$http_accept = isset( $headers['Accept'] ) ? $headers['Accept'] : '';
|
||||
}
|
||||
|
||||
if (
|
||||
! empty( $http_accept )
|
||||
&&
|
||||
false !== strpos( $http_accept, 'webp' )
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->is_user_agent_compatible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the User Agent if the Accept headers is missing the WebP info
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function is_user_agent_compatible(): bool {
|
||||
$user_agent = isset( $this->server['HTTP_USER_AGENT'] ) ? $this->server['HTTP_USER_AGENT'] : '';
|
||||
|
||||
if ( empty( $user_agent ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( preg_match( '#Firefox/(?<version>[0-9]{2,})#i', $user_agent, $matches ) ) {
|
||||
if ( 66 >= (int) $matches['version'] ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ( preg_match( '#(?:iPad|iPhone)(.*)Version/(?<version>[0-9]{2,})#i', $user_agent, $matches ) ) {
|
||||
if ( 14 > (int) $matches['version'] ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( preg_match( '#Version/(?<version>[0-9]{2,})(?:.*)Safari#i', $user_agent, $matches ) ) {
|
||||
if ( 16 > (int) $matches['version'] ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of file extensions that may have a webp version.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_extensions() {
|
||||
$extensions = [ 'jpg', 'jpeg', 'jpe', 'png', 'gif' ];
|
||||
|
||||
/**
|
||||
* Filter the list of file extensions that may have a webp version.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $extensions An array of file extensions.
|
||||
*/
|
||||
$extensions = apply_filters( 'rocket_file_extensions_for_webp', $extensions );
|
||||
$extensions = array_filter(
|
||||
(array) $extensions,
|
||||
function ( $extension ) {
|
||||
return $extension && is_string( $extension );
|
||||
}
|
||||
);
|
||||
|
||||
return array_unique( $extensions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the names of the HTML attributes where WP Rocket must search for image files.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_attribute_names() {
|
||||
$attributes = [ 'href', 'src', 'srcset', 'data-large_image', 'data-thumb' ];
|
||||
|
||||
/**
|
||||
* Filter the names of the HTML attributes where WP Rocket must search for image files.
|
||||
* Don't prepend new names with `data-`, WPR will do it. For example if you want to add `data-foo-bar`, you only need to add `foo-bar` or `bar` to the list.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $attributes An array of HTML attribute names.
|
||||
*/
|
||||
$attributes = apply_filters( 'rocket_attributes_for_webp', $attributes );
|
||||
$attributes = array_filter(
|
||||
(array) $attributes,
|
||||
function ( $attributes ) {
|
||||
return $attributes && is_string( $attributes );
|
||||
}
|
||||
);
|
||||
|
||||
return array_unique( $attributes );
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a URL to an absolute path.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param string $url URL to convert.
|
||||
* @return string|bool
|
||||
*/
|
||||
private function url_to_path( $url ) {
|
||||
static $hosts, $site_host, $subdir_levels;
|
||||
|
||||
$url_host = wp_parse_url( $url, PHP_URL_HOST );
|
||||
|
||||
// Relative path.
|
||||
if ( null === $url_host ) {
|
||||
if ( ! isset( $subdir_levels ) ) {
|
||||
$subdir_levels = substr_count( preg_replace( '@^https?://@', '', site_url() ), '/' );
|
||||
}
|
||||
|
||||
if ( $subdir_levels ) {
|
||||
$url = ltrim( $url, '/' );
|
||||
$url = explode( '/', $url );
|
||||
array_splice( $url, 0, $subdir_levels );
|
||||
$url = implode( '/', $url );
|
||||
}
|
||||
|
||||
$url = site_url( $url );
|
||||
}
|
||||
|
||||
// CDN.
|
||||
if ( ! isset( $hosts ) ) {
|
||||
$hosts = $this->cdn_subscriber->get_cdn_hosts( [], [ 'all', 'images' ] );
|
||||
$hosts = array_flip( $hosts );
|
||||
}
|
||||
|
||||
if ( isset( $hosts[ $url_host ] ) ) {
|
||||
if ( ! isset( $site_host ) ) {
|
||||
$site_host = wp_parse_url( site_url( '/' ), PHP_URL_HOST );
|
||||
}
|
||||
if ( $site_host ) {
|
||||
$url = preg_replace( '@^(https?://)' . $url_host . '/@', '$1' . $site_host . '/', $url );
|
||||
}
|
||||
}
|
||||
|
||||
// URL to path.
|
||||
$url = preg_replace( '@^https?:@', '', $url );
|
||||
$paths = $this->get_url_to_path_associations();
|
||||
|
||||
if ( ! $paths ) {
|
||||
// Uh?
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $paths as $asso_url => $asso_path ) {
|
||||
if ( 0 === strpos( $url, $asso_url ) ) {
|
||||
$file = str_replace( $asso_url, $asso_path, $url );
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ( empty( $file ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** This filter is documented in inc/functions/formatting.php. */
|
||||
return (string) apply_filters( 'rocket_url_to_path', $file, $url );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a webp extension to a URL.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param string $url A URL (I see you're very surprised).
|
||||
* @param string $extensions Allowed image extensions.
|
||||
* @return string|bool The same URL with a webp extension if the file exists. False if the webp image doesn't exist.
|
||||
*/
|
||||
private function url_to_webp( $url, $extensions ) {
|
||||
if ( ! preg_match( '@^(?<src>.+\.(?<extension>' . $extensions . '))(?<query>(?:\?.*)?)$@i', $url, $src_url ) ) {
|
||||
// Probably something like "image.jpg.webp".
|
||||
return false;
|
||||
}
|
||||
|
||||
$src_path = $this->url_to_path( $src_url['src'] );
|
||||
|
||||
if ( empty( $src_path ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$src_path_webp = preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_path );
|
||||
|
||||
if ( $this->filesystem->exists( $src_path_webp ) ) {
|
||||
// File name: image.jpg => image.webp.
|
||||
return preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_url['src'] ) . $src_url['query'];
|
||||
}
|
||||
|
||||
if ( $this->filesystem->exists( $src_path . '.webp' ) ) {
|
||||
// File name: image.jpg => image.jpg.webp.
|
||||
return $src_url['src'] . '.webp' . $src_url['query'];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add webp extension to URLs in a srcset attribute.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array|string $srcset_values Value of a srcset attribute.
|
||||
* @param string $extensions Allowed image extensions.
|
||||
* @return string|bool An array similar to $srcset_values, with webp extensions when the files exist. False if no images have webp versions.
|
||||
*/
|
||||
private function srcset_to_webp( $srcset_values, $extensions ) {
|
||||
if ( ! $srcset_values ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( ! is_array( $srcset_values ) ) {
|
||||
$srcset_values = explode( ',', $srcset_values );
|
||||
}
|
||||
|
||||
$has_webp = false;
|
||||
|
||||
foreach ( $srcset_values as $i => $srcset_value ) {
|
||||
$srcset_value = preg_split( '/\s+/', trim( $srcset_value ) );
|
||||
|
||||
if ( count( $srcset_value ) > 2 ) {
|
||||
// Not a good idea to have space characters in file name.
|
||||
$descriptor = array_pop( $srcset_value );
|
||||
$srcset_value = [
|
||||
'url' => implode( ' ', $srcset_value ),
|
||||
'descriptor' => $descriptor,
|
||||
];
|
||||
} else {
|
||||
$srcset_value = [
|
||||
'url' => $srcset_value[0],
|
||||
'descriptor' => ! empty( $srcset_value[1] ) ? $srcset_value[1] : '1x',
|
||||
];
|
||||
}
|
||||
|
||||
$url_webp = $this->url_to_webp( $srcset_value['url'], $extensions );
|
||||
|
||||
if ( ! $url_webp ) {
|
||||
$srcset_values[ $i ] = implode( ' ', $srcset_value );
|
||||
continue;
|
||||
}
|
||||
|
||||
$srcset_values[ $i ] = $url_webp . ' ' . $srcset_value['descriptor'];
|
||||
$has_webp = true;
|
||||
}
|
||||
|
||||
if ( ! $has_webp ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return implode( ',', $srcset_values );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of URL/path associations.
|
||||
* URLs are schema-less, starting by a double slash.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array A list of URLs as keys and paths as values.
|
||||
*/
|
||||
private function get_url_to_path_associations() {
|
||||
static $list;
|
||||
|
||||
if ( isset( $list ) ) {
|
||||
return $list;
|
||||
}
|
||||
|
||||
$content_url = preg_replace( '@^https?:@', '', content_url( '/' ) );
|
||||
$content_dir = trailingslashit( rocket_get_constant( 'WP_CONTENT_DIR' ) );
|
||||
$list = [ $content_url => $content_dir ];
|
||||
|
||||
$upload = wp_upload_dir();
|
||||
$upload_dir = trailingslashit( $upload['basedir'] );
|
||||
|
||||
if ( strpos( $upload_dir, $content_dir ) === false ) {
|
||||
$upload_url = preg_replace( '@^https?:@', '', trailingslashit( $upload['baseurl'] ) );
|
||||
$list[ $upload_url ] = $upload_dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the list of URL/path associations.
|
||||
* The URLs with the most levels must come first.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $list The list of URL/path associations. URLs are schema-less, starting by a double slash.
|
||||
*/
|
||||
$list = apply_filters( 'rocket_url_to_path_associations', $list );
|
||||
$list = array_filter(
|
||||
$list,
|
||||
function ( $path, $url ) {
|
||||
return $path && $url && is_string( $path ) && is_string( $url );
|
||||
},
|
||||
ARRAY_FILTER_USE_BOTH
|
||||
);
|
||||
|
||||
if ( $list ) {
|
||||
$list = array_unique( $list );
|
||||
}
|
||||
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of plugins that serve webp images on frontend.
|
||||
* If the CDN is used, this won't list plugins that use a technique not compatible with CDN.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array The WebP plugin names.
|
||||
*/
|
||||
private function get_plugins_serving_webp() {
|
||||
$webp_plugins = $this->get_webp_plugins();
|
||||
|
||||
if ( ! $webp_plugins ) {
|
||||
// Somebody probably messed up.
|
||||
return [];
|
||||
}
|
||||
|
||||
$checks = [];
|
||||
$is_using_cdn = $this->is_using_cdn();
|
||||
|
||||
foreach ( $webp_plugins as $plugin ) {
|
||||
if ( $is_using_cdn && $plugin->is_serving_webp_compatible_with_cdn() ) {
|
||||
$checks[ $plugin->get_id() ] = $plugin->get_name();
|
||||
} elseif ( ! $is_using_cdn && $plugin->is_serving_webp() ) {
|
||||
$checks[ $plugin->get_id() ] = $plugin->get_name();
|
||||
}
|
||||
}
|
||||
|
||||
return $checks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change Youtube thumbnail extension.
|
||||
*
|
||||
* @param string $extension extension from the thumbnail.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function change_youtube_thumbnail( $extension ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
return $extension;
|
||||
}
|
||||
return 'webp';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
/**
|
||||
* Plugin Name: Action Scheduler
|
||||
* Plugin URI: https://actionscheduler.org
|
||||
* Description: A robust scheduling library for use in WordPress plugins.
|
||||
* Author: Automattic
|
||||
* Author URI: https://automattic.com/
|
||||
* Version: 3.5.4
|
||||
* License: GPLv3
|
||||
*
|
||||
* Copyright 2019 Automattic, Inc. (https://automattic.com/contact/)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* @package ActionScheduler
|
||||
*/
|
||||
|
||||
if ( ! function_exists( 'action_scheduler_register_3_dot_5_dot_4' ) && function_exists( 'add_action' ) ) { // WRCS: DEFINED_VERSION.
|
||||
|
||||
if ( ! class_exists( 'ActionScheduler_Versions', false ) ) {
|
||||
require_once __DIR__ . '/classes/ActionScheduler_Versions.php';
|
||||
add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 );
|
||||
}
|
||||
|
||||
add_action( 'plugins_loaded', 'action_scheduler_register_3_dot_5_dot_4', 0, 0 ); // WRCS: DEFINED_VERSION.
|
||||
|
||||
/**
|
||||
* Registers this version of Action Scheduler.
|
||||
*/
|
||||
function action_scheduler_register_3_dot_5_dot_4() { // WRCS: DEFINED_VERSION.
|
||||
$versions = ActionScheduler_Versions::instance();
|
||||
$versions->register( '3.5.4', 'action_scheduler_initialize_3_dot_5_dot_4' ); // WRCS: DEFINED_VERSION.
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes this version of Action Scheduler.
|
||||
*/
|
||||
function action_scheduler_initialize_3_dot_5_dot_4() { // WRCS: DEFINED_VERSION.
|
||||
// A final safety check is required even here, because historic versions of Action Scheduler
|
||||
// followed a different pattern (in some unusual cases, we could reach this point and the
|
||||
// ActionScheduler class is already defined—so we need to guard against that).
|
||||
if ( ! class_exists( 'ActionScheduler', false ) ) {
|
||||
require_once __DIR__ . '/classes/abstracts/ActionScheduler.php';
|
||||
ActionScheduler::init( __FILE__ );
|
||||
}
|
||||
}
|
||||
|
||||
// Support usage in themes - load this version if no plugin has loaded a version yet.
|
||||
if ( did_action( 'plugins_loaded' ) && ! doing_action( 'plugins_loaded' ) && ! class_exists( 'ActionScheduler', false ) ) {
|
||||
action_scheduler_initialize_3_dot_5_dot_4(); // WRCS: DEFINED_VERSION.
|
||||
do_action( 'action_scheduler_pre_theme_init' );
|
||||
ActionScheduler_Versions::initialize_latest_version();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
*** Changelog ***
|
||||
|
||||
= 3.5.4 - 2023-01-17 =
|
||||
* Add pre filters during action registration.
|
||||
* Async scheduling.
|
||||
* Calculate timeouts based on total actions.
|
||||
* Correctly order the parameters for `ActionScheduler_ActionFactory`'s calls to `single_unique`.
|
||||
* Fetch action in memory first before releasing claim to avoid deadlock.
|
||||
* PHP 8.2: declare property to fix creation of dynamic property warning.
|
||||
* PHP 8.2: fix "Using ${var} in strings is deprecated, use {$var} instead".
|
||||
* Prevent `undefined variable` warning for `$num_pastdue_actions`.
|
||||
|
||||
= 3.5.3 - 2022-11-09 =
|
||||
* Query actions with partial match.
|
||||
|
||||
= 3.5.2 - 2022-09-16 =
|
||||
* Fix - erroneous 3.5.1 release.
|
||||
|
||||
= 3.5.1 - 2022-09-13 =
|
||||
* Maintenance on A/S docs.
|
||||
* fix: PHP 8.2 deprecated notice.
|
||||
|
||||
= 3.5.0 - 2022-08-25 =
|
||||
* Add - The active view link within the "Tools > Scheduled Actions" screen is now clickable.
|
||||
* Add - A warning when there are past-due actions.
|
||||
* Enhancement - Added the ability to schedule unique actions via an atomic operation.
|
||||
* Enhancement - Improvements to cache invalidation when processing batches (when running on WordPress 6.0+).
|
||||
* Enhancement - If a recurring action is found to be consistently failing, it will stop being rescheduled.
|
||||
* Enhancement - Adds a new "Past Due" view to the scheduled actions list table.
|
||||
|
||||
= 3.4.2 - 2022-06-08 =
|
||||
* Fix - Change the include for better linting.
|
||||
* Fix - update: Added Action scheduler completed action hook.
|
||||
|
||||
= 3.4.1 - 2022-05-24 =
|
||||
* Fix - Change the include for better linting.
|
||||
* Fix - Fix the documented return type.
|
||||
|
||||
= 3.4.0 - 2021-10-29 =
|
||||
* Enhancement - Number of items per page can now be set for the Scheduled Actions view (props @ovidiul). #771
|
||||
* Fix - Do not lower the max_execution_time if it is already set to 0 (unlimited) (props @barryhughes). #755
|
||||
* Fix - Avoid triggering autoloaders during the version resolution process (props @olegabr). #731 & #776
|
||||
* Dev - ActionScheduler_wcSystemStatus PHPCS fixes (props @ovidiul). #761
|
||||
* Dev - ActionScheduler_DBLogger.php PHPCS fixes (props @ovidiul). #768
|
||||
* Dev - Fixed phpcs for ActionScheduler_Schedule_Deprecated (props @ovidiul). #762
|
||||
* Dev - Improve actions table indicies (props @glagonikas). #774 & #777
|
||||
* Dev - PHPCS fixes for ActionScheduler_DBStore.php (props @ovidiul). #769 & #778
|
||||
* Dev - PHPCS Fixes for ActionScheduler_Abstract_ListTable (props @ovidiul). #763 & #779
|
||||
* Dev - Adds new filter action_scheduler_claim_actions_order_by to allow tuning of the claim query (props @glagonikas). #773
|
||||
* Dev - PHPCS fixes for ActionScheduler_WpPostStore class (props @ovidiul). #780
|
||||
|
||||
= 3.3.0 - 2021-09-15 =
|
||||
* Enhancement - Adds as_has_scheduled_action() to provide a performant way to test for existing actions. #645
|
||||
* Fix - Improves compatibility with environments where NO_ZERO_DATE is enabled. #519
|
||||
* Fix - Adds safety checks to guard against errors when our database tables cannot be created. #645
|
||||
* Dev - Now supports queries that use multiple statuses. #649
|
||||
* Dev - Minimum requirements for WordPress and PHP bumped (to 5.2 and 5.6 respectively). #723
|
||||
|
||||
= 3.2.1 - 2021-06-21 =
|
||||
* Fix - Add extra safety/account for different versions of AS and different loading patterns. #714
|
||||
* Fix - Handle hidden columns (Tools → Scheduled Actions) | #600.
|
||||
|
||||
= 3.2.0 - 2021-06-03 =
|
||||
* Fix - Add "no ordering" option to as_next_scheduled_action().
|
||||
* Fix - Add secondary scheduled date checks when claiming actions (DBStore) | #634.
|
||||
* Fix - Add secondary scheduled date checks when claiming actions (wpPostStore) | #634.
|
||||
* Fix - Adds a new index to the action table, reducing the potential for deadlocks (props: @glagonikas).
|
||||
* Fix - Fix unit tests infrastructure and adapt tests to PHP 8.
|
||||
* Fix - Identify in-use data store.
|
||||
* Fix - Improve test_migration_is_scheduled.
|
||||
* Fix - PHP notice on list table.
|
||||
* Fix - Speed up clean up and batch selects.
|
||||
* Fix - Update pending dependencies.
|
||||
* Fix - [PHP 8.0] Only pass action arg values through to do_action_ref_array().
|
||||
* Fix - [PHP 8] Set the PHP version to 7.1 in composer.json for PHP 8 compatibility.
|
||||
* Fix - add is_initialized() to docs.
|
||||
* Fix - fix file permissions.
|
||||
* Fix - fixes #664 by replacing __ with esc_html__.
|
||||
|
||||
= 3.1.6 - 2020-05-12 =
|
||||
* Change log starts.
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_ActionClaim
|
||||
*/
|
||||
class ActionScheduler_ActionClaim {
|
||||
private $id = '';
|
||||
private $action_ids = array();
|
||||
|
||||
public function __construct( $id, array $action_ids ) {
|
||||
$this->id = $id;
|
||||
$this->action_ids = $action_ids;
|
||||
}
|
||||
|
||||
public function get_id() {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function get_actions() {
|
||||
return $this->action_ids;
|
||||
}
|
||||
}
|
||||
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_ActionFactory
|
||||
*/
|
||||
class ActionScheduler_ActionFactory {
|
||||
|
||||
/**
|
||||
* Return stored actions for given params.
|
||||
*
|
||||
* @param string $status The action's status in the data store.
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass to callbacks when the hook is triggered.
|
||||
* @param ActionScheduler_Schedule $schedule The action's schedule.
|
||||
* @param string $group A group to put the action in.
|
||||
*
|
||||
* @return ActionScheduler_Action An instance of the stored action.
|
||||
*/
|
||||
public function get_stored_action( $status, $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) {
|
||||
|
||||
switch ( $status ) {
|
||||
case ActionScheduler_Store::STATUS_PENDING:
|
||||
$action_class = 'ActionScheduler_Action';
|
||||
break;
|
||||
case ActionScheduler_Store::STATUS_CANCELED:
|
||||
$action_class = 'ActionScheduler_CanceledAction';
|
||||
if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) && ! is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) {
|
||||
$schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() );
|
||||
}
|
||||
break;
|
||||
default:
|
||||
$action_class = 'ActionScheduler_FinishedAction';
|
||||
break;
|
||||
}
|
||||
|
||||
$action_class = apply_filters( 'action_scheduler_stored_action_class', $action_class, $status, $hook, $args, $schedule, $group );
|
||||
|
||||
$action = new $action_class( $hook, $args, $schedule, $group );
|
||||
|
||||
/**
|
||||
* Allow 3rd party code to change the instantiated action for a given hook, args, schedule and group.
|
||||
*
|
||||
* @param ActionScheduler_Action $action The instantiated action.
|
||||
* @param string $hook The instantiated action's hook.
|
||||
* @param array $args The instantiated action's args.
|
||||
* @param ActionScheduler_Schedule $schedule The instantiated action's schedule.
|
||||
* @param string $group The instantiated action's group.
|
||||
*/
|
||||
return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue an action to run one time, as soon as possible (rather a specific scheduled time).
|
||||
*
|
||||
* This method creates a new action using the NullSchedule. In practice, this results in an action scheduled to
|
||||
* execute "now". Therefore, it will generally run as soon as possible but is not prioritized ahead of other actions
|
||||
* that are already past-due.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param string $group A group to put the action in.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
*/
|
||||
public function async( $hook, $args = array(), $group = '' ) {
|
||||
return $this->async_unique( $hook, $args, $group, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as async, but also supports $unique param.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param string $group A group to put the action in.
|
||||
* @param bool $unique Whether to ensure the action is unique.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
*/
|
||||
public function async_unique( $hook, $args = array(), $group = '', $unique = true ) {
|
||||
$schedule = new ActionScheduler_NullSchedule();
|
||||
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||
return $unique ? $this->store_unique_action( $action, $unique ) : $this->store( $action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create single action.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param int $when Unix timestamp when the action will run.
|
||||
* @param string $group A group to put the action in.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
*/
|
||||
public function single( $hook, $args = array(), $when = null, $group = '' ) {
|
||||
return $this->single_unique( $hook, $args, $when, $group, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create single action only if there is no pending or running action with same name and params.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param int $when Unix timestamp when the action will run.
|
||||
* @param string $group A group to put the action in.
|
||||
* @param bool $unique Whether action scheduled should be unique.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
*/
|
||||
public function single_unique( $hook, $args = array(), $when = null, $group = '', $unique = true ) {
|
||||
$date = as_get_datetime_object( $when );
|
||||
$schedule = new ActionScheduler_SimpleSchedule( $date );
|
||||
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||
return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the first instance of an action recurring on a given interval.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param int $first Unix timestamp for the first run.
|
||||
* @param int $interval Seconds between runs.
|
||||
* @param string $group A group to put the action in.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
*/
|
||||
public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) {
|
||||
return $this->recurring_unique( $hook, $args, $first, $interval, $group, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the first instance of an action recurring on a given interval only if there is no pending or running action with same name and params.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param int $first Unix timestamp for the first run.
|
||||
* @param int $interval Seconds between runs.
|
||||
* @param string $group A group to put the action in.
|
||||
* @param bool $unique Whether action scheduled should be unique.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
*/
|
||||
public function recurring_unique( $hook, $args = array(), $first = null, $interval = null, $group = '', $unique = true ) {
|
||||
if ( empty( $interval ) ) {
|
||||
return $this->single_unique( $hook, $args, $first, $group, $unique );
|
||||
}
|
||||
$date = as_get_datetime_object( $first );
|
||||
$schedule = new ActionScheduler_IntervalSchedule( $date, $interval );
|
||||
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||
return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the first instance of an action recurring on a Cron schedule.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param int $base_timestamp The first instance of the action will be scheduled
|
||||
* to run at a time calculated after this timestamp matching the cron
|
||||
* expression. This can be used to delay the first instance of the action.
|
||||
* @param int $schedule A cron definition string.
|
||||
* @param string $group A group to put the action in.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
*/
|
||||
public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) {
|
||||
return $this->cron_unique( $hook, $args, $base_timestamp, $schedule, $group, false );
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create the first instance of an action recurring on a Cron schedule only if there is no pending or running action with same name and params.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs.
|
||||
* @param array $args Args to pass when the hook is triggered.
|
||||
* @param int $base_timestamp The first instance of the action will be scheduled
|
||||
* to run at a time calculated after this timestamp matching the cron
|
||||
* expression. This can be used to delay the first instance of the action.
|
||||
* @param int $schedule A cron definition string.
|
||||
* @param string $group A group to put the action in.
|
||||
* @param bool $unique Whether action scheduled should be unique.
|
||||
*
|
||||
* @return int The ID of the stored action.
|
||||
**/
|
||||
public function cron_unique( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '', $unique = true ) {
|
||||
if ( empty( $schedule ) ) {
|
||||
return $this->single_unique( $hook, $args, $base_timestamp, $group, $unique );
|
||||
}
|
||||
$date = as_get_datetime_object( $base_timestamp );
|
||||
$cron = CronExpression::factory( $schedule );
|
||||
$schedule = new ActionScheduler_CronSchedule( $date, $cron );
|
||||
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||
return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a successive instance of a recurring or cron action.
|
||||
*
|
||||
* Importantly, the action will be rescheduled to run based on the current date/time.
|
||||
* That means when the action is scheduled to run in the past, the next scheduled date
|
||||
* will be pushed forward. For example, if a recurring action set to run every hour
|
||||
* was scheduled to run 5 seconds ago, it will be next scheduled for 1 hour in the
|
||||
* future, which is 1 hour and 5 seconds from when it was last scheduled to run.
|
||||
*
|
||||
* Alternatively, if the action is scheduled to run in the future, and is run early,
|
||||
* likely via manual intervention, then its schedule will change based on the time now.
|
||||
* For example, if a recurring action set to run every day, and is run 12 hours early,
|
||||
* it will run again in 24 hours, not 36 hours.
|
||||
*
|
||||
* This slippage is less of an issue with Cron actions, as the specific run time can
|
||||
* be set for them to run, e.g. 1am each day. In those cases, and entire period would
|
||||
* need to be missed before there was any change is scheduled, e.g. in the case of an
|
||||
* action scheduled for 1am each day, the action would need to run an entire day late.
|
||||
*
|
||||
* @param ActionScheduler_Action $action The existing action.
|
||||
*
|
||||
* @return string The ID of the stored action
|
||||
* @throws InvalidArgumentException If $action is not a recurring action.
|
||||
*/
|
||||
public function repeat( $action ) {
|
||||
$schedule = $action->get_schedule();
|
||||
$next = $schedule->get_next( as_get_datetime_object() );
|
||||
|
||||
if ( is_null( $next ) || ! $schedule->is_recurring() ) {
|
||||
throw new InvalidArgumentException( __( 'Invalid action - must be a recurring action.', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
$schedule_class = get_class( $schedule );
|
||||
$new_schedule = new $schedule( $next, $schedule->get_recurrence(), $schedule->get_first_date() );
|
||||
$new_action = new ActionScheduler_Action( $action->get_hook(), $action->get_args(), $new_schedule, $action->get_group() );
|
||||
return $this->store( $new_action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save action to database.
|
||||
*
|
||||
* @param ActionScheduler_Action $action Action object to save.
|
||||
*
|
||||
* @return int The ID of the stored action
|
||||
*/
|
||||
protected function store( ActionScheduler_Action $action ) {
|
||||
$store = ActionScheduler_Store::instance();
|
||||
return $store->save_action( $action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Store action if it's unique.
|
||||
*
|
||||
* @param ActionScheduler_Action $action Action object to store.
|
||||
*
|
||||
* @return int ID of the created action. Will be 0 if action was not created.
|
||||
*/
|
||||
protected function store_unique_action( ActionScheduler_Action $action ) {
|
||||
$store = ActionScheduler_Store::instance();
|
||||
return method_exists( $store, 'save_unique_action' ) ?
|
||||
$store->save_unique_action( $action ) : $store->save_action( $action );
|
||||
}
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_AdminView
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
|
||||
|
||||
private static $admin_view = NULL;
|
||||
|
||||
private static $screen_id = 'tools_page_action-scheduler';
|
||||
|
||||
/** @var ActionScheduler_ListTable */
|
||||
protected $list_table;
|
||||
|
||||
/**
|
||||
* @return ActionScheduler_AdminView
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function instance() {
|
||||
|
||||
if ( empty( self::$admin_view ) ) {
|
||||
$class = apply_filters('action_scheduler_admin_view_class', 'ActionScheduler_AdminView');
|
||||
self::$admin_view = new $class();
|
||||
}
|
||||
|
||||
return self::$admin_view;
|
||||
}
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || false == DOING_AJAX ) ) {
|
||||
|
||||
if ( class_exists( 'WooCommerce' ) ) {
|
||||
add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) );
|
||||
add_action( 'woocommerce_system_status_report', array( $this, 'system_status_report' ) );
|
||||
add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) );
|
||||
}
|
||||
|
||||
add_action( 'admin_menu', array( $this, 'register_menu' ) );
|
||||
add_action( 'admin_notices', array( $this, 'maybe_check_pastdue_actions' ) );
|
||||
add_action( 'current_screen', array( $this, 'add_help_tabs' ) );
|
||||
}
|
||||
}
|
||||
|
||||
public function system_status_report() {
|
||||
$table = new ActionScheduler_wcSystemStatus( ActionScheduler::store() );
|
||||
$table->render();
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers action-scheduler into WooCommerce > System status.
|
||||
*
|
||||
* @param array $tabs An associative array of tab key => label.
|
||||
* @return array $tabs An associative array of tab key => label, including Action Scheduler's tabs
|
||||
*/
|
||||
public function register_system_status_tab( array $tabs ) {
|
||||
$tabs['action-scheduler'] = __( 'Scheduled Actions', 'action-scheduler' );
|
||||
|
||||
return $tabs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include Action Scheduler's administration under the Tools menu.
|
||||
*
|
||||
* A menu under the Tools menu is important for backward compatibility (as that's
|
||||
* where it started), and also provides more convenient access than the WooCommerce
|
||||
* System Status page, and for sites where WooCommerce isn't active.
|
||||
*/
|
||||
public function register_menu() {
|
||||
$hook_suffix = add_submenu_page(
|
||||
'tools.php',
|
||||
__( 'Scheduled Actions', 'action-scheduler' ),
|
||||
__( 'Scheduled Actions', 'action-scheduler' ),
|
||||
'manage_options',
|
||||
'action-scheduler',
|
||||
array( $this, 'render_admin_ui' )
|
||||
);
|
||||
add_action( 'load-' . $hook_suffix , array( $this, 'process_admin_ui' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers processing of any pending actions.
|
||||
*/
|
||||
public function process_admin_ui() {
|
||||
$this->get_list_table();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the Admin UI
|
||||
*/
|
||||
public function render_admin_ui() {
|
||||
$table = $this->get_list_table();
|
||||
$table->display_page();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the admin UI object and process any requested actions.
|
||||
*
|
||||
* @return ActionScheduler_ListTable
|
||||
*/
|
||||
protected function get_list_table() {
|
||||
if ( null === $this->list_table ) {
|
||||
$this->list_table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
|
||||
$this->list_table->process_actions();
|
||||
}
|
||||
|
||||
return $this->list_table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Action: admin_notices
|
||||
*
|
||||
* Maybe check past-due actions, and print notice.
|
||||
*
|
||||
* @uses $this->check_pastdue_actions()
|
||||
*/
|
||||
public function maybe_check_pastdue_actions() {
|
||||
|
||||
# Filter to prevent checking actions (ex: inappropriate user).
|
||||
if ( ! apply_filters( 'action_scheduler_check_pastdue_actions', current_user_can( 'manage_options' ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
# Get last check transient.
|
||||
$last_check = get_transient( 'action_scheduler_last_pastdue_actions_check' );
|
||||
|
||||
# If transient exists, we're within interval, so bail.
|
||||
if ( ! empty( $last_check ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
# Perform the check.
|
||||
$this->check_pastdue_actions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check past-due actions, and print notice.
|
||||
*
|
||||
* @todo update $link_url to "Past-due" filter when released (see issue #510, PR #511)
|
||||
*/
|
||||
protected function check_pastdue_actions() {
|
||||
|
||||
# Set thresholds.
|
||||
$threshold_seconds = ( int ) apply_filters( 'action_scheduler_pastdue_actions_seconds', DAY_IN_SECONDS );
|
||||
$threshhold_min = ( int ) apply_filters( 'action_scheduler_pastdue_actions_min', 1 );
|
||||
|
||||
// Set fallback value for past-due actions count.
|
||||
$num_pastdue_actions = 0;
|
||||
|
||||
// Allow third-parties to preempt the default check logic.
|
||||
$check = apply_filters( 'action_scheduler_pastdue_actions_check_pre', null );
|
||||
|
||||
// If no third-party preempted and there are no past-due actions, return early.
|
||||
if ( ! is_null( $check ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
# Scheduled actions query arguments.
|
||||
$query_args = array(
|
||||
'date' => as_get_datetime_object( time() - $threshold_seconds ),
|
||||
'status' => ActionScheduler_Store::STATUS_PENDING,
|
||||
'per_page' => $threshhold_min,
|
||||
);
|
||||
|
||||
# If no third-party preempted, run default check.
|
||||
if ( is_null( $check ) ) {
|
||||
$store = ActionScheduler_Store::instance();
|
||||
$num_pastdue_actions = ( int ) $store->query_actions( $query_args, 'count' );
|
||||
|
||||
# Check if past-due actions count is greater than or equal to threshold.
|
||||
$check = ( $num_pastdue_actions >= $threshhold_min );
|
||||
$check = ( bool ) apply_filters( 'action_scheduler_pastdue_actions_check', $check, $num_pastdue_actions, $threshold_seconds, $threshhold_min );
|
||||
}
|
||||
|
||||
# If check failed, set transient and abort.
|
||||
if ( ! boolval( $check ) ) {
|
||||
$interval = apply_filters( 'action_scheduler_pastdue_actions_check_interval', round( $threshold_seconds / 4 ), $threshold_seconds );
|
||||
set_transient( 'action_scheduler_last_pastdue_actions_check', time(), $interval );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$actions_url = add_query_arg( array(
|
||||
'page' => 'action-scheduler',
|
||||
'status' => 'past-due',
|
||||
'order' => 'asc',
|
||||
), admin_url( 'tools.php' ) );
|
||||
|
||||
# Print notice.
|
||||
echo '<div class="notice notice-warning"><p>';
|
||||
printf(
|
||||
_n(
|
||||
// translators: 1) is the number of affected actions, 2) is a link to an admin screen.
|
||||
'<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due action</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation »</a>',
|
||||
'<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due actions</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation »</a>',
|
||||
$num_pastdue_actions,
|
||||
'action-scheduler'
|
||||
),
|
||||
$num_pastdue_actions,
|
||||
esc_attr( esc_url( $actions_url ) )
|
||||
);
|
||||
echo '</p></div>';
|
||||
|
||||
# Facilitate third-parties to evaluate and print notices.
|
||||
do_action( 'action_scheduler_pastdue_actions_extra_notices', $query_args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide more information about the screen and its data in the help tab.
|
||||
*/
|
||||
public function add_help_tabs() {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( ! $screen || self::$screen_id != $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$as_version = ActionScheduler_Versions::instance()->latest_version();
|
||||
$screen->add_help_tab(
|
||||
array(
|
||||
'id' => 'action_scheduler_about',
|
||||
'title' => __( 'About', 'action-scheduler' ),
|
||||
'content' =>
|
||||
'<h2>' . sprintf( __( 'About Action Scheduler %s', 'action-scheduler' ), $as_version ) . '</h2>' .
|
||||
'<p>' .
|
||||
__( 'Action Scheduler is a scalable, traceable job queue for background processing large sets of actions. Action Scheduler works by triggering an action hook to run at some time in the future. Scheduled actions can also be scheduled to run on a recurring schedule.', 'action-scheduler' ) .
|
||||
'</p>',
|
||||
)
|
||||
);
|
||||
|
||||
$screen->add_help_tab(
|
||||
array(
|
||||
'id' => 'action_scheduler_columns',
|
||||
'title' => __( 'Columns', 'action-scheduler' ),
|
||||
'content' =>
|
||||
'<h2>' . __( 'Scheduled Action Columns', 'action-scheduler' ) . '</h2>' .
|
||||
'<ul>' .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) .
|
||||
'</ul>',
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
/**
|
||||
* ActionScheduler_AsyncRequest_QueueRunner
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* ActionScheduler_AsyncRequest_QueueRunner class.
|
||||
*/
|
||||
class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request {
|
||||
|
||||
/**
|
||||
* Data store for querying actions
|
||||
*
|
||||
* @var ActionScheduler_Store
|
||||
* @access protected
|
||||
*/
|
||||
protected $store;
|
||||
|
||||
/**
|
||||
* Prefix for ajax hooks
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $prefix = 'as';
|
||||
|
||||
/**
|
||||
* Action for ajax hooks
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $action = 'async_request_queue_runner';
|
||||
|
||||
/**
|
||||
* Initiate new async request
|
||||
*/
|
||||
public function __construct( ActionScheduler_Store $store ) {
|
||||
parent::__construct();
|
||||
$this->store = $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle async requests
|
||||
*
|
||||
* Run a queue, and maybe dispatch another async request to run another queue
|
||||
* if there are still pending actions after completing a queue in this request.
|
||||
*/
|
||||
protected function handle() {
|
||||
do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context
|
||||
|
||||
$sleep_seconds = $this->get_sleep_seconds();
|
||||
|
||||
if ( $sleep_seconds ) {
|
||||
sleep( $sleep_seconds );
|
||||
}
|
||||
|
||||
$this->maybe_dispatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the async request runner is needed and allowed to run, dispatch a request.
|
||||
*/
|
||||
public function maybe_dispatch() {
|
||||
if ( ! $this->allow() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->dispatch();
|
||||
ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Only allow async requests when needed.
|
||||
*
|
||||
* Also allow 3rd party code to disable running actions via async requests.
|
||||
*/
|
||||
protected function allow() {
|
||||
|
||||
if ( ! has_action( 'action_scheduler_run_queue' ) || ActionScheduler::runner()->has_maximum_concurrent_batches() || ! $this->store->has_pending_actions_due() ) {
|
||||
$allow = false;
|
||||
} else {
|
||||
$allow = true;
|
||||
}
|
||||
|
||||
return apply_filters( 'action_scheduler_allow_async_request_runner', $allow );
|
||||
}
|
||||
|
||||
/**
|
||||
* Chaining async requests can crash MySQL. A brief sleep call in PHP prevents that.
|
||||
*/
|
||||
protected function get_sleep_seconds() {
|
||||
return apply_filters( 'action_scheduler_async_request_sleep_seconds', 5, $this );
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Compatibility
|
||||
*/
|
||||
class ActionScheduler_Compatibility {
|
||||
|
||||
/**
|
||||
* Converts a shorthand byte value to an integer byte value.
|
||||
*
|
||||
* Wrapper for wp_convert_hr_to_bytes(), moved to load.php in WordPress 4.6 from media.php
|
||||
*
|
||||
* @link https://secure.php.net/manual/en/function.ini-get.php
|
||||
* @link https://secure.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
|
||||
*
|
||||
* @param string $value A (PHP ini) byte value, either shorthand or ordinary.
|
||||
* @return int An integer byte value.
|
||||
*/
|
||||
public static function convert_hr_to_bytes( $value ) {
|
||||
if ( function_exists( 'wp_convert_hr_to_bytes' ) ) {
|
||||
return wp_convert_hr_to_bytes( $value );
|
||||
}
|
||||
|
||||
$value = strtolower( trim( $value ) );
|
||||
$bytes = (int) $value;
|
||||
|
||||
if ( false !== strpos( $value, 'g' ) ) {
|
||||
$bytes *= GB_IN_BYTES;
|
||||
} elseif ( false !== strpos( $value, 'm' ) ) {
|
||||
$bytes *= MB_IN_BYTES;
|
||||
} elseif ( false !== strpos( $value, 'k' ) ) {
|
||||
$bytes *= KB_IN_BYTES;
|
||||
}
|
||||
|
||||
// Deal with large (float) values which run into the maximum integer size.
|
||||
return min( $bytes, PHP_INT_MAX );
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to raise the PHP memory limit for memory intensive processes.
|
||||
*
|
||||
* Only allows raising the existing limit and prevents lowering it.
|
||||
*
|
||||
* Wrapper for wp_raise_memory_limit(), added in WordPress v4.6.0
|
||||
*
|
||||
* @return bool|int|string The limit that was set or false on failure.
|
||||
*/
|
||||
public static function raise_memory_limit() {
|
||||
if ( function_exists( 'wp_raise_memory_limit' ) ) {
|
||||
return wp_raise_memory_limit( 'admin' );
|
||||
}
|
||||
|
||||
$current_limit = @ini_get( 'memory_limit' );
|
||||
$current_limit_int = self::convert_hr_to_bytes( $current_limit );
|
||||
|
||||
if ( -1 === $current_limit_int ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$wp_max_limit = WP_MAX_MEMORY_LIMIT;
|
||||
$wp_max_limit_int = self::convert_hr_to_bytes( $wp_max_limit );
|
||||
$filtered_limit = apply_filters( 'admin_memory_limit', $wp_max_limit );
|
||||
$filtered_limit_int = self::convert_hr_to_bytes( $filtered_limit );
|
||||
|
||||
if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
|
||||
if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) {
|
||||
return $filtered_limit;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
|
||||
if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) {
|
||||
return $wp_max_limit;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to raise the PHP timeout for time intensive processes.
|
||||
*
|
||||
* Only allows raising the existing limit and prevents lowering it. Wrapper for wc_set_time_limit(), when available.
|
||||
*
|
||||
* @param int $limit The time limit in seconds.
|
||||
*/
|
||||
public static function raise_time_limit( $limit = 0 ) {
|
||||
$limit = (int) $limit;
|
||||
$max_execution_time = (int) ini_get( 'max_execution_time' );
|
||||
|
||||
/*
|
||||
* If the max execution time is already unlimited (zero), or if it exceeds or is equal to the proposed
|
||||
* limit, there is no reason for us to make further changes (we never want to lower it).
|
||||
*/
|
||||
if (
|
||||
0 === $max_execution_time
|
||||
|| ( $max_execution_time >= $limit && $limit !== 0 )
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( function_exists( 'wc_set_time_limit' ) ) {
|
||||
wc_set_time_limit( $limit );
|
||||
} elseif ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved
|
||||
@set_time_limit( $limit ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
|
||||
}
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
use Action_Scheduler\Migration\Controller;
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_DataController
|
||||
*
|
||||
* The main plugin/initialization class for the data stores.
|
||||
*
|
||||
* Responsible for hooking everything up with WordPress.
|
||||
*
|
||||
* @package Action_Scheduler
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_DataController {
|
||||
/** Action data store class name. */
|
||||
const DATASTORE_CLASS = 'ActionScheduler_DBStore';
|
||||
|
||||
/** Logger data store class name. */
|
||||
const LOGGER_CLASS = 'ActionScheduler_DBLogger';
|
||||
|
||||
/** Migration status option name. */
|
||||
const STATUS_FLAG = 'action_scheduler_migration_status';
|
||||
|
||||
/** Migration status option value. */
|
||||
const STATUS_COMPLETE = 'complete';
|
||||
|
||||
/** Migration minimum required PHP version. */
|
||||
const MIN_PHP_VERSION = '5.5';
|
||||
|
||||
/** @var ActionScheduler_DataController */
|
||||
private static $instance;
|
||||
|
||||
/** @var int */
|
||||
private static $sleep_time = 0;
|
||||
|
||||
/** @var int */
|
||||
private static $free_ticks = 50;
|
||||
|
||||
/**
|
||||
* Get a flag indicating whether the migration environment dependencies are met.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function dependencies_met() {
|
||||
$php_support = version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' );
|
||||
return $php_support && apply_filters( 'action_scheduler_migration_dependencies_met', true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a flag indicating whether the migration is complete.
|
||||
*
|
||||
* @return bool Whether the flag has been set marking the migration as complete
|
||||
*/
|
||||
public static function is_migration_complete() {
|
||||
return get_option( self::STATUS_FLAG ) === self::STATUS_COMPLETE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the migration as complete.
|
||||
*/
|
||||
public static function mark_migration_complete() {
|
||||
update_option( self::STATUS_FLAG, self::STATUS_COMPLETE );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unmark migration when a plugin is de-activated. Will not work in case of silent activation, for example in an update.
|
||||
* We do this to mitigate the bug of lost actions which happens if there was an AS 2.x to AS 3.x migration in the past, but that plugin is now
|
||||
* deactivated and the site was running on AS 2.x again.
|
||||
*/
|
||||
public static function mark_migration_incomplete() {
|
||||
delete_option( self::STATUS_FLAG );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the action store class name.
|
||||
*
|
||||
* @param string $class Classname of the store class.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function set_store_class( $class ) {
|
||||
return self::DATASTORE_CLASS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the action logger class name.
|
||||
*
|
||||
* @param string $class Classname of the logger class.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function set_logger_class( $class ) {
|
||||
return self::LOGGER_CLASS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the sleep time in seconds.
|
||||
*
|
||||
* @param integer $sleep_time The number of seconds to pause before resuming operation.
|
||||
*/
|
||||
public static function set_sleep_time( $sleep_time ) {
|
||||
self::$sleep_time = (int) $sleep_time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the tick count required for freeing memory.
|
||||
*
|
||||
* @param integer $free_ticks The number of ticks to free memory on.
|
||||
*/
|
||||
public static function set_free_ticks( $free_ticks ) {
|
||||
self::$free_ticks = (int) $free_ticks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Free memory if conditions are met.
|
||||
*
|
||||
* @param int $ticks Current tick count.
|
||||
*/
|
||||
public static function maybe_free_memory( $ticks ) {
|
||||
if ( self::$free_ticks && 0 === $ticks % self::$free_ticks ) {
|
||||
self::free_memory();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce memory footprint by clearing the database query and object caches.
|
||||
*/
|
||||
public static function free_memory() {
|
||||
if ( 0 < self::$sleep_time ) {
|
||||
/* translators: %d: amount of time */
|
||||
\WP_CLI::warning( sprintf( _n( 'Stopped the insanity for %d second', 'Stopped the insanity for %d seconds', self::$sleep_time, 'action-scheduler' ), self::$sleep_time ) );
|
||||
sleep( self::$sleep_time );
|
||||
}
|
||||
|
||||
\WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) );
|
||||
|
||||
/**
|
||||
* @var $wpdb \wpdb
|
||||
* @var $wp_object_cache \WP_Object_Cache
|
||||
*/
|
||||
global $wpdb, $wp_object_cache;
|
||||
|
||||
$wpdb->queries = array();
|
||||
|
||||
if ( ! is_a( $wp_object_cache, 'WP_Object_Cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$wp_object_cache->group_ops = array();
|
||||
$wp_object_cache->stats = array();
|
||||
$wp_object_cache->memcache_debug = array();
|
||||
$wp_object_cache->cache = array();
|
||||
|
||||
if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) {
|
||||
call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to table datastores if migration is complete.
|
||||
* Otherwise, proceed with the migration if the dependencies have been met.
|
||||
*/
|
||||
public static function init() {
|
||||
if ( self::is_migration_complete() ) {
|
||||
add_filter( 'action_scheduler_store_class', array( 'ActionScheduler_DataController', 'set_store_class' ), 100 );
|
||||
add_filter( 'action_scheduler_logger_class', array( 'ActionScheduler_DataController', 'set_logger_class' ), 100 );
|
||||
add_action( 'deactivate_plugin', array( 'ActionScheduler_DataController', 'mark_migration_incomplete' ) );
|
||||
} elseif ( self::dependencies_met() ) {
|
||||
Controller::init();
|
||||
}
|
||||
|
||||
add_action( 'action_scheduler/progress_tick', array( 'ActionScheduler_DataController', 'maybe_free_memory' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Singleton factory.
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( ! isset( self::$instance ) ) {
|
||||
self::$instance = new static();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* ActionScheduler DateTime class.
|
||||
*
|
||||
* This is a custom extension to DateTime that
|
||||
*/
|
||||
class ActionScheduler_DateTime extends DateTime {
|
||||
|
||||
/**
|
||||
* UTC offset.
|
||||
*
|
||||
* Only used when a timezone is not set. When a timezone string is
|
||||
* used, this will be set to 0.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $utcOffset = 0;
|
||||
|
||||
/**
|
||||
* Get the unix timestamp of the current object.
|
||||
*
|
||||
* Missing in PHP 5.2 so just here so it can be supported consistently.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function getTimestamp() {
|
||||
return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the UTC offset.
|
||||
*
|
||||
* This represents a fixed offset instead of a timezone setting.
|
||||
*
|
||||
* @param $offset
|
||||
*/
|
||||
public function setUtcOffset( $offset ) {
|
||||
$this->utcOffset = intval( $offset );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the timezone offset.
|
||||
*
|
||||
* @return int
|
||||
* @link http://php.net/manual/en/datetime.getoffset.php
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function getOffset() {
|
||||
return $this->utcOffset ? $this->utcOffset : parent::getOffset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the TimeZone associated with the DateTime
|
||||
*
|
||||
* @param DateTimeZone $timezone
|
||||
*
|
||||
* @return static
|
||||
* @link http://php.net/manual/en/datetime.settimezone.php
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function setTimezone( $timezone ) {
|
||||
$this->utcOffset = 0;
|
||||
parent::setTimezone( $timezone );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the timestamp with the WordPress timezone offset added or subtracted.
|
||||
*
|
||||
* @since 3.0.0
|
||||
* @return int
|
||||
*/
|
||||
public function getOffsetTimestamp() {
|
||||
return $this->getTimestamp() + $this->getOffset();
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* ActionScheduler Exception Interface.
|
||||
*
|
||||
* Facilitates catching Exceptions unique to Action Scheduler.
|
||||
*
|
||||
* @package ActionScheduler
|
||||
* @since 2.1.0
|
||||
*/
|
||||
interface ActionScheduler_Exception {}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_FatalErrorMonitor
|
||||
*/
|
||||
class ActionScheduler_FatalErrorMonitor {
|
||||
/** @var ActionScheduler_ActionClaim */
|
||||
private $claim = NULL;
|
||||
/** @var ActionScheduler_Store */
|
||||
private $store = NULL;
|
||||
private $action_id = 0;
|
||||
|
||||
public function __construct( ActionScheduler_Store $store ) {
|
||||
$this->store = $store;
|
||||
}
|
||||
|
||||
public function attach( ActionScheduler_ActionClaim $claim ) {
|
||||
$this->claim = $claim;
|
||||
add_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
|
||||
add_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0, 1 );
|
||||
add_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0, 0 );
|
||||
add_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0, 0 );
|
||||
add_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0, 0 );
|
||||
}
|
||||
|
||||
public function detach() {
|
||||
$this->claim = NULL;
|
||||
$this->untrack_action();
|
||||
remove_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
|
||||
remove_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0 );
|
||||
remove_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0 );
|
||||
remove_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0 );
|
||||
remove_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0 );
|
||||
}
|
||||
|
||||
public function track_current_action( $action_id ) {
|
||||
$this->action_id = $action_id;
|
||||
}
|
||||
|
||||
public function untrack_action() {
|
||||
$this->action_id = 0;
|
||||
}
|
||||
|
||||
public function handle_unexpected_shutdown() {
|
||||
if ( $error = error_get_last() ) {
|
||||
if ( in_array( $error['type'], array( E_ERROR, E_PARSE, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ) ) ) {
|
||||
if ( !empty($this->action_id) ) {
|
||||
$this->store->mark_failure( $this->action_id );
|
||||
do_action( 'action_scheduler_unexpected_shutdown', $this->action_id, $error );
|
||||
}
|
||||
}
|
||||
$this->store->release_claim( $this->claim );
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* InvalidAction Exception.
|
||||
*
|
||||
* Used for identifying actions that are invalid in some way.
|
||||
*
|
||||
* @package ActionScheduler
|
||||
*/
|
||||
class ActionScheduler_InvalidActionException extends \InvalidArgumentException implements ActionScheduler_Exception {
|
||||
|
||||
/**
|
||||
* Create a new exception when the action's schedule cannot be fetched.
|
||||
*
|
||||
* @param string $action_id The action ID with bad args.
|
||||
* @return static
|
||||
*/
|
||||
public static function from_schedule( $action_id, $schedule ) {
|
||||
$message = sprintf(
|
||||
/* translators: 1: action ID 2: schedule */
|
||||
__( 'Action [%1$s] has an invalid schedule: %2$s', 'action-scheduler' ),
|
||||
$action_id,
|
||||
var_export( $schedule, true )
|
||||
);
|
||||
|
||||
return new static( $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new exception when the action's args cannot be decoded to an array.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param string $action_id The action ID with bad args.
|
||||
* @return static
|
||||
*/
|
||||
public static function from_decoding_args( $action_id, $args = array() ) {
|
||||
$message = sprintf(
|
||||
/* translators: 1: action ID 2: arguments */
|
||||
__( 'Action [%1$s] has invalid arguments. It cannot be JSON decoded to an array. $args = %2$s', 'action-scheduler' ),
|
||||
$action_id,
|
||||
var_export( $args, true )
|
||||
);
|
||||
|
||||
return new static( $message );
|
||||
}
|
||||
}
|
||||
+657
@@ -0,0 +1,657 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements the admin view of the actions.
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
|
||||
|
||||
/**
|
||||
* The package name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $package = 'action-scheduler';
|
||||
|
||||
/**
|
||||
* Columns to show (name => label).
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $columns = array();
|
||||
|
||||
/**
|
||||
* Actions (name => label).
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $row_actions = array();
|
||||
|
||||
/**
|
||||
* The active data stores
|
||||
*
|
||||
* @var ActionScheduler_Store
|
||||
*/
|
||||
protected $store;
|
||||
|
||||
/**
|
||||
* A logger to use for getting action logs to display
|
||||
*
|
||||
* @var ActionScheduler_Logger
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* A ActionScheduler_QueueRunner runner instance (or child class)
|
||||
*
|
||||
* @var ActionScheduler_QueueRunner
|
||||
*/
|
||||
protected $runner;
|
||||
|
||||
/**
|
||||
* Bulk actions. The key of the array is the method name of the implementation:
|
||||
*
|
||||
* bulk_<key>(array $ids, string $sql_in).
|
||||
*
|
||||
* See the comments in the parent class for further details
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $bulk_actions = array();
|
||||
|
||||
/**
|
||||
* Flag variable to render our notifications, if any, once.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static $did_notification = false;
|
||||
|
||||
/**
|
||||
* Array of seconds for common time periods, like week or month, alongside an internationalised string representation, i.e. "Day" or "Days"
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private static $time_periods;
|
||||
|
||||
/**
|
||||
* Sets the current data store object into `store->action` and initialises the object.
|
||||
*
|
||||
* @param ActionScheduler_Store $store
|
||||
* @param ActionScheduler_Logger $logger
|
||||
* @param ActionScheduler_QueueRunner $runner
|
||||
*/
|
||||
public function __construct( ActionScheduler_Store $store, ActionScheduler_Logger $logger, ActionScheduler_QueueRunner $runner ) {
|
||||
|
||||
$this->store = $store;
|
||||
$this->logger = $logger;
|
||||
$this->runner = $runner;
|
||||
|
||||
$this->table_header = __( 'Scheduled Actions', 'action-scheduler' );
|
||||
|
||||
$this->bulk_actions = array(
|
||||
'delete' => __( 'Delete', 'action-scheduler' ),
|
||||
);
|
||||
|
||||
$this->columns = array(
|
||||
'hook' => __( 'Hook', 'action-scheduler' ),
|
||||
'status' => __( 'Status', 'action-scheduler' ),
|
||||
'args' => __( 'Arguments', 'action-scheduler' ),
|
||||
'group' => __( 'Group', 'action-scheduler' ),
|
||||
'recurrence' => __( 'Recurrence', 'action-scheduler' ),
|
||||
'schedule' => __( 'Scheduled Date', 'action-scheduler' ),
|
||||
'log_entries' => __( 'Log', 'action-scheduler' ),
|
||||
);
|
||||
|
||||
$this->sort_by = array(
|
||||
'schedule',
|
||||
'hook',
|
||||
'group',
|
||||
);
|
||||
|
||||
$this->search_by = array(
|
||||
'hook',
|
||||
'args',
|
||||
'claim_id',
|
||||
);
|
||||
|
||||
$request_status = $this->get_request_status();
|
||||
|
||||
if ( empty( $request_status ) ) {
|
||||
$this->sort_by[] = 'status';
|
||||
} elseif ( in_array( $request_status, array( 'in-progress', 'failed' ) ) ) {
|
||||
$this->columns += array( 'claim_id' => __( 'Claim ID', 'action-scheduler' ) );
|
||||
$this->sort_by[] = 'claim_id';
|
||||
}
|
||||
|
||||
$this->row_actions = array(
|
||||
'hook' => array(
|
||||
'run' => array(
|
||||
'name' => __( 'Run', 'action-scheduler' ),
|
||||
'desc' => __( 'Process the action now as if it were run as part of a queue', 'action-scheduler' ),
|
||||
),
|
||||
'cancel' => array(
|
||||
'name' => __( 'Cancel', 'action-scheduler' ),
|
||||
'desc' => __( 'Cancel the action now to avoid it being run in future', 'action-scheduler' ),
|
||||
'class' => 'cancel trash',
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
self::$time_periods = array(
|
||||
array(
|
||||
'seconds' => YEAR_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => MONTH_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => WEEK_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => DAY_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => HOUR_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => MINUTE_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => 1,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s second', '%s seconds', 'action-scheduler' ),
|
||||
),
|
||||
);
|
||||
|
||||
parent::__construct(
|
||||
array(
|
||||
'singular' => 'action-scheduler',
|
||||
'plural' => 'action-scheduler',
|
||||
'ajax' => false,
|
||||
)
|
||||
);
|
||||
|
||||
add_screen_option(
|
||||
'per_page',
|
||||
array(
|
||||
'default' => $this->items_per_page,
|
||||
)
|
||||
);
|
||||
|
||||
add_filter( 'set_screen_option_' . $this->get_per_page_option_name(), array( $this, 'set_items_per_page_option' ), 10, 3 );
|
||||
set_screen_options();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles setting the items_per_page option for this screen.
|
||||
*
|
||||
* @param mixed $status Default false (to skip saving the current option).
|
||||
* @param string $option Screen option name.
|
||||
* @param int $value Screen option value.
|
||||
* @return int
|
||||
*/
|
||||
public function set_items_per_page_option( $status, $option, $value ) {
|
||||
return $value;
|
||||
}
|
||||
/**
|
||||
* Convert an interval of seconds into a two part human friendly string.
|
||||
*
|
||||
* The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
|
||||
* even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step
|
||||
* further to display two degrees of accuracy.
|
||||
*
|
||||
* Inspired by the Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
|
||||
*
|
||||
* @param int $interval A interval in seconds.
|
||||
* @param int $periods_to_include Depth of time periods to include, e.g. for an interval of 70, and $periods_to_include of 2, both minutes and seconds would be included. With a value of 1, only minutes would be included.
|
||||
* @return string A human friendly string representation of the interval.
|
||||
*/
|
||||
private static function human_interval( $interval, $periods_to_include = 2 ) {
|
||||
|
||||
if ( $interval <= 0 ) {
|
||||
return __( 'Now!', 'action-scheduler' );
|
||||
}
|
||||
|
||||
$output = '';
|
||||
|
||||
for ( $time_period_index = 0, $periods_included = 0, $seconds_remaining = $interval; $time_period_index < count( self::$time_periods ) && $seconds_remaining > 0 && $periods_included < $periods_to_include; $time_period_index++ ) {
|
||||
|
||||
$periods_in_interval = floor( $seconds_remaining / self::$time_periods[ $time_period_index ]['seconds'] );
|
||||
|
||||
if ( $periods_in_interval > 0 ) {
|
||||
if ( ! empty( $output ) ) {
|
||||
$output .= ' ';
|
||||
}
|
||||
$output .= sprintf( _n( self::$time_periods[ $time_period_index ]['names'][0], self::$time_periods[ $time_period_index ]['names'][1], $periods_in_interval, 'action-scheduler' ), $periods_in_interval );
|
||||
$seconds_remaining -= $periods_in_interval * self::$time_periods[ $time_period_index ]['seconds'];
|
||||
$periods_included++;
|
||||
}
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the recurrence of an action or 'Non-repeating'. The output is human readable.
|
||||
*
|
||||
* @param ActionScheduler_Action $action
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_recurrence( $action ) {
|
||||
$schedule = $action->get_schedule();
|
||||
if ( $schedule->is_recurring() ) {
|
||||
$recurrence = $schedule->get_recurrence();
|
||||
|
||||
if ( is_numeric( $recurrence ) ) {
|
||||
/* translators: %s: time interval */
|
||||
return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence ) );
|
||||
} else {
|
||||
return $recurrence;
|
||||
}
|
||||
}
|
||||
|
||||
return __( 'Non-repeating', 'action-scheduler' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes the argument of an action to render it in a human friendly format.
|
||||
*
|
||||
* @param array $row The array representation of the current row of the table
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function column_args( array $row ) {
|
||||
if ( empty( $row['args'] ) ) {
|
||||
return apply_filters( 'action_scheduler_list_table_column_args', '', $row );
|
||||
}
|
||||
|
||||
$row_html = '<ul>';
|
||||
foreach ( $row['args'] as $key => $value ) {
|
||||
$row_html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( var_export( $key, true ) ), esc_html( var_export( $value, true ) ) );
|
||||
}
|
||||
$row_html .= '</ul>';
|
||||
|
||||
return apply_filters( 'action_scheduler_list_table_column_args', $row_html, $row );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
|
||||
*
|
||||
* @param array $row Action array.
|
||||
* @return string
|
||||
*/
|
||||
public function column_log_entries( array $row ) {
|
||||
|
||||
$log_entries_html = '<ol>';
|
||||
|
||||
$timezone = new DateTimezone( 'UTC' );
|
||||
|
||||
foreach ( $row['log_entries'] as $log_entry ) {
|
||||
$log_entries_html .= $this->get_log_entry_html( $log_entry, $timezone );
|
||||
}
|
||||
|
||||
$log_entries_html .= '</ol>';
|
||||
|
||||
return $log_entries_html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
|
||||
*
|
||||
* @param ActionScheduler_LogEntry $log_entry
|
||||
* @param DateTimezone $timezone
|
||||
* @return string
|
||||
*/
|
||||
protected function get_log_entry_html( ActionScheduler_LogEntry $log_entry, DateTimezone $timezone ) {
|
||||
$date = $log_entry->get_date();
|
||||
$date->setTimezone( $timezone );
|
||||
return sprintf( '<li><strong>%s</strong><br/>%s</li>', esc_html( $date->format( 'Y-m-d H:i:s O' ) ), esc_html( $log_entry->get_message() ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Only display row actions for pending actions.
|
||||
*
|
||||
* @param array $row Row to render
|
||||
* @param string $column_name Current row
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function maybe_render_actions( $row, $column_name ) {
|
||||
if ( 'pending' === strtolower( $row[ 'status_name' ] ) ) {
|
||||
return parent::maybe_render_actions( $row, $column_name );
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders admin notifications
|
||||
*
|
||||
* Notifications:
|
||||
* 1. When the maximum number of tasks are being executed simultaneously.
|
||||
* 2. Notifications when a task is manually executed.
|
||||
* 3. Tables are missing.
|
||||
*/
|
||||
public function display_admin_notices() {
|
||||
global $wpdb;
|
||||
|
||||
if ( ( is_a( $this->store, 'ActionScheduler_HybridStore' ) || is_a( $this->store, 'ActionScheduler_DBStore' ) ) && apply_filters( 'action_scheduler_enable_recreate_data_store', true ) ) {
|
||||
$table_list = array(
|
||||
'actionscheduler_actions',
|
||||
'actionscheduler_logs',
|
||||
'actionscheduler_groups',
|
||||
'actionscheduler_claims',
|
||||
);
|
||||
|
||||
$found_tables = $wpdb->get_col( "SHOW TABLES LIKE '{$wpdb->prefix}actionscheduler%'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
foreach ( $table_list as $table_name ) {
|
||||
if ( ! in_array( $wpdb->prefix . $table_name, $found_tables ) ) {
|
||||
$this->admin_notices[] = array(
|
||||
'class' => 'error',
|
||||
'message' => __( 'It appears one or more database tables were missing. Attempting to re-create the missing table(s).' , 'action-scheduler' ),
|
||||
);
|
||||
$this->recreate_tables();
|
||||
parent::display_admin_notices();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $this->runner->has_maximum_concurrent_batches() ) {
|
||||
$claim_count = $this->store->get_claim_count();
|
||||
$this->admin_notices[] = array(
|
||||
'class' => 'updated',
|
||||
'message' => sprintf(
|
||||
/* translators: %s: amount of claims */
|
||||
_n(
|
||||
'Maximum simultaneous queues already in progress (%s queue). No additional queues will begin processing until the current queues are complete.',
|
||||
'Maximum simultaneous queues already in progress (%s queues). No additional queues will begin processing until the current queues are complete.',
|
||||
$claim_count,
|
||||
'action-scheduler'
|
||||
),
|
||||
$claim_count
|
||||
),
|
||||
);
|
||||
} elseif ( $this->store->has_pending_actions_due() ) {
|
||||
|
||||
$async_request_lock_expiration = ActionScheduler::lock()->get_expiration( 'async-request-runner' );
|
||||
|
||||
// No lock set or lock expired
|
||||
if ( false === $async_request_lock_expiration || $async_request_lock_expiration < time() ) {
|
||||
$in_progress_url = add_query_arg( 'status', 'in-progress', remove_query_arg( 'status' ) );
|
||||
/* translators: %s: process URL */
|
||||
$async_request_message = sprintf( __( 'A new queue has begun processing. <a href="%s">View actions in-progress »</a>', 'action-scheduler' ), esc_url( $in_progress_url ) );
|
||||
} else {
|
||||
/* translators: %d: seconds */
|
||||
$async_request_message = sprintf( __( 'The next queue will begin processing in approximately %d seconds.', 'action-scheduler' ), $async_request_lock_expiration - time() );
|
||||
}
|
||||
|
||||
$this->admin_notices[] = array(
|
||||
'class' => 'notice notice-info',
|
||||
'message' => $async_request_message,
|
||||
);
|
||||
}
|
||||
|
||||
$notification = get_transient( 'action_scheduler_admin_notice' );
|
||||
|
||||
if ( is_array( $notification ) ) {
|
||||
delete_transient( 'action_scheduler_admin_notice' );
|
||||
|
||||
$action = $this->store->fetch_action( $notification['action_id'] );
|
||||
$action_hook_html = '<strong><code>' . $action->get_hook() . '</code></strong>';
|
||||
if ( 1 == $notification['success'] ) {
|
||||
$class = 'updated';
|
||||
switch ( $notification['row_action_type'] ) {
|
||||
case 'run' :
|
||||
/* translators: %s: action HTML */
|
||||
$action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html );
|
||||
break;
|
||||
case 'cancel' :
|
||||
/* translators: %s: action HTML */
|
||||
$action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html );
|
||||
break;
|
||||
default :
|
||||
/* translators: %s: action HTML */
|
||||
$action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html );
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
$class = 'error';
|
||||
/* translators: 1: action HTML 2: action ID 3: error message */
|
||||
$action_message_html = sprintf( __( 'Could not process change for action: "%1$s" (ID: %2$d). Error: %3$s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) );
|
||||
}
|
||||
|
||||
$action_message_html = apply_filters( 'action_scheduler_admin_notice_html', $action_message_html, $action, $notification );
|
||||
|
||||
$this->admin_notices[] = array(
|
||||
'class' => $class,
|
||||
'message' => $action_message_html,
|
||||
);
|
||||
}
|
||||
|
||||
parent::display_admin_notices();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the scheduled date in a human friendly format.
|
||||
*
|
||||
* @param array $row The array representation of the current row of the table
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function column_schedule( $row ) {
|
||||
return $this->get_schedule_display_string( $row['schedule'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the scheduled date in a human friendly format.
|
||||
*
|
||||
* @param ActionScheduler_Schedule $schedule
|
||||
* @return string
|
||||
*/
|
||||
protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) {
|
||||
|
||||
$schedule_display_string = '';
|
||||
|
||||
if ( is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) {
|
||||
return __( 'async', 'action-scheduler' );
|
||||
}
|
||||
|
||||
if ( ! $schedule->get_date() ) {
|
||||
return '0000-00-00 00:00:00';
|
||||
}
|
||||
|
||||
$next_timestamp = $schedule->get_date()->getTimestamp();
|
||||
|
||||
$schedule_display_string .= $schedule->get_date()->format( 'Y-m-d H:i:s O' );
|
||||
$schedule_display_string .= '<br/>';
|
||||
|
||||
if ( gmdate( 'U' ) > $next_timestamp ) {
|
||||
/* translators: %s: date interval */
|
||||
$schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) );
|
||||
} else {
|
||||
/* translators: %s: date interval */
|
||||
$schedule_display_string .= sprintf( __( ' (%s)', 'action-scheduler' ), self::human_interval( $next_timestamp - gmdate( 'U' ) ) );
|
||||
}
|
||||
|
||||
return $schedule_display_string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk delete
|
||||
*
|
||||
* Deletes actions based on their ID. This is the handler for the bulk delete. It assumes the data
|
||||
* properly validated by the callee and it will delete the actions without any extra validation.
|
||||
*
|
||||
* @param array $ids
|
||||
* @param string $ids_sql Inherited and unused
|
||||
*/
|
||||
protected function bulk_delete( array $ids, $ids_sql ) {
|
||||
foreach ( $ids as $id ) {
|
||||
$this->store->delete_action( $id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
|
||||
* parameters are valid.
|
||||
*
|
||||
* @param int $action_id
|
||||
*/
|
||||
protected function row_action_cancel( $action_id ) {
|
||||
$this->process_row_action( $action_id, 'cancel' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
|
||||
* parameters are valid.
|
||||
*
|
||||
* @param int $action_id
|
||||
*/
|
||||
protected function row_action_run( $action_id ) {
|
||||
$this->process_row_action( $action_id, 'run' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Force the data store schema updates.
|
||||
*/
|
||||
protected function recreate_tables() {
|
||||
if ( is_a( $this->store, 'ActionScheduler_HybridStore' ) ) {
|
||||
$store = $this->store;
|
||||
} else {
|
||||
$store = new ActionScheduler_HybridStore();
|
||||
}
|
||||
add_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10, 2 );
|
||||
|
||||
$store_schema = new ActionScheduler_StoreSchema();
|
||||
$logger_schema = new ActionScheduler_LoggerSchema();
|
||||
$store_schema->register_tables( true );
|
||||
$logger_schema->register_tables( true );
|
||||
|
||||
remove_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10 );
|
||||
}
|
||||
/**
|
||||
* Implements the logic behind processing an action once an action link is clicked on the list table.
|
||||
*
|
||||
* @param int $action_id
|
||||
* @param string $row_action_type The type of action to perform on the action.
|
||||
*/
|
||||
protected function process_row_action( $action_id, $row_action_type ) {
|
||||
try {
|
||||
switch ( $row_action_type ) {
|
||||
case 'run' :
|
||||
$this->runner->process_action( $action_id, 'Admin List Table' );
|
||||
break;
|
||||
case 'cancel' :
|
||||
$this->store->cancel_action( $action_id );
|
||||
break;
|
||||
}
|
||||
$success = 1;
|
||||
$error_message = '';
|
||||
} catch ( Exception $e ) {
|
||||
$success = 0;
|
||||
$error_message = $e->getMessage();
|
||||
}
|
||||
|
||||
set_transient( 'action_scheduler_admin_notice', compact( 'action_id', 'success', 'error_message', 'row_action_type' ), 30 );
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function prepare_items() {
|
||||
$this->prepare_column_headers();
|
||||
|
||||
$per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );
|
||||
|
||||
$query = array(
|
||||
'per_page' => $per_page,
|
||||
'offset' => $this->get_items_offset(),
|
||||
'status' => $this->get_request_status(),
|
||||
'orderby' => $this->get_request_orderby(),
|
||||
'order' => $this->get_request_order(),
|
||||
'search' => $this->get_request_search_query(),
|
||||
);
|
||||
|
||||
/**
|
||||
* Change query arguments to query for past-due actions.
|
||||
* Past-due actions have the 'pending' status and are in the past.
|
||||
* This is needed because registering 'past-due' as a status is overkill.
|
||||
*/
|
||||
if ( 'past-due' === $this->get_request_status() ) {
|
||||
$query['status'] = ActionScheduler_Store::STATUS_PENDING;
|
||||
$query['date'] = as_get_datetime_object();
|
||||
}
|
||||
|
||||
$this->items = array();
|
||||
|
||||
$total_items = $this->store->query_actions( $query, 'count' );
|
||||
|
||||
$status_labels = $this->store->get_status_labels();
|
||||
|
||||
foreach ( $this->store->query_actions( $query ) as $action_id ) {
|
||||
try {
|
||||
$action = $this->store->fetch_action( $action_id );
|
||||
} catch ( Exception $e ) {
|
||||
continue;
|
||||
}
|
||||
if ( is_a( $action, 'ActionScheduler_NullAction' ) ) {
|
||||
continue;
|
||||
}
|
||||
$this->items[ $action_id ] = array(
|
||||
'ID' => $action_id,
|
||||
'hook' => $action->get_hook(),
|
||||
'status_name' => $this->store->get_status( $action_id ),
|
||||
'status' => $status_labels[ $this->store->get_status( $action_id ) ],
|
||||
'args' => $action->get_args(),
|
||||
'group' => $action->get_group(),
|
||||
'log_entries' => $this->logger->get_logs( $action_id ),
|
||||
'claim_id' => $this->store->get_claim_id( $action_id ),
|
||||
'recurrence' => $this->get_recurrence( $action ),
|
||||
'schedule' => $action->get_schedule(),
|
||||
);
|
||||
}
|
||||
|
||||
$this->set_pagination_args( array(
|
||||
'total_items' => $total_items,
|
||||
'per_page' => $per_page,
|
||||
'total_pages' => ceil( $total_items / $per_page ),
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the available statuses so the user can click to filter.
|
||||
*/
|
||||
protected function display_filter_by_status() {
|
||||
$this->status_counts = $this->store->action_counts() + $this->store->extra_action_counts();
|
||||
parent::display_filter_by_status();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the text to display in the search box on the list table.
|
||||
*/
|
||||
protected function get_search_box_button_text() {
|
||||
return __( 'Search hook, args and claim ID', 'action-scheduler' );
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
protected function get_per_page_option_name() {
|
||||
return str_replace( '-', '_', $this->screen->id ) . '_per_page';
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_LogEntry
|
||||
*/
|
||||
class ActionScheduler_LogEntry {
|
||||
|
||||
/**
|
||||
* @var int $action_id
|
||||
*/
|
||||
protected $action_id = '';
|
||||
|
||||
/**
|
||||
* @var string $message
|
||||
*/
|
||||
protected $message = '';
|
||||
|
||||
/**
|
||||
* @var Datetime $date
|
||||
*/
|
||||
protected $date;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param mixed $action_id Action ID
|
||||
* @param string $message Message
|
||||
* @param Datetime $date Datetime object with the time when this log entry was created. If this parameter is
|
||||
* not provided a new Datetime object (with current time) will be created.
|
||||
*/
|
||||
public function __construct( $action_id, $message, $date = null ) {
|
||||
|
||||
/*
|
||||
* ActionScheduler_wpCommentLogger::get_entry() previously passed a 3rd param of $comment->comment_type
|
||||
* to ActionScheduler_LogEntry::__construct(), goodness knows why, and the Follow-up Emails plugin
|
||||
* hard-codes loading its own version of ActionScheduler_wpCommentLogger with that out-dated method,
|
||||
* goodness knows why, so we need to guard against that here instead of using a DateTime type declaration
|
||||
* for the constructor's 3rd param of $date and causing a fatal error with older versions of FUE.
|
||||
*/
|
||||
if ( null !== $date && ! is_a( $date, 'DateTime' ) ) {
|
||||
_doing_it_wrong( __METHOD__, 'The third parameter must be a valid DateTime instance, or null.', '2.0.0' );
|
||||
$date = null;
|
||||
}
|
||||
|
||||
$this->action_id = $action_id;
|
||||
$this->message = $message;
|
||||
$this->date = $date ? $date : new Datetime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the date when this log entry was created
|
||||
*
|
||||
* @return Datetime
|
||||
*/
|
||||
public function get_date() {
|
||||
return $this->date;
|
||||
}
|
||||
|
||||
public function get_action_id() {
|
||||
return $this->action_id;
|
||||
}
|
||||
|
||||
public function get_message() {
|
||||
return $this->message;
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_NullLogEntry
|
||||
*/
|
||||
class ActionScheduler_NullLogEntry extends ActionScheduler_LogEntry {
|
||||
public function __construct( $action_id = '', $message = '' ) {
|
||||
// nothing to see here
|
||||
}
|
||||
}
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Provide a way to set simple transient locks to block behaviour
|
||||
* for up-to a given duration.
|
||||
*
|
||||
* Class ActionScheduler_OptionLock
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_OptionLock extends ActionScheduler_Lock {
|
||||
|
||||
/**
|
||||
* Set a lock using options for a given amount of time (60 seconds by default).
|
||||
*
|
||||
* Using an autoloaded option avoids running database queries or other resource intensive tasks
|
||||
* on frequently triggered hooks, like 'init' or 'shutdown'.
|
||||
*
|
||||
* For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid
|
||||
* calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown',
|
||||
* hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count()
|
||||
* to find the current number of claims in the database.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @bool True if lock value has changed, false if not or if set failed.
|
||||
*/
|
||||
public function set( $lock_type ) {
|
||||
return update_option( $this->get_key( $lock_type ), time() + $this->get_duration( $lock_type ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* If a lock is set, return the timestamp it was set to expiry.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
|
||||
*/
|
||||
public function get_expiration( $lock_type ) {
|
||||
return get_option( $this->get_key( $lock_type ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the key to use for storing the lock in the transient
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return string
|
||||
*/
|
||||
protected function get_key( $lock_type ) {
|
||||
return sprintf( 'action_scheduler_lock_%s', $lock_type );
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_QueueCleaner
|
||||
*/
|
||||
class ActionScheduler_QueueCleaner {
|
||||
|
||||
/** @var int */
|
||||
protected $batch_size;
|
||||
|
||||
/** @var ActionScheduler_Store */
|
||||
private $store = null;
|
||||
|
||||
/**
|
||||
* 31 days in seconds.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $month_in_seconds = 2678400;
|
||||
|
||||
/**
|
||||
* ActionScheduler_QueueCleaner constructor.
|
||||
*
|
||||
* @param ActionScheduler_Store $store The store instance.
|
||||
* @param int $batch_size The batch size.
|
||||
*/
|
||||
public function __construct( ActionScheduler_Store $store = null, $batch_size = 20 ) {
|
||||
$this->store = $store ? $store : ActionScheduler_Store::instance();
|
||||
$this->batch_size = $batch_size;
|
||||
}
|
||||
|
||||
public function delete_old_actions() {
|
||||
$lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds );
|
||||
$cutoff = as_get_datetime_object($lifespan.' seconds ago');
|
||||
|
||||
$statuses_to_purge = array(
|
||||
ActionScheduler_Store::STATUS_COMPLETE,
|
||||
ActionScheduler_Store::STATUS_CANCELED,
|
||||
);
|
||||
|
||||
foreach ( $statuses_to_purge as $status ) {
|
||||
$actions_to_delete = $this->store->query_actions( array(
|
||||
'status' => $status,
|
||||
'modified' => $cutoff,
|
||||
'modified_compare' => '<=',
|
||||
'per_page' => $this->get_batch_size(),
|
||||
'orderby' => 'none',
|
||||
) );
|
||||
|
||||
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 ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unclaim pending actions that have not been run within a given time limit.
|
||||
*
|
||||
* When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
|
||||
* as a parameter is 10x the time limit used for queue processing.
|
||||
*
|
||||
* @param int $time_limit The number of seconds to allow a queue to run before unclaiming its pending actions. Default 300 (5 minutes).
|
||||
*/
|
||||
public function reset_timeouts( $time_limit = 300 ) {
|
||||
$timeout = apply_filters( 'action_scheduler_timeout_period', $time_limit );
|
||||
if ( $timeout < 0 ) {
|
||||
return;
|
||||
}
|
||||
$cutoff = as_get_datetime_object($timeout.' seconds ago');
|
||||
$actions_to_reset = $this->store->query_actions( array(
|
||||
'status' => ActionScheduler_Store::STATUS_PENDING,
|
||||
'modified' => $cutoff,
|
||||
'modified_compare' => '<=',
|
||||
'claimed' => true,
|
||||
'per_page' => $this->get_batch_size(),
|
||||
'orderby' => 'none',
|
||||
) );
|
||||
|
||||
foreach ( $actions_to_reset as $action_id ) {
|
||||
$this->store->unclaim_action( $action_id );
|
||||
do_action( 'action_scheduler_reset_action', $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark actions that have been running for more than a given time limit as failed, based on
|
||||
* the assumption some uncatachable and unloggable fatal error occurred during processing.
|
||||
*
|
||||
* When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
|
||||
* as a parameter is 10x the time limit used for queue processing.
|
||||
*
|
||||
* @param int $time_limit The number of seconds to allow an action to run before it is considered to have failed. Default 300 (5 minutes).
|
||||
*/
|
||||
public function mark_failures( $time_limit = 300 ) {
|
||||
$timeout = apply_filters( 'action_scheduler_failure_period', $time_limit );
|
||||
if ( $timeout < 0 ) {
|
||||
return;
|
||||
}
|
||||
$cutoff = as_get_datetime_object($timeout.' seconds ago');
|
||||
$actions_to_reset = $this->store->query_actions( array(
|
||||
'status' => ActionScheduler_Store::STATUS_RUNNING,
|
||||
'modified' => $cutoff,
|
||||
'modified_compare' => '<=',
|
||||
'per_page' => $this->get_batch_size(),
|
||||
'orderby' => 'none',
|
||||
) );
|
||||
|
||||
foreach ( $actions_to_reset as $action_id ) {
|
||||
$this->store->mark_failure( $action_id );
|
||||
do_action( 'action_scheduler_failed_action', $action_id, $timeout );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Do all of the cleaning actions.
|
||||
*
|
||||
* @param int $time_limit The number of seconds to use as the timeout and failure period. Default 300 (5 minutes).
|
||||
* @author Jeremy Pry
|
||||
*/
|
||||
public function clean( $time_limit = 300 ) {
|
||||
$this->delete_old_actions();
|
||||
$this->reset_timeouts( $time_limit );
|
||||
$this->mark_failures( $time_limit );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the batch size for cleaning the queue.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
* @return int
|
||||
*/
|
||||
protected function get_batch_size() {
|
||||
/**
|
||||
* Filter the batch size when cleaning the queue.
|
||||
*
|
||||
* @param int $batch_size The number of actions to clean in one batch.
|
||||
*/
|
||||
return absint( apply_filters( 'action_scheduler_cleanup_batch_size', $this->batch_size ) );
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_QueueRunner
|
||||
*/
|
||||
class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
|
||||
const WP_CRON_HOOK = 'action_scheduler_run_queue';
|
||||
|
||||
const WP_CRON_SCHEDULE = 'every_minute';
|
||||
|
||||
/** @var ActionScheduler_AsyncRequest_QueueRunner */
|
||||
protected $async_request;
|
||||
|
||||
/** @var ActionScheduler_QueueRunner */
|
||||
private static $runner = null;
|
||||
|
||||
/** @var int */
|
||||
private $processed_actions_count = 0;
|
||||
|
||||
/**
|
||||
* @return ActionScheduler_QueueRunner
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( empty(self::$runner) ) {
|
||||
$class = apply_filters('action_scheduler_queue_runner_class', 'ActionScheduler_QueueRunner');
|
||||
self::$runner = new $class();
|
||||
}
|
||||
return self::$runner;
|
||||
}
|
||||
|
||||
/**
|
||||
* ActionScheduler_QueueRunner constructor.
|
||||
*
|
||||
* @param ActionScheduler_Store $store
|
||||
* @param ActionScheduler_FatalErrorMonitor $monitor
|
||||
* @param ActionScheduler_QueueCleaner $cleaner
|
||||
*/
|
||||
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null, ActionScheduler_AsyncRequest_QueueRunner $async_request = null ) {
|
||||
parent::__construct( $store, $monitor, $cleaner );
|
||||
|
||||
if ( is_null( $async_request ) ) {
|
||||
$async_request = new ActionScheduler_AsyncRequest_QueueRunner( $this->store );
|
||||
}
|
||||
|
||||
$this->async_request = $async_request;
|
||||
}
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
|
||||
add_filter( 'cron_schedules', array( 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 = array( 'WP Cron' );
|
||||
|
||||
if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) {
|
||||
$schedule = apply_filters( '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, array( self::instance(), 'run' ) );
|
||||
$this->hook_dispatch_async_request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook check for dispatching an async request.
|
||||
*/
|
||||
public function hook_dispatch_async_request() {
|
||||
add_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unhook check for dispatching an async request.
|
||||
*/
|
||||
public function unhook_dispatch_async_request() {
|
||||
remove_action( 'shutdown', array( $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' );
|
||||
$this->run_cleanup();
|
||||
|
||||
$this->processed_actions_count = 0;
|
||||
if ( false === $this->has_maximum_concurrent_batches() ) {
|
||||
$batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
|
||||
do {
|
||||
$processed_actions_in_batch = $this->do_batch( $batch_size, $context );
|
||||
$this->processed_actions_count += $processed_actions_in_batch;
|
||||
} while ( $processed_actions_in_batch > 0 && ! $this->batch_limits_exceeded( $this->processed_actions_count ) ); // keep going until we run out of actions, time, or memory
|
||||
}
|
||||
|
||||
do_action( 'action_scheduler_after_process_queue' );
|
||||
return $this->processed_actions_count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = '' ) {
|
||||
$claim = $this->store->stake_claim($size);
|
||||
$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() ) ) ) {
|
||||
break;
|
||||
}
|
||||
$this->process_action( $action_id, $context );
|
||||
$processed_actions++;
|
||||
|
||||
if ( $this->batch_limits_exceeded( $processed_actions + $this->processed_actions_count ) ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$this->store->release_claim($claim);
|
||||
$this->monitor->detach();
|
||||
$this->clear_caches();
|
||||
return $processed_actions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush the cache if possible (intended for use after a batch of actions has been processed).
|
||||
*
|
||||
* This is useful because running large batches can eat up memory and because invalid data can accrue in the
|
||||
* runtime cache, which may lead to unexpected results.
|
||||
*/
|
||||
protected function clear_caches() {
|
||||
/*
|
||||
* Calling wp_cache_flush_runtime() lets us clear the runtime cache without invalidating the external object
|
||||
* cache, so we will always prefer this when it is available (but it was only introduced in WordPress 6.0).
|
||||
*/
|
||||
if ( function_exists( 'wp_cache_flush_runtime' ) ) {
|
||||
wp_cache_flush_runtime();
|
||||
} elseif (
|
||||
! wp_using_ext_object_cache()
|
||||
/**
|
||||
* When an external object cache is in use, and when wp_cache_flush_runtime() is not available, then
|
||||
* normally the cache will not be flushed after processing a batch of actions (to avoid a performance
|
||||
* penalty for other processes).
|
||||
*
|
||||
* This filter makes it possible to override this behavior and always flush the cache, even if an external
|
||||
* object cache is in use.
|
||||
*
|
||||
* @since 1.0
|
||||
*
|
||||
* @param bool $flush_cache If the cache should be flushed.
|
||||
*/
|
||||
|| apply_filters( 'action_scheduler_queue_runner_flush_cache', false )
|
||||
) {
|
||||
wp_cache_flush();
|
||||
}
|
||||
}
|
||||
|
||||
public function add_wp_cron_schedule( $schedules ) {
|
||||
$schedules['every_minute'] = array(
|
||||
'interval' => 60, // in seconds
|
||||
'display' => __( 'Every minute', 'action-scheduler' ),
|
||||
);
|
||||
|
||||
return $schedules;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Versions
|
||||
*/
|
||||
class ActionScheduler_Versions {
|
||||
/**
|
||||
* @var ActionScheduler_Versions
|
||||
*/
|
||||
private static $instance = NULL;
|
||||
|
||||
private $versions = array();
|
||||
|
||||
public function register( $version_string, $initialization_callback ) {
|
||||
if ( isset($this->versions[$version_string]) ) {
|
||||
return FALSE;
|
||||
}
|
||||
$this->versions[$version_string] = $initialization_callback;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
public function get_versions() {
|
||||
return $this->versions;
|
||||
}
|
||||
|
||||
public function latest_version() {
|
||||
$keys = array_keys($this->versions);
|
||||
if ( empty($keys) ) {
|
||||
return false;
|
||||
}
|
||||
uasort( $keys, 'version_compare' );
|
||||
return end($keys);
|
||||
}
|
||||
|
||||
public function latest_version_callback() {
|
||||
$latest = $this->latest_version();
|
||||
if ( empty($latest) || !isset($this->versions[$latest]) ) {
|
||||
return '__return_null';
|
||||
}
|
||||
return $this->versions[$latest];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ActionScheduler_Versions
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( empty(self::$instance) ) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function initialize_latest_version() {
|
||||
$self = self::instance();
|
||||
call_user_func($self->latest_version_callback());
|
||||
}
|
||||
}
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_WPCommentCleaner
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_WPCommentCleaner {
|
||||
|
||||
/**
|
||||
* Post migration hook used to cleanup the WP comment table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $cleanup_hook = 'action_scheduler/cleanup_wp_comment_logs';
|
||||
|
||||
/**
|
||||
* An instance of the ActionScheduler_wpCommentLogger class to interact with the comments table.
|
||||
*
|
||||
* This instance should only be used as an interface. It should not be initialized.
|
||||
*
|
||||
* @var ActionScheduler_wpCommentLogger
|
||||
*/
|
||||
protected static $wp_comment_logger = null;
|
||||
|
||||
/**
|
||||
* The key used to store the cached value of whether there are logs in the WP comment table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $has_logs_option_key = 'as_has_wp_comment_logs';
|
||||
|
||||
/**
|
||||
* Initialize the class and attach callbacks.
|
||||
*/
|
||||
public static function init() {
|
||||
if ( empty( self::$wp_comment_logger ) ) {
|
||||
self::$wp_comment_logger = new ActionScheduler_wpCommentLogger();
|
||||
}
|
||||
|
||||
add_action( self::$cleanup_hook, array( __CLASS__, 'delete_all_action_comments' ) );
|
||||
|
||||
// While there are orphaned logs left in the comments table, we need to attach the callbacks which filter comment counts.
|
||||
add_action( 'pre_get_comments', array( self::$wp_comment_logger, 'filter_comment_queries' ), 10, 1 );
|
||||
add_action( 'wp_count_comments', array( self::$wp_comment_logger, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs
|
||||
add_action( 'comment_feed_where', array( self::$wp_comment_logger, 'filter_comment_feed' ), 10, 2 );
|
||||
|
||||
// Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen
|
||||
add_action( 'load-tools_page_action-scheduler', array( __CLASS__, 'register_admin_notice' ) );
|
||||
add_action( 'load-woocommerce_page_wc-status', array( __CLASS__, 'register_admin_notice' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if there are log entries in the wp comments table.
|
||||
*
|
||||
* Uses the flag set on migration completion set by @see self::maybe_schedule_cleanup().
|
||||
*
|
||||
* @return boolean Whether there are scheduled action comments in the comments table.
|
||||
*/
|
||||
public static function has_logs() {
|
||||
return 'yes' === get_option( self::$has_logs_option_key );
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules the WP Post comment table cleanup to run in 6 months if it's not already scheduled.
|
||||
* Attached to the migration complete hook 'action_scheduler/migration_complete'.
|
||||
*/
|
||||
public static function maybe_schedule_cleanup() {
|
||||
if ( (bool) get_comments( array( 'type' => ActionScheduler_wpCommentLogger::TYPE, 'number' => 1, 'fields' => 'ids' ) ) ) {
|
||||
update_option( self::$has_logs_option_key, 'yes' );
|
||||
|
||||
if ( ! as_next_scheduled_action( self::$cleanup_hook ) ) {
|
||||
as_schedule_single_action( gmdate( 'U' ) + ( 6 * MONTH_IN_SECONDS ), self::$cleanup_hook );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all action comments from the WP Comments table.
|
||||
*/
|
||||
public static function delete_all_action_comments() {
|
||||
global $wpdb;
|
||||
$wpdb->delete( $wpdb->comments, array( 'comment_type' => ActionScheduler_wpCommentLogger::TYPE, 'comment_agent' => ActionScheduler_wpCommentLogger::AGENT ) );
|
||||
delete_option( self::$has_logs_option_key );
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers admin notices about the orphaned action logs.
|
||||
*/
|
||||
public static function register_admin_notice() {
|
||||
add_action( 'admin_notices', array( __CLASS__, 'print_admin_notice' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints details about the orphaned action logs and includes information on where to learn more.
|
||||
*/
|
||||
public static function print_admin_notice() {
|
||||
$next_cleanup_message = '';
|
||||
$next_scheduled_cleanup_hook = as_next_scheduled_action( self::$cleanup_hook );
|
||||
|
||||
if ( $next_scheduled_cleanup_hook ) {
|
||||
/* translators: %s: date interval */
|
||||
$next_cleanup_message = sprintf( __( 'This data will be deleted in %s.', 'action-scheduler' ), human_time_diff( gmdate( 'U' ), $next_scheduled_cleanup_hook ) );
|
||||
}
|
||||
|
||||
$notice = sprintf(
|
||||
/* translators: 1: next cleanup message 2: github issue URL */
|
||||
__( 'Action Scheduler has migrated data to custom tables; however, orphaned log entries exist in the WordPress Comments table. %1$s <a href="%2$s">Learn more »</a>', 'action-scheduler' ),
|
||||
$next_cleanup_message,
|
||||
'https://github.com/woocommerce/action-scheduler/issues/368'
|
||||
);
|
||||
|
||||
echo '<div class="notice notice-warning"><p>' . wp_kses_post( $notice ) . '</p></div>';
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_wcSystemStatus
|
||||
*/
|
||||
class ActionScheduler_wcSystemStatus {
|
||||
|
||||
/**
|
||||
* The active data stores
|
||||
*
|
||||
* @var ActionScheduler_Store
|
||||
*/
|
||||
protected $store;
|
||||
|
||||
/**
|
||||
* Constructor method for ActionScheduler_wcSystemStatus.
|
||||
*
|
||||
* @param ActionScheduler_Store $store Active store object.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( $store ) {
|
||||
$this->store = $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display action data, including number of actions grouped by status and the oldest & newest action in each status.
|
||||
*
|
||||
* Helpful to identify issues, like a clogged queue.
|
||||
*/
|
||||
public function render() {
|
||||
$action_counts = $this->store->action_counts();
|
||||
$status_labels = $this->store->get_status_labels();
|
||||
$oldest_and_newest = $this->get_oldest_and_newest( array_keys( $status_labels ) );
|
||||
|
||||
$this->get_template( $status_labels, $action_counts, $oldest_and_newest );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get oldest and newest scheduled dates for a given set of statuses.
|
||||
*
|
||||
* @param array $status_keys Set of statuses to find oldest & newest action for.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_oldest_and_newest( $status_keys ) {
|
||||
|
||||
$oldest_and_newest = array();
|
||||
|
||||
foreach ( $status_keys as $status ) {
|
||||
$oldest_and_newest[ $status ] = array(
|
||||
'oldest' => '–',
|
||||
'newest' => '–',
|
||||
);
|
||||
|
||||
if ( 'in-progress' === $status ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$oldest_and_newest[ $status ]['oldest'] = $this->get_action_status_date( $status, 'oldest' );
|
||||
$oldest_and_newest[ $status ]['newest'] = $this->get_action_status_date( $status, 'newest' );
|
||||
}
|
||||
|
||||
return $oldest_and_newest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get oldest or newest scheduled date for a given status.
|
||||
*
|
||||
* @param string $status Action status label/name string.
|
||||
* @param string $date_type Oldest or Newest.
|
||||
* @return DateTime
|
||||
*/
|
||||
protected function get_action_status_date( $status, $date_type = 'oldest' ) {
|
||||
|
||||
$order = 'oldest' === $date_type ? 'ASC' : 'DESC';
|
||||
|
||||
$action = $this->store->query_actions(
|
||||
array(
|
||||
'claimed' => false,
|
||||
'status' => $status,
|
||||
'per_page' => 1,
|
||||
'order' => $order,
|
||||
)
|
||||
);
|
||||
|
||||
if ( ! empty( $action ) ) {
|
||||
$date_object = $this->store->get_date( $action[0] );
|
||||
$action_date = $date_object->format( 'Y-m-d H:i:s O' );
|
||||
} else {
|
||||
$action_date = '–';
|
||||
}
|
||||
|
||||
return $action_date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get oldest or newest scheduled date for a given status.
|
||||
*
|
||||
* @param array $status_labels Set of statuses to find oldest & newest action for.
|
||||
* @param array $action_counts Number of actions grouped by status.
|
||||
* @param array $oldest_and_newest Date of the oldest and newest action with each status.
|
||||
*/
|
||||
protected function get_template( $status_labels, $action_counts, $oldest_and_newest ) {
|
||||
$as_version = ActionScheduler_Versions::instance()->latest_version();
|
||||
$as_datastore = get_class( ActionScheduler_Store::instance() );
|
||||
?>
|
||||
|
||||
<table class="wc_status_table widefat" cellspacing="0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th colspan="5" data-export-label="Action Scheduler"><h2><?php esc_html_e( 'Action Scheduler', 'action-scheduler' ); ?><?php echo wc_help_tip( esc_html__( 'This section shows details of Action Scheduler.', 'action-scheduler' ) ); ?></h2></th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2" data-export-label="Version"><?php esc_html_e( 'Version:', 'action-scheduler' ); ?></td>
|
||||
<td colspan="3"><?php echo esc_html( $as_version ); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2" data-export-label="Data store"><?php esc_html_e( 'Data store:', 'action-scheduler' ); ?></td>
|
||||
<td colspan="3"><?php echo esc_html( $as_datastore ); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong><?php esc_html_e( 'Action Status', 'action-scheduler' ); ?></strong></td>
|
||||
<td class="help"> </td>
|
||||
<td><strong><?php esc_html_e( 'Count', 'action-scheduler' ); ?></strong></td>
|
||||
<td><strong><?php esc_html_e( 'Oldest Scheduled Date', 'action-scheduler' ); ?></strong></td>
|
||||
<td><strong><?php esc_html_e( 'Newest Scheduled Date', 'action-scheduler' ); ?></strong></td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
foreach ( $action_counts as $status => $count ) {
|
||||
// WC uses the 3rd column for export, so we need to display more data in that (hidden when viewed as part of the table) and add an empty 2nd column.
|
||||
printf(
|
||||
'<tr><td>%1$s</td><td> </td><td>%2$s<span style="display: none;">, Oldest: %3$s, Newest: %4$s</span></td><td>%3$s</td><td>%4$s</td></tr>',
|
||||
esc_html( $status_labels[ $status ] ),
|
||||
esc_html( number_format_i18n( $count ) ),
|
||||
esc_html( $oldest_and_newest[ $status ]['oldest'] ),
|
||||
esc_html( $oldest_and_newest[ $status ]['newest'] )
|
||||
);
|
||||
}
|
||||
?>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Is triggered when invoking inaccessible methods in an object context.
|
||||
*
|
||||
* @param string $name Name of method called.
|
||||
* @param array $arguments Parameters to invoke the method with.
|
||||
*
|
||||
* @return mixed
|
||||
* @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
|
||||
*/
|
||||
public function __call( $name, $arguments ) {
|
||||
switch ( $name ) {
|
||||
case 'print':
|
||||
_deprecated_function( __CLASS__ . '::print()', '2.2.4', __CLASS__ . '::render()' );
|
||||
return call_user_func_array( array( $this, 'render' ), $arguments );
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
use Action_Scheduler\WP_CLI\ProgressBar;
|
||||
|
||||
/**
|
||||
* WP CLI Queue runner.
|
||||
*
|
||||
* This class can only be called from within a WP CLI instance.
|
||||
*/
|
||||
class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
|
||||
|
||||
/** @var array */
|
||||
protected $actions;
|
||||
|
||||
/** @var ActionScheduler_ActionClaim */
|
||||
protected $claim;
|
||||
|
||||
/** @var \cli\progress\Bar */
|
||||
protected $progress_bar;
|
||||
|
||||
/**
|
||||
* ActionScheduler_WPCLI_QueueRunner constructor.
|
||||
*
|
||||
* @param ActionScheduler_Store $store
|
||||
* @param ActionScheduler_FatalErrorMonitor $monitor
|
||||
* @param ActionScheduler_QueueCleaner $cleaner
|
||||
*
|
||||
* @throws Exception When this is not run within WP CLI
|
||||
*/
|
||||
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
|
||||
if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
|
||||
/* translators: %s php class name */
|
||||
throw new Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
|
||||
}
|
||||
|
||||
parent::__construct( $store, $monitor, $cleaner );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up the Queue before processing.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param int $batch_size The batch size to process.
|
||||
* @param array $hooks The hooks being used to filter the actions claimed in this batch.
|
||||
* @param string $group The group of actions to claim with this batch.
|
||||
* @param bool $force Whether to force running even with too many concurrent processes.
|
||||
*
|
||||
* @return int The number of actions that will be run.
|
||||
* @throws \WP_CLI\ExitException When there are too many concurrent batches.
|
||||
*/
|
||||
public function setup( $batch_size, $hooks = array(), $group = '', $force = false ) {
|
||||
$this->run_cleanup();
|
||||
$this->add_hooks();
|
||||
|
||||
// Check to make sure there aren't too many concurrent processes running.
|
||||
if ( $this->has_maximum_concurrent_batches() ) {
|
||||
if ( $force ) {
|
||||
WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) );
|
||||
} else {
|
||||
WP_CLI::error( __( 'There are too many concurrent batches.', 'action-scheduler' ) );
|
||||
}
|
||||
}
|
||||
|
||||
// Stake a claim and store it.
|
||||
$this->claim = $this->store->stake_claim( $batch_size, null, $hooks, $group );
|
||||
$this->monitor->attach( $this->claim );
|
||||
$this->actions = $this->claim->get_actions();
|
||||
|
||||
return count( $this->actions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add our hooks to the appropriate actions.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*/
|
||||
protected function add_hooks() {
|
||||
add_action( 'action_scheduler_before_execute', array( $this, 'before_execute' ) );
|
||||
add_action( 'action_scheduler_after_execute', array( $this, 'after_execute' ), 10, 2 );
|
||||
add_action( 'action_scheduler_failed_execution', array( $this, 'action_failed' ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up the WP CLI progress bar.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*/
|
||||
protected function setup_progress_bar() {
|
||||
$count = count( $this->actions );
|
||||
$this->progress_bar = new ProgressBar(
|
||||
/* translators: %d: amount of actions */
|
||||
sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), number_format_i18n( $count ) ),
|
||||
$count
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process actions in the queue.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param string $context Optional runner context. Default 'WP CLI'.
|
||||
*
|
||||
* @return int The number of actions processed.
|
||||
*/
|
||||
public function run( $context = 'WP CLI' ) {
|
||||
do_action( 'action_scheduler_before_process_queue' );
|
||||
$this->setup_progress_bar();
|
||||
foreach ( $this->actions as $action_id ) {
|
||||
// Error if we lost the claim.
|
||||
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $this->claim->get_id() ) ) ) {
|
||||
WP_CLI::warning( __( 'The claim has been lost. Aborting current batch.', 'action-scheduler' ) );
|
||||
break;
|
||||
}
|
||||
|
||||
$this->process_action( $action_id, $context );
|
||||
$this->progress_bar->tick();
|
||||
}
|
||||
|
||||
$completed = $this->progress_bar->current();
|
||||
$this->progress_bar->finish();
|
||||
$this->store->release_claim( $this->claim );
|
||||
do_action( 'action_scheduler_after_process_queue' );
|
||||
|
||||
return $completed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle WP CLI message when the action is starting.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param $action_id
|
||||
*/
|
||||
public function before_execute( $action_id ) {
|
||||
/* translators: %s refers to the action ID */
|
||||
WP_CLI::log( sprintf( __( 'Started processing action %s', 'action-scheduler' ), $action_id ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle WP CLI message when the action has completed.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param int $action_id
|
||||
* @param null|ActionScheduler_Action $action The instance of the action. Default to null for backward compatibility.
|
||||
*/
|
||||
public function after_execute( $action_id, $action = null ) {
|
||||
// backward compatibility
|
||||
if ( null === $action ) {
|
||||
$action = $this->store->fetch_action( $action_id );
|
||||
}
|
||||
/* translators: 1: action ID 2: hook name */
|
||||
WP_CLI::log( sprintf( __( 'Completed processing action %1$s with hook: %2$s', 'action-scheduler' ), $action_id, $action->get_hook() ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle WP CLI message when the action has failed.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param int $action_id
|
||||
* @param Exception $exception
|
||||
* @throws \WP_CLI\ExitException With failure message.
|
||||
*/
|
||||
public function action_failed( $action_id, $exception ) {
|
||||
WP_CLI::error(
|
||||
/* translators: 1: action ID 2: exception message */
|
||||
sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ),
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep and help avoid hitting memory limit
|
||||
*
|
||||
* @param int $sleep_time Amount of seconds to sleep
|
||||
* @deprecated 3.0.0
|
||||
*/
|
||||
protected function stop_the_insanity( $sleep_time = 0 ) {
|
||||
_deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' );
|
||||
|
||||
ActionScheduler_DataController::free_memory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Maybe trigger the stop_the_insanity() method to free up memory.
|
||||
*/
|
||||
protected function maybe_stop_the_insanity() {
|
||||
// The value returned by progress_bar->current() might be padded. Remove padding, and convert to int.
|
||||
$current_iteration = intval( trim( $this->progress_bar->current() ) );
|
||||
if ( 0 === $current_iteration % 50 ) {
|
||||
$this->stop_the_insanity();
|
||||
}
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Commands for Action Scheduler.
|
||||
*/
|
||||
class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
|
||||
|
||||
/**
|
||||
* Force tables schema creation for Action Scheduler
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* @param array $args Positional arguments.
|
||||
* @param array $assoc_args Keyed arguments.
|
||||
*
|
||||
* @subcommand fix-schema
|
||||
*/
|
||||
public function fix_schema( $args, $assoc_args ) {
|
||||
$schema_classes = array( ActionScheduler_LoggerSchema::class, ActionScheduler_StoreSchema::class );
|
||||
|
||||
foreach ( $schema_classes as $classname ) {
|
||||
if ( is_subclass_of( $classname, ActionScheduler_Abstract_Schema::class ) ) {
|
||||
$obj = new $classname();
|
||||
$obj->init();
|
||||
$obj->register_tables( true );
|
||||
|
||||
WP_CLI::success(
|
||||
sprintf(
|
||||
/* translators: %s refers to the schema name*/
|
||||
__( 'Registered schema for %s', 'action-scheduler' ),
|
||||
$classname
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the Action Scheduler
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--batch-size=<size>]
|
||||
* : The maximum number of actions to run. Defaults to 100.
|
||||
*
|
||||
* [--batches=<size>]
|
||||
* : Limit execution to a number of batches. Defaults to 0, meaning batches will continue being executed until all actions are complete.
|
||||
*
|
||||
* [--cleanup-batch-size=<size>]
|
||||
* : The maximum number of actions to clean up. Defaults to the value of --batch-size.
|
||||
*
|
||||
* [--hooks=<hooks>]
|
||||
* : Only run actions with the specified hook. Omitting this option runs actions with any hook. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=hook_one,hook_two,hook_three`
|
||||
*
|
||||
* [--group=<group>]
|
||||
* : Only run actions from the specified group. Omitting this option runs actions from all groups.
|
||||
*
|
||||
* [--free-memory-on=<count>]
|
||||
* : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50.
|
||||
*
|
||||
* [--pause=<seconds>]
|
||||
* : The number of seconds to pause when freeing memory. Default no pause.
|
||||
*
|
||||
* [--force]
|
||||
* : Whether to force execution despite the maximum number of concurrent processes being exceeded.
|
||||
*
|
||||
* @param array $args Positional arguments.
|
||||
* @param array $assoc_args Keyed arguments.
|
||||
* @throws \WP_CLI\ExitException When an error occurs.
|
||||
*
|
||||
* @subcommand run
|
||||
*/
|
||||
public function run( $args, $assoc_args ) {
|
||||
// Handle passed arguments.
|
||||
$batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 100 ) );
|
||||
$batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) );
|
||||
$clean = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'cleanup-batch-size', $batch ) );
|
||||
$hooks = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'hooks', '' ) );
|
||||
$hooks = array_filter( array_map( 'trim', $hooks ) );
|
||||
$group = \WP_CLI\Utils\get_flag_value( $assoc_args, 'group', '' );
|
||||
$free_on = \WP_CLI\Utils\get_flag_value( $assoc_args, 'free-memory-on', 50 );
|
||||
$sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 );
|
||||
$force = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false );
|
||||
|
||||
ActionScheduler_DataController::set_free_ticks( $free_on );
|
||||
ActionScheduler_DataController::set_sleep_time( $sleep );
|
||||
|
||||
$batches_completed = 0;
|
||||
$actions_completed = 0;
|
||||
$unlimited = $batches === 0;
|
||||
|
||||
try {
|
||||
// Custom queue cleaner instance.
|
||||
$cleaner = new ActionScheduler_QueueCleaner( null, $clean );
|
||||
|
||||
// Get the queue runner instance
|
||||
$runner = new ActionScheduler_WPCLI_QueueRunner( null, null, $cleaner );
|
||||
|
||||
// Determine how many tasks will be run in the first batch.
|
||||
$total = $runner->setup( $batch, $hooks, $group, $force );
|
||||
|
||||
// Run actions for as long as possible.
|
||||
while ( $total > 0 ) {
|
||||
$this->print_total_actions( $total );
|
||||
$actions_completed += $runner->run();
|
||||
$batches_completed++;
|
||||
|
||||
// Maybe set up tasks for the next batch.
|
||||
$total = ( $unlimited || $batches_completed < $batches ) ? $runner->setup( $batch, $hooks, $group, $force ) : 0;
|
||||
}
|
||||
} catch ( Exception $e ) {
|
||||
$this->print_error( $e );
|
||||
}
|
||||
|
||||
$this->print_total_batches( $batches_completed );
|
||||
$this->print_success( $actions_completed );
|
||||
}
|
||||
|
||||
/**
|
||||
* Print WP CLI message about how many actions are about to be processed.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param int $total
|
||||
*/
|
||||
protected function print_total_actions( $total ) {
|
||||
WP_CLI::log(
|
||||
sprintf(
|
||||
/* translators: %d refers to how many scheduled taks were found to run */
|
||||
_n( 'Found %d scheduled task', 'Found %d scheduled tasks', $total, 'action-scheduler' ),
|
||||
number_format_i18n( $total )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Print WP CLI message about how many batches of actions were processed.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param int $batches_completed
|
||||
*/
|
||||
protected function print_total_batches( $batches_completed ) {
|
||||
WP_CLI::log(
|
||||
sprintf(
|
||||
/* translators: %d refers to the total number of batches executed */
|
||||
_n( '%d batch executed.', '%d batches executed.', $batches_completed, 'action-scheduler' ),
|
||||
number_format_i18n( $batches_completed )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an exception into a WP CLI error.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param Exception $e The error object.
|
||||
*
|
||||
* @throws \WP_CLI\ExitException
|
||||
*/
|
||||
protected function print_error( Exception $e ) {
|
||||
WP_CLI::error(
|
||||
sprintf(
|
||||
/* translators: %s refers to the exception error message */
|
||||
__( 'There was an error running the action scheduler: %s', 'action-scheduler' ),
|
||||
$e->getMessage()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Print a success message with the number of completed actions.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param int $actions_completed
|
||||
*/
|
||||
protected function print_success( $actions_completed ) {
|
||||
WP_CLI::success(
|
||||
sprintf(
|
||||
/* translators: %d refers to the total number of taskes completed */
|
||||
_n( '%d scheduled task completed.', '%d scheduled tasks completed.', $actions_completed, 'action-scheduler' ),
|
||||
number_format_i18n( $actions_completed )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\WP_CLI;
|
||||
|
||||
use Action_Scheduler\Migration\Config;
|
||||
use Action_Scheduler\Migration\Runner;
|
||||
use Action_Scheduler\Migration\Scheduler;
|
||||
use Action_Scheduler\Migration\Controller;
|
||||
use WP_CLI;
|
||||
use WP_CLI_Command;
|
||||
|
||||
/**
|
||||
* Class Migration_Command
|
||||
*
|
||||
* @package Action_Scheduler\WP_CLI
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class Migration_Command extends WP_CLI_Command {
|
||||
|
||||
/** @var int */
|
||||
private $total_processed = 0;
|
||||
|
||||
/**
|
||||
* Register the command with WP-CLI
|
||||
*/
|
||||
public function register() {
|
||||
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
|
||||
return;
|
||||
}
|
||||
|
||||
WP_CLI::add_command( 'action-scheduler migrate', [ $this, 'migrate' ], [
|
||||
'shortdesc' => 'Migrates actions to the DB tables store',
|
||||
'synopsis' => [
|
||||
[
|
||||
'type' => 'assoc',
|
||||
'name' => 'batch-size',
|
||||
'optional' => true,
|
||||
'default' => 100,
|
||||
'description' => 'The number of actions to process in each batch',
|
||||
],
|
||||
[
|
||||
'type' => 'assoc',
|
||||
'name' => 'free-memory-on',
|
||||
'optional' => true,
|
||||
'default' => 50,
|
||||
'description' => 'The number of actions to process between freeing memory. 0 disables freeing memory',
|
||||
],
|
||||
[
|
||||
'type' => 'assoc',
|
||||
'name' => 'pause',
|
||||
'optional' => true,
|
||||
'default' => 0,
|
||||
'description' => 'The number of seconds to pause when freeing memory',
|
||||
],
|
||||
[
|
||||
'type' => 'flag',
|
||||
'name' => 'dry-run',
|
||||
'optional' => true,
|
||||
'description' => 'Reports on the actions that would have been migrated, but does not change any data',
|
||||
],
|
||||
],
|
||||
] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the data migration.
|
||||
*
|
||||
* @param array $positional_args Required for WP CLI. Not used in migration.
|
||||
* @param array $assoc_args Optional arguments.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function migrate( $positional_args, $assoc_args ) {
|
||||
$this->init_logging();
|
||||
|
||||
$config = $this->get_migration_config( $assoc_args );
|
||||
$runner = new Runner( $config );
|
||||
$runner->init_destination();
|
||||
|
||||
$batch_size = isset( $assoc_args[ 'batch-size' ] ) ? (int) $assoc_args[ 'batch-size' ] : 100;
|
||||
$free_on = isset( $assoc_args[ 'free-memory-on' ] ) ? (int) $assoc_args[ 'free-memory-on' ] : 50;
|
||||
$sleep = isset( $assoc_args[ 'pause' ] ) ? (int) $assoc_args[ 'pause' ] : 0;
|
||||
\ActionScheduler_DataController::set_free_ticks( $free_on );
|
||||
\ActionScheduler_DataController::set_sleep_time( $sleep );
|
||||
|
||||
do {
|
||||
$actions_processed = $runner->run( $batch_size );
|
||||
$this->total_processed += $actions_processed;
|
||||
} while ( $actions_processed > 0 );
|
||||
|
||||
if ( ! $config->get_dry_run() ) {
|
||||
// let the scheduler know that there's nothing left to do
|
||||
$scheduler = new Scheduler();
|
||||
$scheduler->mark_complete();
|
||||
}
|
||||
|
||||
WP_CLI::success( sprintf( '%s complete. %d actions processed.', $config->get_dry_run() ? 'Dry run' : 'Migration', $this->total_processed ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the config object used to create the Runner
|
||||
*
|
||||
* @param array $args Optional arguments.
|
||||
*
|
||||
* @return ActionScheduler\Migration\Config
|
||||
*/
|
||||
private function get_migration_config( $args ) {
|
||||
$args = wp_parse_args( $args, [
|
||||
'dry-run' => false,
|
||||
] );
|
||||
|
||||
$config = Controller::instance()->get_migration_config_object();
|
||||
$config->set_dry_run( ! empty( $args[ 'dry-run' ] ) );
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook command line logging into migration actions.
|
||||
*/
|
||||
private function init_logging() {
|
||||
add_action( 'action_scheduler/migrate_action_dry_run', function ( $action_id ) {
|
||||
WP_CLI::debug( sprintf( 'Dry-run: migrated action %d', $action_id ) );
|
||||
}, 10, 1 );
|
||||
add_action( 'action_scheduler/no_action_to_migrate', function ( $action_id ) {
|
||||
WP_CLI::debug( sprintf( 'No action found to migrate for ID %d', $action_id ) );
|
||||
}, 10, 1 );
|
||||
add_action( 'action_scheduler/migrate_action_failed', function ( $action_id ) {
|
||||
WP_CLI::warning( sprintf( 'Failed migrating action with ID %d', $action_id ) );
|
||||
}, 10, 1 );
|
||||
add_action( 'action_scheduler/migrate_action_incomplete', function ( $source_id, $destination_id ) {
|
||||
WP_CLI::warning( sprintf( 'Unable to remove source action with ID %d after migrating to new ID %d', $source_id, $destination_id ) );
|
||||
}, 10, 2 );
|
||||
add_action( 'action_scheduler/migrated_action', function ( $source_id, $destination_id ) {
|
||||
WP_CLI::debug( sprintf( 'Migrated source action with ID %d to new store with ID %d', $source_id, $destination_id ) );
|
||||
}, 10, 2 );
|
||||
add_action( 'action_scheduler/migration_batch_starting', function ( $batch ) {
|
||||
WP_CLI::debug( 'Beginning migration of batch: ' . print_r( $batch, true ) );
|
||||
}, 10, 1 );
|
||||
add_action( 'action_scheduler/migration_batch_complete', function ( $batch ) {
|
||||
WP_CLI::log( sprintf( 'Completed migration of %d actions', count( $batch ) ) );
|
||||
}, 10, 1 );
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Action_Scheduler\WP_CLI;
|
||||
|
||||
/**
|
||||
* WP_CLI progress bar for Action Scheduler.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Class ProgressBar
|
||||
*
|
||||
* @package Action_Scheduler\WP_CLI
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class ProgressBar {
|
||||
|
||||
/** @var integer */
|
||||
protected $total_ticks;
|
||||
|
||||
/** @var integer */
|
||||
protected $count;
|
||||
|
||||
/** @var integer */
|
||||
protected $interval;
|
||||
|
||||
/** @var string */
|
||||
protected $message;
|
||||
|
||||
/** @var \cli\progress\Bar */
|
||||
protected $progress_bar;
|
||||
|
||||
/**
|
||||
* ProgressBar constructor.
|
||||
*
|
||||
* @param string $message Text to display before the progress bar.
|
||||
* @param integer $count Total number of ticks to be performed.
|
||||
* @param integer $interval Optional. The interval in milliseconds between updates. Default 100.
|
||||
*
|
||||
* @throws Exception When this is not run within WP CLI
|
||||
*/
|
||||
public function __construct( $message, $count, $interval = 100 ) {
|
||||
if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
|
||||
/* translators: %s php class name */
|
||||
throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
|
||||
}
|
||||
|
||||
$this->total_ticks = 0;
|
||||
$this->message = $message;
|
||||
$this->count = $count;
|
||||
$this->interval = $interval;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the progress bar ticks.
|
||||
*/
|
||||
public function tick() {
|
||||
if ( null === $this->progress_bar ) {
|
||||
$this->setup_progress_bar();
|
||||
}
|
||||
|
||||
$this->progress_bar->tick();
|
||||
$this->total_ticks++;
|
||||
|
||||
do_action( 'action_scheduler/progress_tick', $this->total_ticks );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the progress bar tick count.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function current() {
|
||||
return $this->progress_bar ? $this->progress_bar->current() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish the current progress bar.
|
||||
*/
|
||||
public function finish() {
|
||||
if ( null !== $this->progress_bar ) {
|
||||
$this->progress_bar->finish();
|
||||
}
|
||||
|
||||
$this->progress_bar = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the message used when creating the progress bar.
|
||||
*
|
||||
* @param string $message The message to be used when the next progress bar is created.
|
||||
*/
|
||||
public function set_message( $message ) {
|
||||
$this->message = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the count for a new progress bar.
|
||||
*
|
||||
* @param integer $count The total number of ticks expected to complete.
|
||||
*/
|
||||
public function set_count( $count ) {
|
||||
$this->count = $count;
|
||||
$this->finish();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up the progress bar.
|
||||
*/
|
||||
protected function setup_progress_bar() {
|
||||
$this->progress_bar = \WP_CLI\Utils\make_progress_bar(
|
||||
$this->message,
|
||||
$this->count,
|
||||
$this->interval
|
||||
);
|
||||
}
|
||||
}
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
<?php
|
||||
|
||||
use Action_Scheduler\WP_CLI\Migration_Command;
|
||||
use Action_Scheduler\Migration\Controller;
|
||||
|
||||
/**
|
||||
* Class ActionScheduler
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
abstract class ActionScheduler {
|
||||
private static $plugin_file = '';
|
||||
/** @var ActionScheduler_ActionFactory */
|
||||
private static $factory = NULL;
|
||||
/** @var bool */
|
||||
private static $data_store_initialized = false;
|
||||
|
||||
public static function factory() {
|
||||
if ( !isset(self::$factory) ) {
|
||||
self::$factory = new ActionScheduler_ActionFactory();
|
||||
}
|
||||
return self::$factory;
|
||||
}
|
||||
|
||||
public static function store() {
|
||||
return ActionScheduler_Store::instance();
|
||||
}
|
||||
|
||||
public static function lock() {
|
||||
return ActionScheduler_Lock::instance();
|
||||
}
|
||||
|
||||
public static function logger() {
|
||||
return ActionScheduler_Logger::instance();
|
||||
}
|
||||
|
||||
public static function runner() {
|
||||
return ActionScheduler_QueueRunner::instance();
|
||||
}
|
||||
|
||||
public static function admin_view() {
|
||||
return ActionScheduler_AdminView::instance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the absolute system path to the plugin directory, or a file therein
|
||||
* @static
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
public static function plugin_path( $path ) {
|
||||
$base = dirname(self::$plugin_file);
|
||||
if ( $path ) {
|
||||
return trailingslashit($base).$path;
|
||||
} else {
|
||||
return untrailingslashit($base);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the absolute URL to the plugin directory, or a file therein
|
||||
* @static
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
public static function plugin_url( $path ) {
|
||||
return plugins_url($path, self::$plugin_file);
|
||||
}
|
||||
|
||||
public static function autoload( $class ) {
|
||||
$d = DIRECTORY_SEPARATOR;
|
||||
$classes_dir = self::plugin_path( 'classes' . $d );
|
||||
$separator = strrpos( $class, '\\' );
|
||||
if ( false !== $separator ) {
|
||||
if ( 0 !== strpos( $class, 'Action_Scheduler' ) ) {
|
||||
return;
|
||||
}
|
||||
$class = substr( $class, $separator + 1 );
|
||||
}
|
||||
|
||||
if ( 'Deprecated' === substr( $class, -10 ) ) {
|
||||
$dir = self::plugin_path( 'deprecated' . $d );
|
||||
} elseif ( self::is_class_abstract( $class ) ) {
|
||||
$dir = $classes_dir . 'abstracts' . $d;
|
||||
} elseif ( self::is_class_migration( $class ) ) {
|
||||
$dir = $classes_dir . 'migration' . $d;
|
||||
} elseif ( 'Schedule' === substr( $class, -8 ) ) {
|
||||
$dir = $classes_dir . 'schedules' . $d;
|
||||
} elseif ( 'Action' === substr( $class, -6 ) ) {
|
||||
$dir = $classes_dir . 'actions' . $d;
|
||||
} elseif ( 'Schema' === substr( $class, -6 ) ) {
|
||||
$dir = $classes_dir . 'schema' . $d;
|
||||
} elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) {
|
||||
$segments = explode( '_', $class );
|
||||
$type = isset( $segments[ 1 ] ) ? $segments[ 1 ] : '';
|
||||
|
||||
switch ( $type ) {
|
||||
case 'WPCLI':
|
||||
$dir = $classes_dir . 'WP_CLI' . $d;
|
||||
break;
|
||||
case 'DBLogger':
|
||||
case 'DBStore':
|
||||
case 'HybridStore':
|
||||
case 'wpPostStore':
|
||||
case 'wpCommentLogger':
|
||||
$dir = $classes_dir . 'data-stores' . $d;
|
||||
break;
|
||||
default:
|
||||
$dir = $classes_dir;
|
||||
break;
|
||||
}
|
||||
} elseif ( self::is_class_cli( $class ) ) {
|
||||
$dir = $classes_dir . 'WP_CLI' . $d;
|
||||
} elseif ( strpos( $class, 'CronExpression' ) === 0 ) {
|
||||
$dir = self::plugin_path( 'lib' . $d . 'cron-expression' . $d );
|
||||
} elseif ( strpos( $class, 'WP_Async_Request' ) === 0 ) {
|
||||
$dir = self::plugin_path( 'lib' . $d );
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( file_exists( $dir . "{$class}.php" ) ) {
|
||||
include( $dir . "{$class}.php" );
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the plugin
|
||||
*
|
||||
* @static
|
||||
* @param string $plugin_file
|
||||
*/
|
||||
public static function init( $plugin_file ) {
|
||||
self::$plugin_file = $plugin_file;
|
||||
spl_autoload_register( array( __CLASS__, 'autoload' ) );
|
||||
|
||||
/**
|
||||
* Fires in the early stages of Action Scheduler init hook.
|
||||
*/
|
||||
do_action( 'action_scheduler_pre_init' );
|
||||
|
||||
require_once( self::plugin_path( 'functions.php' ) );
|
||||
ActionScheduler_DataController::init();
|
||||
|
||||
$store = self::store();
|
||||
$logger = self::logger();
|
||||
$runner = self::runner();
|
||||
$admin_view = self::admin_view();
|
||||
|
||||
// Ensure initialization on plugin activation.
|
||||
if ( ! did_action( 'init' ) ) {
|
||||
add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init()
|
||||
add_action( 'init', array( $store, 'init' ), 1, 0 );
|
||||
add_action( 'init', array( $logger, 'init' ), 1, 0 );
|
||||
add_action( 'init', array( $runner, 'init' ), 1, 0 );
|
||||
} else {
|
||||
$admin_view->init();
|
||||
$store->init();
|
||||
$logger->init();
|
||||
$runner->init();
|
||||
}
|
||||
|
||||
if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) {
|
||||
require_once( self::plugin_path( 'deprecated/functions.php' ) );
|
||||
}
|
||||
|
||||
if ( defined( 'WP_CLI' ) && WP_CLI ) {
|
||||
WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
|
||||
if ( ! ActionScheduler_DataController::is_migration_complete() && Controller::instance()->allow_migration() ) {
|
||||
$command = new Migration_Command();
|
||||
$command->register();
|
||||
}
|
||||
}
|
||||
|
||||
self::$data_store_initialized = true;
|
||||
|
||||
/**
|
||||
* Handle WP comment cleanup after migration.
|
||||
*/
|
||||
if ( is_a( $logger, 'ActionScheduler_DBLogger' ) && ActionScheduler_DataController::is_migration_complete() && ActionScheduler_WPCommentCleaner::has_logs() ) {
|
||||
ActionScheduler_WPCommentCleaner::init();
|
||||
}
|
||||
|
||||
add_action( 'action_scheduler/migration_complete', 'ActionScheduler_WPCommentCleaner::maybe_schedule_cleanup' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the AS data store has been initialized.
|
||||
*
|
||||
* @param string $function_name The name of the function being called. Optional. Default `null`.
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_initialized( $function_name = null ) {
|
||||
if ( ! self::$data_store_initialized && ! empty( $function_name ) ) {
|
||||
$message = sprintf( __( '%s() was called before the Action Scheduler data store was initialized', 'action-scheduler' ), esc_attr( $function_name ) );
|
||||
error_log( $message, E_WARNING );
|
||||
}
|
||||
|
||||
return self::$data_store_initialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the class is one of our abstract classes.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $class The class name.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function is_class_abstract( $class ) {
|
||||
static $abstracts = array(
|
||||
'ActionScheduler' => true,
|
||||
'ActionScheduler_Abstract_ListTable' => true,
|
||||
'ActionScheduler_Abstract_QueueRunner' => true,
|
||||
'ActionScheduler_Abstract_Schedule' => true,
|
||||
'ActionScheduler_Abstract_RecurringSchedule' => true,
|
||||
'ActionScheduler_Lock' => true,
|
||||
'ActionScheduler_Logger' => true,
|
||||
'ActionScheduler_Abstract_Schema' => true,
|
||||
'ActionScheduler_Store' => true,
|
||||
'ActionScheduler_TimezoneHelper' => true,
|
||||
);
|
||||
|
||||
return isset( $abstracts[ $class ] ) && $abstracts[ $class ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the class is one of our migration classes.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $class The class name.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function is_class_migration( $class ) {
|
||||
static $migration_segments = array(
|
||||
'ActionMigrator' => true,
|
||||
'BatchFetcher' => true,
|
||||
'DBStoreMigrator' => true,
|
||||
'DryRun' => true,
|
||||
'LogMigrator' => true,
|
||||
'Config' => true,
|
||||
'Controller' => true,
|
||||
'Runner' => true,
|
||||
'Scheduler' => true,
|
||||
);
|
||||
|
||||
$segments = explode( '_', $class );
|
||||
$segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class;
|
||||
|
||||
return isset( $migration_segments[ $segment ] ) && $migration_segments[ $segment ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the class is one of our WP CLI classes.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $class The class name.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function is_class_cli( $class ) {
|
||||
static $cli_segments = array(
|
||||
'QueueRunner' => true,
|
||||
'Command' => true,
|
||||
'ProgressBar' => true,
|
||||
);
|
||||
|
||||
$segments = explode( '_', $class );
|
||||
$segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class;
|
||||
|
||||
return isset( $cli_segments[ $segment ] ) && $cli_segments[ $segment ];
|
||||
}
|
||||
|
||||
final public function __clone() {
|
||||
trigger_error("Singleton. No cloning allowed!", E_USER_ERROR);
|
||||
}
|
||||
|
||||
final public function __wakeup() {
|
||||
trigger_error("Singleton. No serialization allowed!", E_USER_ERROR);
|
||||
}
|
||||
|
||||
final private function __construct() {}
|
||||
|
||||
/** Deprecated **/
|
||||
|
||||
public static function get_datetime_object( $when = null, $timezone = 'UTC' ) {
|
||||
_deprecated_function( __METHOD__, '2.0', 'wcs_add_months()' );
|
||||
return as_get_datetime_object( $when, $timezone );
|
||||
}
|
||||
|
||||
/**
|
||||
* Issue deprecated warning if an Action Scheduler function is called in the shutdown hook.
|
||||
*
|
||||
* @param string $function_name The name of the function being called.
|
||||
* @deprecated 3.1.6.
|
||||
*/
|
||||
public static function check_shutdown_hook( $function_name ) {
|
||||
_deprecated_function( __FUNCTION__, '3.1.6' );
|
||||
}
|
||||
}
|
||||
+766
@@ -0,0 +1,766 @@
|
||||
<?php
|
||||
|
||||
if ( ! class_exists( 'WP_List_Table' ) ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Action Scheduler Abstract List Table class
|
||||
*
|
||||
* This abstract class enhances WP_List_Table making it ready to use.
|
||||
*
|
||||
* By extending this class we can focus on describing how our table looks like,
|
||||
* which columns needs to be shown, filter, ordered by and more and forget about the details.
|
||||
*
|
||||
* This class supports:
|
||||
* - Bulk actions
|
||||
* - Search
|
||||
* - Sortable columns
|
||||
* - Automatic translations of the columns
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
* @since 2.0.0
|
||||
*/
|
||||
abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
|
||||
|
||||
/**
|
||||
* The table name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table_name;
|
||||
|
||||
/**
|
||||
* Package name, used to get options from WP_List_Table::get_items_per_page.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $package;
|
||||
|
||||
/**
|
||||
* How many items do we render per page?
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $items_per_page = 10;
|
||||
|
||||
/**
|
||||
* Enables search in this table listing. If this array
|
||||
* is empty it means the listing is not searchable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $search_by = array();
|
||||
|
||||
/**
|
||||
* Columns to show in the table listing. It is a key => value pair. The
|
||||
* key must much the table column name and the value is the label, which is
|
||||
* automatically translated.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $columns = array();
|
||||
|
||||
/**
|
||||
* Defines the row-actions. It expects an array where the key
|
||||
* is the column name and the value is an array of actions.
|
||||
*
|
||||
* The array of actions are key => value, where key is the method name
|
||||
* (with the prefix row_action_<key>) and the value is the label
|
||||
* and title.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $row_actions = array();
|
||||
|
||||
/**
|
||||
* The Primary key of our table
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $ID = 'ID';
|
||||
|
||||
/**
|
||||
* Enables sorting, it expects an array
|
||||
* of columns (the column names are the values)
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $sort_by = array();
|
||||
|
||||
/**
|
||||
* The default sort order
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $filter_by = array();
|
||||
|
||||
/**
|
||||
* The status name => count combinations for this table's items. Used to display status filters.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $status_counts = array();
|
||||
|
||||
/**
|
||||
* Notices to display when loading the table. Array of arrays of form array( 'class' => {updated|error}, 'message' => 'This is the notice text display.' ).
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $admin_notices = array();
|
||||
|
||||
/**
|
||||
* Localised string displayed in the <h1> element above the able.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table_header;
|
||||
|
||||
/**
|
||||
* Enables bulk actions. It must be an array where the key is the action name
|
||||
* and the value is the label (which is translated automatically). It is important
|
||||
* to notice that it will check that the method exists (`bulk_$name`) and will throw
|
||||
* an exception if it does not exists.
|
||||
*
|
||||
* This class will automatically check if the current request has a bulk action, will do the
|
||||
* validations and afterwards will execute the bulk method, with two arguments. The first argument
|
||||
* is the array with primary keys, the second argument is a string with a list of the primary keys,
|
||||
* escaped and ready to use (with `IN`).
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $bulk_actions = array();
|
||||
|
||||
/**
|
||||
* Makes translation easier, it basically just wraps
|
||||
* `_x` with some default (the package name).
|
||||
*
|
||||
* @param string $text The new text to translate.
|
||||
* @param string $context The context of the text.
|
||||
* @return string|void The translated text.
|
||||
*
|
||||
* @deprecated 3.0.0 Use `_x()` instead.
|
||||
*/
|
||||
protected function translate( $text, $context = '' ) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads `$this->bulk_actions` and returns an array that WP_List_Table understands. It
|
||||
* also validates that the bulk method handler exists. It throws an exception because
|
||||
* this is a library meant for developers and missing a bulk method is a development-time error.
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @throws RuntimeException Throws RuntimeException when the bulk action does not have a callback method.
|
||||
*/
|
||||
protected function get_bulk_actions() {
|
||||
$actions = array();
|
||||
|
||||
foreach ( $this->bulk_actions as $action => $label ) {
|
||||
if ( ! is_callable( array( $this, 'bulk_' . $action ) ) ) {
|
||||
throw new RuntimeException( "The bulk action $action does not have a callback method" );
|
||||
}
|
||||
|
||||
$actions[ $action ] = $label;
|
||||
}
|
||||
|
||||
return $actions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current request has a bulk action. If that is the case it will validate and will
|
||||
* execute the bulk method handler. Regardless if the action is valid or not it will redirect to
|
||||
* the previous page removing the current arguments that makes this request a bulk action.
|
||||
*/
|
||||
protected function process_bulk_action() {
|
||||
global $wpdb;
|
||||
// Detect when a bulk action is being triggered.
|
||||
$action = $this->current_action();
|
||||
if ( ! $action ) {
|
||||
return;
|
||||
}
|
||||
|
||||
check_admin_referer( 'bulk-' . $this->_args['plural'] );
|
||||
|
||||
$method = 'bulk_' . $action;
|
||||
if ( array_key_exists( $action, $this->bulk_actions ) && is_callable( array( $this, $method ) ) && ! empty( $_GET['ID'] ) && is_array( $_GET['ID'] ) ) {
|
||||
$ids_sql = '(' . implode( ',', array_fill( 0, count( $_GET['ID'] ), '%s' ) ) . ')';
|
||||
$id = array_map( 'absint', $_GET['ID'] );
|
||||
$this->$method( $id, $wpdb->prepare( $ids_sql, $id ) ); //phpcs:ignore WordPress.DB.PreparedSQL
|
||||
}
|
||||
|
||||
if ( isset( $_SERVER['REQUEST_URI'] ) ) {
|
||||
wp_safe_redirect(
|
||||
remove_query_arg(
|
||||
array( '_wp_http_referer', '_wpnonce', 'ID', 'action', 'action2' ),
|
||||
esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) )
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Default code for deleting entries.
|
||||
* validated already by process_bulk_action()
|
||||
*
|
||||
* @param array $ids ids of the items to delete.
|
||||
* @param string $ids_sql the sql for the ids.
|
||||
* @return void
|
||||
*/
|
||||
protected function bulk_delete( array $ids, $ids_sql ) {
|
||||
$store = ActionScheduler::store();
|
||||
foreach ( $ids as $action_id ) {
|
||||
$store->delete( $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the _column_headers property which is used by WP_Table_List at rendering.
|
||||
* It merges the columns and the sortable columns.
|
||||
*/
|
||||
protected function prepare_column_headers() {
|
||||
$this->_column_headers = array(
|
||||
$this->get_columns(),
|
||||
get_hidden_columns( $this->screen ),
|
||||
$this->get_sortable_columns(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads $this->sort_by and returns the columns name in a format that WP_Table_List
|
||||
* expects
|
||||
*/
|
||||
public function get_sortable_columns() {
|
||||
$sort_by = array();
|
||||
foreach ( $this->sort_by as $column ) {
|
||||
$sort_by[ $column ] = array( $column, true );
|
||||
}
|
||||
return $sort_by;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the columns names for rendering. It adds a checkbox for selecting everything
|
||||
* as the first column
|
||||
*/
|
||||
public function get_columns() {
|
||||
$columns = array_merge(
|
||||
array( 'cb' => '<input type="checkbox" />' ),
|
||||
$this->columns
|
||||
);
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get prepared LIMIT clause for items query
|
||||
*
|
||||
* @global wpdb $wpdb
|
||||
*
|
||||
* @return string Prepared LIMIT clause for items query.
|
||||
*/
|
||||
protected function get_items_query_limit() {
|
||||
global $wpdb;
|
||||
|
||||
$per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );
|
||||
return $wpdb->prepare( 'LIMIT %d', $per_page );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of items to offset/skip for this current view.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function get_items_offset() {
|
||||
$per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );
|
||||
$current_page = $this->get_pagenum();
|
||||
if ( 1 < $current_page ) {
|
||||
$offset = $per_page * ( $current_page - 1 );
|
||||
} else {
|
||||
$offset = 0;
|
||||
}
|
||||
|
||||
return $offset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get prepared OFFSET clause for items query
|
||||
*
|
||||
* @global wpdb $wpdb
|
||||
*
|
||||
* @return string Prepared OFFSET clause for items query.
|
||||
*/
|
||||
protected function get_items_query_offset() {
|
||||
global $wpdb;
|
||||
|
||||
return $wpdb->prepare( 'OFFSET %d', $this->get_items_offset() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the ORDER BY sql statement. It uses `$this->sort_by` to know which
|
||||
* columns are sortable. This requests validates the orderby $_GET parameter is a valid
|
||||
* column and sortable. It will also use order (ASC|DESC) using DESC by default.
|
||||
*/
|
||||
protected function get_items_query_order() {
|
||||
if ( empty( $this->sort_by ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$orderby = esc_sql( $this->get_request_orderby() );
|
||||
$order = esc_sql( $this->get_request_order() );
|
||||
|
||||
return "ORDER BY {$orderby} {$order}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the sortable column specified for this request to order the results by, if any.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_request_orderby() {
|
||||
|
||||
$valid_sortable_columns = array_values( $this->sort_by );
|
||||
|
||||
if ( ! empty( $_GET['orderby'] ) && in_array( $_GET['orderby'], $valid_sortable_columns, true ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
$orderby = sanitize_text_field( wp_unslash( $_GET['orderby'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
} else {
|
||||
$orderby = $valid_sortable_columns[0];
|
||||
}
|
||||
|
||||
return $orderby;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the sortable column order specified for this request.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_request_order() {
|
||||
|
||||
if ( ! empty( $_GET['order'] ) && 'desc' === strtolower( sanitize_text_field( wp_unslash( $_GET['order'] ) ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
$order = 'DESC';
|
||||
} else {
|
||||
$order = 'ASC';
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the status filter for this request, if any.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_request_status() {
|
||||
$status = ( ! empty( $_GET['status'] ) ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return $status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the search filter for this request, if any.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_request_search_query() {
|
||||
$search_query = ( ! empty( $_GET['s'] ) ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return $search_query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process and return the columns name. This is meant for using with SQL, this means it
|
||||
* always includes the primary key.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_table_columns() {
|
||||
$columns = array_keys( $this->columns );
|
||||
if ( ! in_array( $this->ID, $columns, true ) ) {
|
||||
$columns[] = $this->ID;
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current request is doing a "full text" search. If that is the case
|
||||
* prepares the SQL to search texts using LIKE.
|
||||
*
|
||||
* If the current request does not have any search or if this list table does not support
|
||||
* that feature it will return an empty string.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_items_query_search() {
|
||||
global $wpdb;
|
||||
|
||||
if ( empty( $_GET['s'] ) || empty( $this->search_by ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return '';
|
||||
}
|
||||
|
||||
$search_string = sanitize_text_field( wp_unslash( $_GET['s'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
$filter = array();
|
||||
foreach ( $this->search_by as $column ) {
|
||||
$wild = '%';
|
||||
$sql_like = $wild . $wpdb->esc_like( $search_string ) . $wild;
|
||||
$filter[] = $wpdb->prepare( '`' . $column . '` LIKE %s', $sql_like ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.NotPrepared
|
||||
}
|
||||
return implode( ' OR ', $filter );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the SQL to filter rows by the options defined at `$this->filter_by`. Before trusting
|
||||
* any data sent by the user it validates that it is a valid option.
|
||||
*/
|
||||
protected function get_items_query_filters() {
|
||||
global $wpdb;
|
||||
|
||||
if ( ! $this->filter_by || empty( $_GET['filter_by'] ) || ! is_array( $_GET['filter_by'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return '';
|
||||
}
|
||||
|
||||
$filter = array();
|
||||
|
||||
foreach ( $this->filter_by as $column => $options ) {
|
||||
if ( empty( $_GET['filter_by'][ $column ] ) || empty( $options[ $_GET['filter_by'][ $column ] ] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
continue;
|
||||
}
|
||||
|
||||
$filter[] = $wpdb->prepare( "`$column` = %s", sanitize_text_field( wp_unslash( $_GET['filter_by'][ $column ] ) ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
}
|
||||
|
||||
return implode( ' AND ', $filter );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the data to feed WP_Table_List.
|
||||
*
|
||||
* This has the core for selecting, sorting and filting data. To keep the code simple
|
||||
* its logic is split among many methods (get_items_query_*).
|
||||
*
|
||||
* Beside populating the items this function will also count all the records that matches
|
||||
* the filtering criteria and will do fill the pagination variables.
|
||||
*/
|
||||
public function prepare_items() {
|
||||
global $wpdb;
|
||||
|
||||
$this->process_bulk_action();
|
||||
|
||||
$this->process_row_actions();
|
||||
|
||||
if ( ! empty( $_REQUEST['_wp_http_referer'] && ! empty( $_SERVER['REQUEST_URI'] ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
|
||||
wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
$this->prepare_column_headers();
|
||||
|
||||
$limit = $this->get_items_query_limit();
|
||||
$offset = $this->get_items_query_offset();
|
||||
$order = $this->get_items_query_order();
|
||||
$where = array_filter(
|
||||
array(
|
||||
$this->get_items_query_search(),
|
||||
$this->get_items_query_filters(),
|
||||
)
|
||||
);
|
||||
$columns = '`' . implode( '`, `', $this->get_table_columns() ) . '`';
|
||||
|
||||
if ( ! empty( $where ) ) {
|
||||
$where = 'WHERE (' . implode( ') AND (', $where ) . ')';
|
||||
} else {
|
||||
$where = '';
|
||||
}
|
||||
|
||||
$sql = "SELECT $columns FROM {$this->table_name} {$where} {$order} {$limit} {$offset}";
|
||||
|
||||
$this->set_items( $wpdb->get_results( $sql, ARRAY_A ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
|
||||
|
||||
$query_count = "SELECT COUNT({$this->ID}) FROM {$this->table_name} {$where}";
|
||||
$total_items = $wpdb->get_var( $query_count ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
|
||||
$per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );
|
||||
$this->set_pagination_args(
|
||||
array(
|
||||
'total_items' => $total_items,
|
||||
'per_page' => $per_page,
|
||||
'total_pages' => ceil( $total_items / $per_page ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the table.
|
||||
*
|
||||
* @param string $which The name of the table.
|
||||
*/
|
||||
public function extra_tablenav( $which ) {
|
||||
if ( ! $this->filter_by || 'top' !== $which ) {
|
||||
return;
|
||||
}
|
||||
|
||||
echo '<div class="alignleft actions">';
|
||||
|
||||
foreach ( $this->filter_by as $id => $options ) {
|
||||
$default = ! empty( $_GET['filter_by'][ $id ] ) ? sanitize_text_field( wp_unslash( $_GET['filter_by'][ $id ] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
if ( empty( $options[ $default ] ) ) {
|
||||
$default = '';
|
||||
}
|
||||
|
||||
echo '<select name="filter_by[' . esc_attr( $id ) . ']" class="first" id="filter-by-' . esc_attr( $id ) . '">';
|
||||
|
||||
foreach ( $options as $value => $label ) {
|
||||
echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value === $default ? 'selected' : '' ) . '>'
|
||||
. esc_html( $label )
|
||||
. '</option>';
|
||||
}
|
||||
|
||||
echo '</select>';
|
||||
}
|
||||
|
||||
submit_button( esc_html__( 'Filter', 'action-scheduler' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the data for displaying. It will attempt to unserialize (There is a chance that some columns
|
||||
* are serialized). This can be override in child classes for futher data transformation.
|
||||
*
|
||||
* @param array $items Items array.
|
||||
*/
|
||||
protected function set_items( array $items ) {
|
||||
$this->items = array();
|
||||
foreach ( $items as $item ) {
|
||||
$this->items[ $item[ $this->ID ] ] = array_map( 'maybe_unserialize', $item );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the checkbox for each row, this is the first column and it is named ID regardless
|
||||
* of how the primary key is named (to keep the code simpler). The bulk actions will do the proper
|
||||
* name transformation though using `$this->ID`.
|
||||
*
|
||||
* @param array $row The row to render.
|
||||
*/
|
||||
public function column_cb( $row ) {
|
||||
return '<input name="ID[]" type="checkbox" value="' . esc_attr( $row[ $this->ID ] ) . '" />';
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the row-actions.
|
||||
*
|
||||
* This method renders the action menu, it reads the definition from the $row_actions property,
|
||||
* and it checks that the row action method exists before rendering it.
|
||||
*
|
||||
* @param array $row Row to be rendered.
|
||||
* @param string $column_name Column name.
|
||||
* @return string
|
||||
*/
|
||||
protected function maybe_render_actions( $row, $column_name ) {
|
||||
if ( empty( $this->row_actions[ $column_name ] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$row_id = $row[ $this->ID ];
|
||||
|
||||
$actions = '<div class="row-actions">';
|
||||
$action_count = 0;
|
||||
foreach ( $this->row_actions[ $column_name ] as $action_key => $action ) {
|
||||
|
||||
$action_count++;
|
||||
|
||||
if ( ! method_exists( $this, 'row_action_' . $action_key ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$action_link = ! empty( $action['link'] ) ? $action['link'] : add_query_arg(
|
||||
array(
|
||||
'row_action' => $action_key,
|
||||
'row_id' => $row_id,
|
||||
'nonce' => wp_create_nonce( $action_key . '::' . $row_id ),
|
||||
)
|
||||
);
|
||||
$span_class = ! empty( $action['class'] ) ? $action['class'] : $action_key;
|
||||
$separator = ( $action_count < count( $this->row_actions[ $column_name ] ) ) ? ' | ' : '';
|
||||
|
||||
$actions .= sprintf( '<span class="%s">', esc_attr( $span_class ) );
|
||||
$actions .= sprintf( '<a href="%1$s" title="%2$s">%3$s</a>', esc_url( $action_link ), esc_attr( $action['desc'] ), esc_html( $action['name'] ) );
|
||||
$actions .= sprintf( '%s</span>', $separator );
|
||||
}
|
||||
$actions .= '</div>';
|
||||
return $actions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the bulk actions.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function process_row_actions() {
|
||||
$parameters = array( 'row_action', 'row_id', 'nonce' );
|
||||
foreach ( $parameters as $parameter ) {
|
||||
if ( empty( $_REQUEST[ $parameter ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$action = sanitize_text_field( wp_unslash( $_REQUEST['row_action'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
|
||||
$row_id = sanitize_text_field( wp_unslash( $_REQUEST['row_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
|
||||
$nonce = sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
|
||||
$method = 'row_action_' . $action; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
if ( wp_verify_nonce( $nonce, $action . '::' . $row_id ) && method_exists( $this, $method ) ) {
|
||||
$this->$method( sanitize_text_field( wp_unslash( $row_id ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
}
|
||||
|
||||
if ( isset( $_SERVER['REQUEST_URI'] ) ) {
|
||||
wp_safe_redirect(
|
||||
remove_query_arg(
|
||||
array( 'row_id', 'row_action', 'nonce' ),
|
||||
esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) )
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Default column formatting, it will escape everythig for security.
|
||||
*
|
||||
* @param array $item The item array.
|
||||
* @param string $column_name Column name to display.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function column_default( $item, $column_name ) {
|
||||
$column_html = esc_html( $item[ $column_name ] );
|
||||
$column_html .= $this->maybe_render_actions( $item, $column_name );
|
||||
return $column_html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the table heading and search query, if any
|
||||
*/
|
||||
protected function display_header() {
|
||||
echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>';
|
||||
if ( $this->get_request_search_query() ) {
|
||||
/* translators: %s: search query */
|
||||
echo '<span class="subtitle">' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $this->get_request_search_query() ) ) . '</span>';
|
||||
}
|
||||
echo '<hr class="wp-header-end">';
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the table heading and search query, if any
|
||||
*/
|
||||
protected function display_admin_notices() {
|
||||
foreach ( $this->admin_notices as $notice ) {
|
||||
echo '<div id="message" class="' . esc_attr( $notice['class'] ) . '">';
|
||||
echo ' <p>' . wp_kses_post( $notice['message'] ) . '</p>';
|
||||
echo '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the available statuses so the user can click to filter.
|
||||
*/
|
||||
protected function display_filter_by_status() {
|
||||
|
||||
$status_list_items = array();
|
||||
$request_status = $this->get_request_status();
|
||||
|
||||
// Helper to set 'all' filter when not set on status counts passed in.
|
||||
if ( ! isset( $this->status_counts['all'] ) ) {
|
||||
$this->status_counts = array( 'all' => array_sum( $this->status_counts ) ) + $this->status_counts;
|
||||
}
|
||||
|
||||
foreach ( $this->status_counts as $status_name => $count ) {
|
||||
|
||||
if ( 0 === $count ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( $status_name === $request_status || ( empty( $request_status ) && 'all' === $status_name ) ) {
|
||||
$status_list_item = '<li class="%1$s"><a href="%2$s" class="current">%3$s</a> (%4$d)</li>';
|
||||
} else {
|
||||
$status_list_item = '<li class="%1$s"><a href="%2$s">%3$s</a> (%4$d)</li>';
|
||||
}
|
||||
|
||||
$status_filter_url = ( 'all' === $status_name ) ? remove_query_arg( 'status' ) : add_query_arg( 'status', $status_name );
|
||||
$status_filter_url = remove_query_arg( array( 'paged', 's' ), $status_filter_url );
|
||||
$status_list_items[] = sprintf( $status_list_item, esc_attr( $status_name ), esc_url( $status_filter_url ), esc_html( ucfirst( $status_name ) ), absint( $count ) );
|
||||
}
|
||||
|
||||
if ( $status_list_items ) {
|
||||
echo '<ul class="subsubsub">';
|
||||
echo implode( " | \n", $status_list_items ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
echo '</ul>';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the table list, we override the original class to render the table inside a form
|
||||
* and to render any needed HTML (like the search box). By doing so the callee of a function can simple
|
||||
* forget about any extra HTML.
|
||||
*/
|
||||
protected function display_table() {
|
||||
echo '<form id="' . esc_attr( $this->_args['plural'] ) . '-filter" method="get">';
|
||||
foreach ( $_GET as $key => $value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
if ( '_' === $key[0] || 'paged' === $key || 'ID' === $key ) {
|
||||
continue;
|
||||
}
|
||||
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $value ) . '" />';
|
||||
}
|
||||
if ( ! empty( $this->search_by ) ) {
|
||||
echo $this->search_box( $this->get_search_box_button_text(), 'plugin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
}
|
||||
parent::display();
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Process any pending actions.
|
||||
*/
|
||||
public function process_actions() {
|
||||
$this->process_bulk_action();
|
||||
$this->process_row_actions();
|
||||
|
||||
if ( ! empty( $_REQUEST['_wp_http_referer'] ) && ! empty( $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
|
||||
wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the list table page, including header, notices, status filters and table.
|
||||
*/
|
||||
public function display_page() {
|
||||
$this->prepare_items();
|
||||
|
||||
echo '<div class="wrap">';
|
||||
$this->display_header();
|
||||
$this->display_admin_notices();
|
||||
$this->display_filter_by_status();
|
||||
$this->display_table();
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the text to display in the search box on the list table.
|
||||
*/
|
||||
protected function get_search_box_placeholder() {
|
||||
return esc_html__( 'Search', 'action-scheduler' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the screen per_page option name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_per_page_option_name() {
|
||||
return $this->package . '_items_per_page';
|
||||
}
|
||||
}
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Abstract class with common Queue Cleaner functionality.
|
||||
*/
|
||||
abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abstract_QueueRunner_Deprecated {
|
||||
|
||||
/** @var ActionScheduler_QueueCleaner */
|
||||
protected $cleaner;
|
||||
|
||||
/** @var ActionScheduler_FatalErrorMonitor */
|
||||
protected $monitor;
|
||||
|
||||
/** @var ActionScheduler_Store */
|
||||
protected $store;
|
||||
|
||||
/**
|
||||
* The created time.
|
||||
*
|
||||
* Represents when the queue runner was constructed and used when calculating how long a PHP request has been running.
|
||||
* For this reason it should be as close as possible to the PHP request start time.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $created_time;
|
||||
|
||||
/**
|
||||
* ActionScheduler_Abstract_QueueRunner constructor.
|
||||
*
|
||||
* @param ActionScheduler_Store $store
|
||||
* @param ActionScheduler_FatalErrorMonitor $monitor
|
||||
* @param ActionScheduler_QueueCleaner $cleaner
|
||||
*/
|
||||
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
|
||||
|
||||
$this->created_time = microtime( true );
|
||||
|
||||
$this->store = $store ? $store : ActionScheduler_Store::instance();
|
||||
$this->monitor = $monitor ? $monitor : new ActionScheduler_FatalErrorMonitor( $this->store );
|
||||
$this->cleaner = $cleaner ? $cleaner : new ActionScheduler_QueueCleaner( $this->store );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process an individual action.
|
||||
*
|
||||
* @param int $action_id The action ID to process.
|
||||
* @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.
|
||||
*/
|
||||
public function process_action( $action_id, $context = '' ) {
|
||||
try {
|
||||
$valid_action = false;
|
||||
do_action( 'action_scheduler_before_execute', $action_id, $context );
|
||||
|
||||
if ( ActionScheduler_Store::STATUS_PENDING !== $this->store->get_status( $action_id ) ) {
|
||||
do_action( 'action_scheduler_execution_ignored', $action_id, $context );
|
||||
return;
|
||||
}
|
||||
|
||||
$valid_action = true;
|
||||
do_action( 'action_scheduler_begin_execute', $action_id, $context );
|
||||
|
||||
$action = $this->store->fetch_action( $action_id );
|
||||
$this->store->log_execution( $action_id );
|
||||
$action->execute();
|
||||
do_action( 'action_scheduler_after_execute', $action_id, $action, $context );
|
||||
$this->store->mark_complete( $action_id );
|
||||
} catch ( Exception $e ) {
|
||||
if ( $valid_action ) {
|
||||
$this->store->mark_failure( $action_id );
|
||||
do_action( 'action_scheduler_failed_execution', $action_id, $e, $context );
|
||||
} else {
|
||||
do_action( 'action_scheduler_failed_validation', $action_id, $e, $context );
|
||||
}
|
||||
}
|
||||
|
||||
if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) {
|
||||
$this->schedule_next_instance( $action, $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule the next instance of the action if necessary.
|
||||
*
|
||||
* @param ActionScheduler_Action $action
|
||||
* @param int $action_id
|
||||
*/
|
||||
protected function schedule_next_instance( ActionScheduler_Action $action, $action_id ) {
|
||||
// If a recurring action has been consistently failing, we may wish to stop rescheduling it.
|
||||
if (
|
||||
ActionScheduler_Store::STATUS_FAILED === $this->store->get_status( $action_id )
|
||||
&& $this->recurring_action_is_consistently_failing( $action, $action_id )
|
||||
) {
|
||||
ActionScheduler_Logger::instance()->log(
|
||||
$action_id,
|
||||
__( 'This action appears to be consistently failing. A new instance will not be scheduled.', 'action-scheduler' )
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ActionScheduler::factory()->repeat( $action );
|
||||
} catch ( Exception $e ) {
|
||||
do_action( 'action_scheduler_failed_to_schedule_next_instance', $action_id, $e, $action );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the specified recurring action has been consistently failing.
|
||||
*
|
||||
* @param ActionScheduler_Action $action The recurring action to be rescheduled.
|
||||
* @param int $action_id The ID of the recurring action.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function recurring_action_is_consistently_failing( ActionScheduler_Action $action, $action_id ) {
|
||||
/**
|
||||
* Controls the failure threshold for recurring actions.
|
||||
*
|
||||
* Before rescheduling a recurring action, we look at its status. If it failed, we then check if all of the most
|
||||
* recent actions (upto the threshold set by this filter) sharing the same hook have also failed: if they have,
|
||||
* that is considered consistent failure and a new instance of the action will not be scheduled.
|
||||
*
|
||||
* @param int $failure_threshold Number of actions of the same hook to examine for failure. Defaults to 5.
|
||||
*/
|
||||
$consistent_failure_threshold = (int) apply_filters( 'action_scheduler_recurring_action_failure_threshold', 5 );
|
||||
|
||||
// This query should find the earliest *failing* action (for the hook we are interested in) within our threshold.
|
||||
$query_args = array(
|
||||
'hook' => $action->get_hook(),
|
||||
'status' => ActionScheduler_Store::STATUS_FAILED,
|
||||
'date' => date_create( 'now', timezone_open( 'UTC' ) )->format( 'Y-m-d H:i:s' ),
|
||||
'date_compare' => '<',
|
||||
'per_page' => 1,
|
||||
'offset' => $consistent_failure_threshold - 1
|
||||
);
|
||||
|
||||
$first_failing_action_id = $this->store->query_actions( $query_args );
|
||||
|
||||
// If we didn't retrieve an action ID, then there haven't been enough failures for us to worry about.
|
||||
if ( empty( $first_failing_action_id ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now let's fetch the first action (having the same hook) of *any status*ithin the same window.
|
||||
unset( $query_args['status'] );
|
||||
$first_action_id_with_the_same_hook = $this->store->query_actions( $query_args );
|
||||
|
||||
// If the IDs match, then actions for this hook must be consistently failing.
|
||||
return $first_action_id_with_the_same_hook === $first_failing_action_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the queue cleaner.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*/
|
||||
protected function run_cleanup() {
|
||||
$this->cleaner->clean( 10 * $this->get_time_limit() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of concurrent batches a runner allows.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_allowed_concurrent_batches() {
|
||||
return apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 1 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the number of allowed concurrent batches is met or exceeded.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function has_maximum_concurrent_batches() {
|
||||
return $this->store->get_claim_count() >= $this->get_allowed_concurrent_batches();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the maximum number of seconds a batch can run for.
|
||||
*
|
||||
* @return int The number of seconds.
|
||||
*/
|
||||
protected function get_time_limit() {
|
||||
|
||||
$time_limit = 30;
|
||||
|
||||
// Apply deprecated filter from deprecated get_maximum_execution_time() method
|
||||
if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) {
|
||||
_deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' );
|
||||
$time_limit = apply_filters( 'action_scheduler_maximum_execution_time', $time_limit );
|
||||
}
|
||||
|
||||
return absint( apply_filters( 'action_scheduler_queue_runner_time_limit', $time_limit ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of seconds the process has been running.
|
||||
*
|
||||
* @return int The number of seconds.
|
||||
*/
|
||||
protected function get_execution_time() {
|
||||
$execution_time = microtime( true ) - $this->created_time;
|
||||
|
||||
// Get the CPU time if the hosting environment uses it rather than wall-clock time to calculate a process's execution time.
|
||||
if ( function_exists( 'getrusage' ) && apply_filters( 'action_scheduler_use_cpu_execution_time', defined( 'PANTHEON_ENVIRONMENT' ) ) ) {
|
||||
$resource_usages = getrusage();
|
||||
|
||||
if ( isset( $resource_usages['ru_stime.tv_usec'], $resource_usages['ru_stime.tv_usec'] ) ) {
|
||||
$execution_time = $resource_usages['ru_stime.tv_sec'] + ( $resource_usages['ru_stime.tv_usec'] / 1000000 );
|
||||
}
|
||||
}
|
||||
|
||||
return $execution_time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the host's max execution time is (likely) to be exceeded if processing more actions.
|
||||
*
|
||||
* @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action
|
||||
* @return bool
|
||||
*/
|
||||
protected function time_likely_to_be_exceeded( $processed_actions ) {
|
||||
$execution_time = $this->get_execution_time();
|
||||
$max_execution_time = $this->get_time_limit();
|
||||
|
||||
// Safety against division by zero errors.
|
||||
if ( 0 === $processed_actions ) {
|
||||
return $execution_time >= $max_execution_time;
|
||||
}
|
||||
|
||||
$time_per_action = $execution_time / $processed_actions;
|
||||
$estimated_time = $execution_time + ( $time_per_action * 3 );
|
||||
$likely_to_be_exceeded = $estimated_time > $max_execution_time;
|
||||
|
||||
return apply_filters( 'action_scheduler_maximum_execution_time_likely_to_be_exceeded', $likely_to_be_exceeded, $this, $processed_actions, $execution_time, $max_execution_time );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get memory limit
|
||||
*
|
||||
* Based on WP_Background_Process::get_memory_limit()
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function get_memory_limit() {
|
||||
if ( function_exists( 'ini_get' ) ) {
|
||||
$memory_limit = ini_get( 'memory_limit' );
|
||||
} else {
|
||||
$memory_limit = '128M'; // Sensible default, and minimum required by WooCommerce
|
||||
}
|
||||
|
||||
if ( ! $memory_limit || -1 === $memory_limit || '-1' === $memory_limit ) {
|
||||
// Unlimited, set to 32GB.
|
||||
$memory_limit = '32G';
|
||||
}
|
||||
|
||||
return ActionScheduler_Compatibility::convert_hr_to_bytes( $memory_limit );
|
||||
}
|
||||
|
||||
/**
|
||||
* Memory exceeded
|
||||
*
|
||||
* Ensures the batch process never exceeds 90% of the maximum WordPress memory.
|
||||
*
|
||||
* Based on WP_Background_Process::memory_exceeded()
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function memory_exceeded() {
|
||||
|
||||
$memory_limit = $this->get_memory_limit() * 0.90;
|
||||
$current_memory = memory_get_usage( true );
|
||||
$memory_exceeded = $current_memory >= $memory_limit;
|
||||
|
||||
return apply_filters( 'action_scheduler_memory_exceeded', $memory_exceeded, $this );
|
||||
}
|
||||
|
||||
/**
|
||||
* See if the batch limits have been exceeded, which is when memory usage is almost at
|
||||
* the maximum limit, or the time to process more actions will exceed the max time limit.
|
||||
*
|
||||
* Based on WC_Background_Process::batch_limits_exceeded()
|
||||
*
|
||||
* @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action
|
||||
* @return bool
|
||||
*/
|
||||
protected function batch_limits_exceeded( $processed_actions ) {
|
||||
return $this->memory_exceeded() || $this->time_likely_to_be_exceeded( $processed_actions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process actions in the queue.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
* @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.
|
||||
*/
|
||||
abstract public function run( $context = '' );
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user