From 82f189a23e50f89b373775356f12583580f8ddc1 Mon Sep 17 00:00:00 2001 From: Alessio Torrisi Date: Mon, 10 Mar 2025 09:30:37 +0100 Subject: [PATCH 01/14] First steps on cache section refactoring --- bootstrap.php | 4 +- includes/BurstSafetyMode/init.php | 8 +- includes/Cache/Cache.php | 64 +++++++++++ includes/{ => Cache}/CacheExclusion.php | 2 +- includes/Cache/CacheFeatureHooks.php | 100 ++++++++++++++++++ includes/{ => Cache}/CacheManager.php | 4 +- includes/{ => Cache}/CachePurgingService.php | 5 +- includes/{ => Cache}/CacheTypes/Browser.php | 6 +- includes/{ => Cache}/CacheTypes/CacheBase.php | 2 +- .../{ => Cache}/CacheTypes/Cloudflare.php | 4 +- includes/{ => Cache}/CacheTypes/File.php | 9 +- includes/{ => Cache}/CacheTypes/Nginx.php | 4 +- includes/{ => Cache}/CacheTypes/Sitelock.php | 4 +- includes/{ => Cache}/CacheTypes/Skip404.php | 2 +- .../WPCLI/CacheTypesCommandHandler.php | 8 +- includes/{Concerns => Cache}/Purgeable.php | 2 +- .../{ => Cache}/ResponseHeaderManager.php | 2 +- includes/Performance.php | 65 ++---------- includes/PerformanceFeatureHooks.php | 69 ------------ includes/PerformanceWPCLI.php | 2 +- includes/RestApi/CacheExclusionController.php | 2 +- includes/RestApi/SettingsController.php | 2 +- includes/burstSafetyModeFunctions.php | 6 +- includes/functions.php | 3 +- 24 files changed, 216 insertions(+), 163 deletions(-) create mode 100644 includes/Cache/Cache.php rename includes/{ => Cache}/CacheExclusion.php (95%) create mode 100644 includes/Cache/CacheFeatureHooks.php rename includes/{ => Cache}/CacheManager.php (95%) rename includes/{ => Cache}/CachePurgingService.php (97%) rename includes/{ => Cache}/CacheTypes/Browser.php (96%) rename includes/{ => Cache}/CacheTypes/CacheBase.php (94%) rename includes/{ => Cache}/CacheTypes/Cloudflare.php (95%) rename includes/{ => Cache}/CacheTypes/File.php (97%) rename includes/{ => Cache}/CacheTypes/Nginx.php (93%) rename includes/{ => Cache}/CacheTypes/Sitelock.php (94%) rename includes/{ => Cache}/CacheTypes/Skip404.php (97%) rename includes/{ => Cache}/CacheTypes/WPCLI/CacheTypesCommandHandler.php (93%) rename includes/{Concerns => Cache}/Purgeable.php (86%) rename includes/{ => Cache}/ResponseHeaderManager.php (97%) delete mode 100644 includes/PerformanceFeatureHooks.php diff --git a/bootstrap.php b/bootstrap.php index f5bfb9c8..1d944194 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -2,6 +2,8 @@ namespace NewfoldLabs\WP\Module\Performance; +use NewfoldLabs\WP\Module\Performance\Cache\CacheFeatureHooks; + if ( function_exists( 'add_filter' ) ) { add_filter( 'newfold/features/filter/register', @@ -11,6 +13,6 @@ function ( $features ) { ); } -new PerformanceFeatureHooks(); +new CacheFeatureHooks(); require_once __DIR__ . '/includes/BurstSafetyMode/init.php'; diff --git a/includes/BurstSafetyMode/init.php b/includes/BurstSafetyMode/init.php index 2447e2e1..1c574f95 100644 --- a/includes/BurstSafetyMode/init.php +++ b/includes/BurstSafetyMode/init.php @@ -2,16 +2,16 @@ use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Skip404 as BurstSkip404; use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Browser as BurstBrowser; -use NewfoldLabs\WP\Module\Performance\CacheTypes\Browser as CacheBrowser; -use NewfoldLabs\WP\Module\Performance\CacheTypes\Skip404 as CacheSkip404; -use NewfoldLabs\WP\Module\Performance\ResponseHeaderManager; +use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\Browser as CacheBrowser; +use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\Skip404 as CacheSkip404; +use NewfoldLabs\WP\Module\Performance\Cache\ResponseHeaderManager; $newfold_burst_safety_mode = function_exists( 'get_option' ) ? (bool) get_option( 'newfold_burst_safety_mode', false ) : false; $newfold_cache_level = function_exists( 'newfold_cache_level' ) ? (int) get_option( 'newfold_cache_level', 0 ) : 0; // Check if Performance feature is enabled and it's necessary reset the cache options -if ( class_exists( 'NewfoldLabs\WP\Module\Performance\PerformanceFeatureHooks' ) ) { +if ( class_exists( 'NewfoldLabs\WP\Module\Performance\Cache\PerformanceFeatureHooks' ) ) { if ( $newfold_burst_safety_mode ) { $browser = new CacheBrowser(); $browser::maybeAddRules( $newfold_cache_level ); diff --git a/includes/Cache/Cache.php b/includes/Cache/Cache.php new file mode 100644 index 00000000..e5914af8 --- /dev/null +++ b/includes/Cache/Cache.php @@ -0,0 +1,64 @@ +container = $container; + + $cacheManager = new CacheManager( $container ); + $cachePurger = new CachePurgingService( $cacheManager->getInstances() ); + + $container->set( 'cachePurger', $cachePurger ); + + new CacheExclusion( $container ); + + $container->set( 'hasMustUsePlugin', file_exists( WPMU_PLUGIN_DIR . '/endurance-page-cache.php' ) ); + + $this->hooks(); + + add_action( 'plugins_loaded', array( $this, 'hooks2' ) ); + + } + + /** + * Add hooks. + */ + public function hooks() { + + add_action( 'after_mod_rewrite_rules', array( $this, 'onRewrite' ) ); + + add_action( 'newfold_container_set', array( $this, 'pluginHooks' ) ); + add_action( 'plugins_loaded', array( $this, 'hooks' ) ); + + add_action( 'newfold_container_set', array( $this, 'pluginHooks' ) ); + } + + /** + * When updating mod rewrite rules, also update our rewrites as appropriate. + */ + public function onRewrite() { + $this->onCacheLevelChange( getCacheLevel() ); + } + +} diff --git a/includes/CacheExclusion.php b/includes/Cache/CacheExclusion.php similarity index 95% rename from includes/CacheExclusion.php rename to includes/Cache/CacheExclusion.php index 39d89778..b5948738 100644 --- a/includes/CacheExclusion.php +++ b/includes/Cache/CacheExclusion.php @@ -1,5 +1,5 @@ container = $container; + register_activation_hook( $container->plugin()->file, array( $this, 'onActivation' ) ); + register_deactivation_hook( $container->plugin()->file, array( $this, 'onDeactivation' ) ); + } + + /** + * Add hooks. + */ + public function hooks() { + add_action( 'newfold/features/action/onEnable:performance', array( $this, 'onActivation' ) ); + add_action( 'newfold/features/action/onDisable:performance', array( $this, 'onDeactivation' ) ); + } + + /** + * Activation hook to perform when plugin is activated or feature is enabled + */ + public function onActivation() { + Skip404::onActivation(); + File::onActivation(); + Browser::onActivation(); + // Add headers to .htaccess + $responseHeaderManager = new ResponseHeaderManager(); + $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( getCacheLevel() ) ); + } + + /** + * Deactivation hook to perform when plugin is deactivated or feature is disabled + */ + public function onDeactivation() { + Skip404::onDeactivation(); + File::onDeactivation(); + Browser::onDeactivation(); + // Remove all headers from .htaccess + $responseHeaderManager = new ResponseHeaderManager(); + $responseHeaderManager->removeAllHeaders(); + } + + /** + * On cache level change, update the response headers. + * + * @param int|null $cacheLevel The cache level. + */ + public function onCacheLevelChange( $cacheLevel ) { + /** + * Respone Header Manager from container + * + * @var ResponseHeaderManager $responseHeaderManager + */ + $responseHeaderManager = $this->container->get( 'responseHeaderManager' ); + $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( $cacheLevel ) ); + + // Remove the old option from EPC, if it exists. + if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'endurance_cache_level', 0 ) ) ) { + update_option( 'endurance_cache_level', 0 ); + delete_option( 'endurance_cache_level' ); + } + } +} diff --git a/includes/CacheManager.php b/includes/Cache/CacheManager.php similarity index 95% rename from includes/CacheManager.php rename to includes/Cache/CacheManager.php index def88723..b4b9aaed 100644 --- a/includes/CacheManager.php +++ b/includes/Cache/CacheManager.php @@ -1,8 +1,8 @@ container = $container; $this->configureContainer( $container ); - $this->hooks( $container ); + $this->hooks(); - $cacheManager = new CacheManager( $container ); - $cachePurger = new CachePurgingService( $cacheManager->getInstances() ); + new Cache( $container ); new PerformanceWPCLI(); new Constants( $container ); new ImageManager( $container ); new HealthChecks( $container ); new LinkPrefetch( $container ); - new CacheExclusion( $container ); + add_action( 'admin_bar_menu', array( $this, 'adminBarMenu' ), 100 ); add_action( 'admin_menu', array( $this, 'add_sub_menu_page' ) ); - $container->set( 'cachePurger', $cachePurger ); - - $container->set( 'hasMustUsePlugin', file_exists( WPMU_PLUGIN_DIR . '/endurance-page-cache.php' ) ); - if ( Permissions::is_authorized_admin() || Permissions::rest_is_authorized_admin() ) { new RestAPI(); } @@ -92,6 +78,7 @@ public function __construct( Container $container ) { ! defined( 'NFD_PERFORMANCE_PLUGIN_LANGUAGES_DIR' ) && define( 'NFD_PERFORMANCE_PLUGIN_LANGUAGES_DIR', dirname( $container->plugin()->file ) . '/vendor/newfold-labs/wp-module-performance/languages' ); new I18nService( $container ); + } /** @@ -101,8 +88,6 @@ public function __construct( Container $container ) { */ public function configureContainer( Container $container ) { - $is_apache = false; - // Ensure $is_apache is properly set, with a fallback for WP-CLI environment if ( NFD_WPCLI::is_executing_wp_cli() ) { // Attempt to detect Apache based on the SERVER_SOFTWARE header @@ -112,7 +97,9 @@ public function configureContainer( Container $container ) { if ( ! $is_apache && file_exists( ABSPATH . '.htaccess' ) ) { $is_apache = true; } - } + }else{ + global $is_apache; + } $container->set( 'isApache', $is_apache ); @@ -133,8 +120,6 @@ public function hooks() { add_action( 'admin_init', array( $this, 'remove_epc_settings' ), 99 ); - new OptionListener( CacheManager::OPTION_CACHE_LEVEL, array( $this, 'onCacheLevelChange' ) ); - /** * On CLI requests, mod_rewrite is unavailable, so it fails to update * the .htaccess file when save_mod_rewrite_rules() is called. This @@ -158,12 +143,11 @@ function () { } ); - add_action( 'after_mod_rewrite_rules', array( $this, 'onRewrite' ) ); add_filter( 'action_scheduler_retention_period', array( $this, 'nfd_asr_default' ) ); add_filter( 'action_scheduler_cleanup_batch_size', array( $this, 'nfd_as_cleanup_batch_size' ) ); } - /** + /** * Remove EPC Settings if needed * * @return void @@ -216,33 +200,6 @@ public function nfd_as_cleanup_batch_size( $batch_size ) { return 1000; } - /** - * When updating mod rewrite rules, also update our rewrites as appropriate. - */ - public function onRewrite() { - $this->onCacheLevelChange( getCacheLevel() ); - } - - /** - * On cache level change, update the response headers. - * - * @param int|null $cacheLevel The cache level. - */ - public function onCacheLevelChange( $cacheLevel ) { - /** - * Respone Header Manager from container - * - * @var ResponseHeaderManager $responseHeaderManager - */ - $responseHeaderManager = $this->container->get( 'responseHeaderManager' ); - $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( $cacheLevel ) ); - - // Remove the old option from EPC, if it exists. - if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'endurance_cache_level', 0 ) ) ) { - update_option( 'endurance_cache_level', 0 ); - delete_option( 'endurance_cache_level' ); - } - } /** * Add options to the WordPress admin bar. diff --git a/includes/PerformanceFeatureHooks.php b/includes/PerformanceFeatureHooks.php deleted file mode 100644 index 0b6ef42a..00000000 --- a/includes/PerformanceFeatureHooks.php +++ /dev/null @@ -1,69 +0,0 @@ -plugin()->file, array( $this, 'onActivation' ) ); - register_deactivation_hook( $container->plugin()->file, array( $this, 'onDeactivation' ) ); - } - - /** - * Add hooks. - */ - public function hooks() { - add_action( 'newfold/features/action/onEnable:performance', array( $this, 'onActivation' ) ); - add_action( 'newfold/features/action/onDisable:performance', array( $this, 'onDeactivation' ) ); - } - - /** - * Activation hook to perform when plugin is activated or feature is enabled - */ - public function onActivation() { - Skip404::onActivation(); - File::onActivation(); - Browser::onActivation(); - // Add headers to .htaccess - $responseHeaderManager = new ResponseHeaderManager(); - $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( getCacheLevel() ) ); - } - - /** - * Deactivation hook to perform when plugin is deactivated or feature is disabled - */ - public function onDeactivation() { - Skip404::onDeactivation(); - File::onDeactivation(); - Browser::onDeactivation(); - // Remove all headers from .htaccess - $responseHeaderManager = new ResponseHeaderManager(); - $responseHeaderManager->removeAllHeaders(); - } -} diff --git a/includes/PerformanceWPCLI.php b/includes/PerformanceWPCLI.php index c0bac56d..5f7896a8 100644 --- a/includes/PerformanceWPCLI.php +++ b/includes/PerformanceWPCLI.php @@ -4,7 +4,7 @@ use NewfoldLabs\WP\Module\Performance\Images\WPCLI\ImageCommandHandler; use NewfoldLabs\WP\Module\Performance\LinkPrefetch\WPCLI\LinkPrefetchCommandHandler; -use NewfoldLabs\WP\Module\Performance\CacheTypes\WPCLI\CacheTypesCommandHandler; +use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\WPCLI\CacheTypesCommandHandler; /** * Manages all "wp nfd performance" WP-CLI commands. diff --git a/includes/RestApi/CacheExclusionController.php b/includes/RestApi/CacheExclusionController.php index ce056f40..493e24be 100644 --- a/includes/RestApi/CacheExclusionController.php +++ b/includes/RestApi/CacheExclusionController.php @@ -3,7 +3,7 @@ namespace NewfoldLabs\WP\Module\Performance\RestApi; use NewfoldLabs\WP\Module\ECommerce\Permissions; -use NewfoldLabs\WP\Module\Performance\CacheExclusion; +use NewfoldLabs\WP\Module\Performance\Cache\CacheExclusion; use function NewfoldLabs\WP\Module\Performance\get_default_cache_exclusions; diff --git a/includes/RestApi/SettingsController.php b/includes/RestApi/SettingsController.php index d082f993..56c4eeba 100644 --- a/includes/RestApi/SettingsController.php +++ b/includes/RestApi/SettingsController.php @@ -1,7 +1,7 @@ Date: Mon, 10 Mar 2025 10:49:29 +0100 Subject: [PATCH 02/14] Tweak: renamed folder "CacheTypes" to "Types" to avoid redundancy --- includes/BurstSafetyMode/init.php | 4 ++-- includes/Cache/Cache.php | 21 +++++++++++++++++++++ includes/Cache/CacheFeatureHooks.php | 6 +++--- includes/Cache/CacheManager.php | 14 +++++++------- includes/Cache/CachePurgingService.php | 2 +- includes/PerformanceWPCLI.php | 2 +- includes/RestApi/SettingsController.php | 2 +- includes/burstSafetyModeFunctions.php | 4 ++-- includes/functions.php | 2 +- 9 files changed, 39 insertions(+), 18 deletions(-) diff --git a/includes/BurstSafetyMode/init.php b/includes/BurstSafetyMode/init.php index 1c574f95..ff21f15f 100644 --- a/includes/BurstSafetyMode/init.php +++ b/includes/BurstSafetyMode/init.php @@ -2,8 +2,8 @@ use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Skip404 as BurstSkip404; use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Browser as BurstBrowser; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\Browser as CacheBrowser; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\Skip404 as CacheSkip404; +use NewfoldLabs\WP\Module\Performance\Cache\Types\Browser as CacheBrowser; +use NewfoldLabs\WP\Module\Performance\Cache\Types\Skip404 as CacheSkip404; use NewfoldLabs\WP\Module\Performance\Cache\ResponseHeaderManager; diff --git a/includes/Cache/Cache.php b/includes/Cache/Cache.php index e5914af8..7d284887 100644 --- a/includes/Cache/Cache.php +++ b/includes/Cache/Cache.php @@ -61,4 +61,25 @@ public function onRewrite() { $this->onCacheLevelChange( getCacheLevel() ); } + /** + * On cache level change, update the response headers. + * + * @param int|null $cacheLevel The cache level. + */ + public function onCacheLevelChange( $cacheLevel ) { + /** + * Respone Header Manager from container + * + * @var ResponseHeaderManager $responseHeaderManager + */ + $responseHeaderManager = $this->container->get( 'responseHeaderManager' ); + $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( $cacheLevel ) ); + + // Remove the old option from EPC, if it exists. + if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'endurance_cache_level', 0 ) ) ) { + update_option( 'endurance_cache_level', 0 ); + delete_option( 'endurance_cache_level' ); + } + } + } diff --git a/includes/Cache/CacheFeatureHooks.php b/includes/Cache/CacheFeatureHooks.php index 3b441cae..a019ee79 100644 --- a/includes/Cache/CacheFeatureHooks.php +++ b/includes/Cache/CacheFeatureHooks.php @@ -4,9 +4,9 @@ use NewfoldLabs\WP\ModuleLoader\Container; use NewfoldLabs\WP\Module\Performance\OptionListener; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\Browser; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\File; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\Skip404; +use NewfoldLabs\WP\Module\Performance\Cache\Types\Browser; +use NewfoldLabs\WP\Module\Performance\Cache\Types\File; +use NewfoldLabs\WP\Module\Performance\Cache\Types\Skip404; use function NewfoldLabs\WP\Module\Performance\getCacheLevel; diff --git a/includes/Cache/CacheManager.php b/includes/Cache/CacheManager.php index b4b9aaed..b32cabc5 100644 --- a/includes/Cache/CacheManager.php +++ b/includes/Cache/CacheManager.php @@ -2,7 +2,7 @@ namespace NewfoldLabs\WP\Module\Performance\Cache; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\CacheBase; +use NewfoldLabs\WP\Module\Performance\Cache\Types\CacheBase; use NewfoldLabs\WP\ModuleLoader\Container; use WP_Forge\Collection\Collection; @@ -48,12 +48,12 @@ public function __construct( Container $container ) { */ protected function classMap() { return array( - 'browser' => __NAMESPACE__ . '\\CacheTypes\\Browser', - 'cloudflare' => __NAMESPACE__ . '\\CacheTypes\\Cloudflare', - 'file' => __NAMESPACE__ . '\\CacheTypes\\File', - 'nginx' => __NAMESPACE__ . '\\CacheTypes\\Nginx', - 'sitelock' => __NAMESPACE__ . '\\CacheTypes\\Sitelock', - 'skip404' => __NAMESPACE__ . '\\CacheTypes\\Skip404', + 'browser' => __NAMESPACE__ . '\\Types\\Browser', + 'cloudflare' => __NAMESPACE__ . '\\Types\\Cloudflare', + 'file' => __NAMESPACE__ . '\\Types\\File', + 'nginx' => __NAMESPACE__ . '\\Types\\Nginx', + 'sitelock' => __NAMESPACE__ . '\\Types\\Sitelock', + 'skip404' => __NAMESPACE__ . '\\Types\\Skip404', ); } diff --git a/includes/Cache/CachePurgingService.php b/includes/Cache/CachePurgingService.php index 620938c7..9d8a332c 100644 --- a/includes/Cache/CachePurgingService.php +++ b/includes/Cache/CachePurgingService.php @@ -2,7 +2,7 @@ namespace NewfoldLabs\WP\Module\Performance\Cache; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\CacheBase; +use NewfoldLabs\WP\Module\Performance\Cache\Types\CacheBase; use wpscholar\Url; /** diff --git a/includes/PerformanceWPCLI.php b/includes/PerformanceWPCLI.php index 5f7896a8..402e4d00 100644 --- a/includes/PerformanceWPCLI.php +++ b/includes/PerformanceWPCLI.php @@ -4,7 +4,7 @@ use NewfoldLabs\WP\Module\Performance\Images\WPCLI\ImageCommandHandler; use NewfoldLabs\WP\Module\Performance\LinkPrefetch\WPCLI\LinkPrefetchCommandHandler; -use NewfoldLabs\WP\Module\Performance\Cache\CacheTypes\WPCLI\CacheTypesCommandHandler; +use NewfoldLabs\WP\Module\Performance\Cache\Types\WPCLI\CacheTypesCommandHandler; /** * Manages all "wp nfd performance" WP-CLI commands. diff --git a/includes/RestApi/SettingsController.php b/includes/RestApi/SettingsController.php index 56c4eeba..110ed9f9 100644 --- a/includes/RestApi/SettingsController.php +++ b/includes/RestApi/SettingsController.php @@ -1,7 +1,7 @@ Date: Mon, 10 Mar 2025 12:28:10 +0100 Subject: [PATCH 03/14] Tweak: use WP FILESYSTEM for operation on files Fix: phpcs issues with naming standard --- includes/BurstSafetyMode/Browser.php | 2 +- .../BurstSafetyMode/ResponseHeaderManager.php | 28 ++-- includes/BurstSafetyMode/init.php | 4 +- includes/Cache/Cache.php | 142 ++++++++-------- includes/Cache/CacheFeatureHooks.php | 151 +++++++++--------- includes/Cache/CacheManager.php | 12 +- includes/Cache/CachePurgingService.php | 92 ++++++----- includes/Cache/Purgeable.php | 4 +- includes/Cache/ResponseHeaderManager.php | 26 +-- .../Cache/{CacheTypes => Types}/Browser.php | 20 +-- .../Cache/{CacheTypes => Types}/CacheBase.php | 4 +- .../{CacheTypes => Types}/Cloudflare.php | 8 +- includes/Cache/{CacheTypes => Types}/File.php | 55 ++++--- .../Cache/{CacheTypes => Types}/Nginx.php | 6 +- .../Cache/{CacheTypes => Types}/Sitelock.php | 8 +- .../Cache/{CacheTypes => Types}/Skip404.php | 14 +- .../WPCLI/CacheTypesCommandHandler.php | 4 +- includes/Performance.php | 25 ++- includes/burstSafetyModeFunctions.php | 8 +- includes/functions.php | 96 ++++------- 20 files changed, 338 insertions(+), 371 deletions(-) rename includes/Cache/{CacheTypes => Types}/Browser.php (90%) rename includes/Cache/{CacheTypes => Types}/CacheBase.php (81%) rename includes/Cache/{CacheTypes => Types}/Cloudflare.php (94%) rename includes/Cache/{CacheTypes => Types}/File.php (85%) rename includes/Cache/{CacheTypes => Types}/Nginx.php (92%) rename includes/Cache/{CacheTypes => Types}/Sitelock.php (91%) rename includes/Cache/{CacheTypes => Types}/Skip404.php (88%) rename includes/Cache/{CacheTypes => Types}/WPCLI/CacheTypesCommandHandler.php (96%) diff --git a/includes/BurstSafetyMode/Browser.php b/includes/BurstSafetyMode/Browser.php index ecf1c1f5..ab23a494 100644 --- a/includes/BurstSafetyMode/Browser.php +++ b/includes/BurstSafetyMode/Browser.php @@ -20,7 +20,7 @@ class Browser { */ public function __construct() { $responseHeaderManager = new ResponseHeaderManager(); - $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', BURST_SAFETY_CACHE_LEVEL ); + $responseHeaderManager->add_header( 'X-Newfold-Cache-Level', BURST_SAFETY_CACHE_LEVEL ); $this->addRules(); } diff --git a/includes/BurstSafetyMode/ResponseHeaderManager.php b/includes/BurstSafetyMode/ResponseHeaderManager.php index 1ca05095..be07ba46 100644 --- a/includes/BurstSafetyMode/ResponseHeaderManager.php +++ b/includes/BurstSafetyMode/ResponseHeaderManager.php @@ -36,7 +36,7 @@ public function __construct() { * * @return array */ - public function parseHeaders() { + public function parse_headers() { $headers = array(); @@ -63,10 +63,10 @@ public function parseHeaders() { * @param string $name Header name * @param string $value Header value */ - public function addHeader( string $name, string $value ) { - $this->setHeaders( + public function add_header( string $name, string $value ) { + $this->set_headers( array_merge( - $this->parseHeaders(), + $this->parse_headers(), array( $name => $value ) ) ); @@ -77,9 +77,9 @@ public function addHeader( string $name, string $value ) { * * @param string[] $headers Headers to add. */ - public function addHeaders( array $headers ) { - $headers = array_merge( $this->parseHeaders(), $headers ); - $this->setHeaders( $headers ); + public function add_headers( array $headers ) { + $headers = array_merge( $this->parse_headers(), $headers ); + $this->set_headers( $headers ); } /** @@ -87,17 +87,17 @@ public function addHeaders( array $headers ) { * * @param string $name Header name */ - public function removeHeader( $name ) { - $headers = $this->parseHeaders(); + public function remove_header( $name ) { + $headers = $this->parse_headers(); unset( $headers[ $name ] ); - $this->setHeaders( $headers ); + $this->set_headers( $headers ); } /** * Remove all headers. */ - public function removeAllHeaders() { - $this->setHeaders( array() ); + public function remove_all_headers() { + $this->set_headers( array() ); } /** @@ -105,10 +105,10 @@ public function removeAllHeaders() { * * @param array $headers Headers to set. */ - public function setHeaders( array $headers ) { + public function set_headers( array $headers ) { if ( empty( $headers ) ) { - $this->htaccess->removeContent(); + $this->htaccess->remove_content(); return; } diff --git a/includes/BurstSafetyMode/init.php b/includes/BurstSafetyMode/init.php index ff21f15f..dbf98a66 100644 --- a/includes/BurstSafetyMode/init.php +++ b/includes/BurstSafetyMode/init.php @@ -24,11 +24,11 @@ } $response_header_manager = new ResponseHeaderManager(); - $response_header_manager->addHeader( 'X-Newfold-Cache-Level', $newfold_cache_level ); + $response_header_manager->add_header( 'X-Newfold-Cache-Level', $newfold_cache_level ); delete_option( 'newfold_burst_safety_mode' ); } -} elseif ( ! $newfold_burst_safety_mode ) { +} elseif ( ! $newfold_burst_safety_mode && defined( 'BLUEHOST_PLUGIN_DIR' ) ) { $files_to_include = array( 'htaccess' => BLUEHOST_PLUGIN_DIR . 'vendor/wp-forge/wp-htaccess-manager/includes/htaccess.php', 'htaccess_functions' => BLUEHOST_PLUGIN_DIR . 'vendor/wp-forge/wp-htaccess-manager/includes/functions.php', diff --git a/includes/Cache/Cache.php b/includes/Cache/Cache.php index 7d284887..9406ad02 100644 --- a/includes/Cache/Cache.php +++ b/includes/Cache/Cache.php @@ -4,82 +4,80 @@ use NewfoldLabs\WP\ModuleLoader\Container; -use function NewfoldLabs\WP\Module\Performance\getCacheLevel; +use function NewfoldLabs\WP\Module\Performance\get_cache_level; /** * Cache manager. */ class Cache { - /** - * Dependency injection container. - * - * @var Container - */ - protected $container; - - /** - * Constructor. - * - * @param Container $container the container - */ - public function __construct( Container $container ) { - $this->container = $container; - - $cacheManager = new CacheManager( $container ); - $cachePurger = new CachePurgingService( $cacheManager->getInstances() ); - - $container->set( 'cachePurger', $cachePurger ); - - new CacheExclusion( $container ); - - $container->set( 'hasMustUsePlugin', file_exists( WPMU_PLUGIN_DIR . '/endurance-page-cache.php' ) ); - - $this->hooks(); - - add_action( 'plugins_loaded', array( $this, 'hooks2' ) ); - - } - - /** - * Add hooks. - */ - public function hooks() { - - add_action( 'after_mod_rewrite_rules', array( $this, 'onRewrite' ) ); - - add_action( 'newfold_container_set', array( $this, 'pluginHooks' ) ); - add_action( 'plugins_loaded', array( $this, 'hooks' ) ); - - add_action( 'newfold_container_set', array( $this, 'pluginHooks' ) ); - } - - /** - * When updating mod rewrite rules, also update our rewrites as appropriate. - */ - public function onRewrite() { - $this->onCacheLevelChange( getCacheLevel() ); - } - - /** - * On cache level change, update the response headers. - * - * @param int|null $cacheLevel The cache level. - */ - public function onCacheLevelChange( $cacheLevel ) { - /** - * Respone Header Manager from container - * - * @var ResponseHeaderManager $responseHeaderManager - */ - $responseHeaderManager = $this->container->get( 'responseHeaderManager' ); - $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( $cacheLevel ) ); - - // Remove the old option from EPC, if it exists. - if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'endurance_cache_level', 0 ) ) ) { - update_option( 'endurance_cache_level', 0 ); - delete_option( 'endurance_cache_level' ); - } - } - + /** + * Dependency injection container. + * + * @var Container + */ + protected $container; + + /** + * Constructor. + * + * @param Container $container the container + */ + public function __construct( Container $container ) { + $this->container = $container; + + $cacheManager = new CacheManager( $container ); + $cachePurger = new CachePurgingService( $cacheManager->get_instances() ); + + $container->set( 'cachePurger', $cachePurger ); + + new CacheExclusion( $container ); + + $container->set( 'hasMustUsePlugin', file_exists( WPMU_PLUGIN_DIR . '/endurance-page-cache.php' ) ); + + $this->hooks(); + + add_action( 'plugins_loaded', array( $this, 'hooks2' ) ); + } + + /** + * Add hooks. + */ + public function hooks() { + + add_action( 'after_mod_rewrite_rules', array( $this, 'on_rewrite' ) ); + + add_action( 'newfold_container_set', array( $this, 'plugin_hooks' ) ); + add_action( 'plugins_loaded', array( $this, 'hooks' ) ); + + add_action( 'newfold_container_set', array( $this, 'plugin_hooks' ) ); + } + + /** + * When updating mod rewrite rules, also update our rewrites as appropriate. + */ + public function on_rewrite() { + $this->on_cache_level_change( get_cache_level() ); + } + + /** + * On cache level change, update the response headers. + * + * @param int|null $cacheLevel The cache level. + */ + public function on_cache_level_change( $cacheLevel ) { + /** + * Respone Header Manager from container + * + * @var ResponseHeaderManager $responseHeaderManager + */ + $responseHeaderManager = $this->container->get( 'responseHeaderManager' ); + $responseHeaderManager->add_header( 'X-Newfold-Cache-Level', absint( $cacheLevel ) ); + + // Remove the old option from EPC, if it exists. + if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'endurance_cache_level', 0 ) ) ) { + update_option( 'endurance_cache_level', 0 ); + delete_option( 'endurance_cache_level' ); + } + } } diff --git a/includes/Cache/CacheFeatureHooks.php b/includes/Cache/CacheFeatureHooks.php index a019ee79..c6160f00 100644 --- a/includes/Cache/CacheFeatureHooks.php +++ b/includes/Cache/CacheFeatureHooks.php @@ -8,93 +8,92 @@ use NewfoldLabs\WP\Module\Performance\Cache\Types\File; use NewfoldLabs\WP\Module\Performance\Cache\Types\Skip404; -use function NewfoldLabs\WP\Module\Performance\getCacheLevel; +use function NewfoldLabs\WP\Module\Performance\get_cache_level; /** * Add activation/deactivation hooks for the performance feature. **/ class CacheFeatureHooks { - /** - * Dependency injection container. - * - * @var Container - */ - protected $container; + /** + * Dependency injection container. + * + * @var Container + */ + protected $container; - /** - * Constructor. - */ - public function __construct() { - if ( function_exists( 'add_action' ) ) { - add_action( 'newfold_container_set', array( $this, 'pluginHooks' ) ); - add_action( 'plugins_loaded', array( $this, 'hooks' ) ); - } + /** + * Constructor. + */ + public function __construct() { + if ( function_exists( 'add_action' ) ) { + add_action( 'newfold_container_set', array( $this, 'plugin_hooks' ) ); + add_action( 'plugins_loaded', array( $this, 'hooks' ) ); + new OptionListener( CacheManager::OPTION_CACHE_LEVEL, array( $this, 'on_cache_level_change' ) ); + } + } - new OptionListener( CacheManager::OPTION_CACHE_LEVEL, array( $this, 'onCacheLevelChange' ) ); - } + /** + * Hooks for plugin activation/deactivation + * + * @param Container $container from the plugin + */ + public function plugin_hooks( Container $container ) { + $this->container = $container; + register_activation_hook( $container->plugin()->file, array( $this, 'on_activation' ) ); + register_deactivation_hook( $container->plugin()->file, array( $this, 'on_deactivation' ) ); + } - /** - * Hooks for plugin activation/deactivation - * - * @param Container $container from the plugin - */ - public function pluginHooks( Container $container ) { - $this->container = $container; - register_activation_hook( $container->plugin()->file, array( $this, 'onActivation' ) ); - register_deactivation_hook( $container->plugin()->file, array( $this, 'onDeactivation' ) ); - } + /** + * Add hooks. + */ + public function hooks() { + add_action( 'newfold/features/action/onEnable:performance', array( $this, 'on_activation' ) ); + add_action( 'newfold/features/action/onDisable:performance', array( $this, 'on_deactivation' ) ); + } - /** - * Add hooks. - */ - public function hooks() { - add_action( 'newfold/features/action/onEnable:performance', array( $this, 'onActivation' ) ); - add_action( 'newfold/features/action/onDisable:performance', array( $this, 'onDeactivation' ) ); - } + /** + * Activation hook to perform when plugin is activated or feature is enabled + */ + public function on_activation() { + Skip404::on_activation(); + File::on_activation(); + Browser::on_activation(); + // Add headers to .htaccess + $responseHeaderManager = new ResponseHeaderManager(); + $responseHeaderManager->add_header( 'X-Newfold-Cache-Level', absint( get_cache_level() ) ); + } - /** - * Activation hook to perform when plugin is activated or feature is enabled - */ - public function onActivation() { - Skip404::onActivation(); - File::onActivation(); - Browser::onActivation(); - // Add headers to .htaccess - $responseHeaderManager = new ResponseHeaderManager(); - $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( getCacheLevel() ) ); - } + /** + * Deactivation hook to perform when plugin is deactivated or feature is disabled + */ + public function on_deactivation() { + Skip404::on_deactivation(); + File::on_deactivation(); + Browser::on_deactivation(); + // Remove all headers from .htaccess + $responseHeaderManager = new ResponseHeaderManager(); + $responseHeaderManager->remove_all_headers(); + } - /** - * Deactivation hook to perform when plugin is deactivated or feature is disabled - */ - public function onDeactivation() { - Skip404::onDeactivation(); - File::onDeactivation(); - Browser::onDeactivation(); - // Remove all headers from .htaccess - $responseHeaderManager = new ResponseHeaderManager(); - $responseHeaderManager->removeAllHeaders(); - } + /** + * On cache level change, update the response headers. + * + * @param int|null $cacheLevel The cache level. + */ + public function on_cache_level_change( $cacheLevel ) { + /** + * Respone Header Manager from container + * + * @var ResponseHeaderManager $responseHeaderManager + */ + $responseHeaderManager = $this->container->get( 'responseHeaderManager' ); + $responseHeaderManager->add_header( 'X-Newfold-Cache-Level', absint( $cacheLevel ) ); - /** - * On cache level change, update the response headers. - * - * @param int|null $cacheLevel The cache level. - */ - public function onCacheLevelChange( $cacheLevel ) { - /** - * Respone Header Manager from container - * - * @var ResponseHeaderManager $responseHeaderManager - */ - $responseHeaderManager = $this->container->get( 'responseHeaderManager' ); - $responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', absint( $cacheLevel ) ); - - // Remove the old option from EPC, if it exists. - if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'endurance_cache_level', 0 ) ) ) { - update_option( 'endurance_cache_level', 0 ); - delete_option( 'endurance_cache_level' ); - } - } + // Remove the old option from EPC, if it exists. + if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'endurance_cache_level', 0 ) ) ) { + update_option( 'endurance_cache_level', 0 ); + delete_option( 'endurance_cache_level' ); + } + } } diff --git a/includes/Cache/CacheManager.php b/includes/Cache/CacheManager.php index b32cabc5..93d49c24 100644 --- a/includes/Cache/CacheManager.php +++ b/includes/Cache/CacheManager.php @@ -62,7 +62,7 @@ protected function classMap() { * * @return string[] */ - public function registeredCacheTypes() { + public function registered_cache_types() { return array_keys( $this->classMap() ); } @@ -71,7 +71,7 @@ public function registeredCacheTypes() { * * @return array */ - public function enabledCacheTypes() { + public function enabled_cache_types() { $default_cache_types = array( 'browser', 'skip404' ); if ( $this->container->has( 'cache_types' ) ) { @@ -81,7 +81,7 @@ public function enabledCacheTypes() { } return is_array( $provided_types ) - ? array_intersect( array_map( 'strtolower', $provided_types ), $this->registeredCacheTypes() ) + ? array_intersect( array_map( 'strtolower', $provided_types ), $this->registered_cache_types() ) : $default_cache_types; } @@ -91,17 +91,17 @@ public function enabledCacheTypes() { * * @return CacheBase[] An array of cache type instances. */ - public function getInstances() { + public function get_instances() { $instances = array(); $collection = new Collection( $this->classMap() ); - $map = $collection->only( $this->enabledCacheTypes() ); + $map = $collection->only( $this->enabled_cache_types() ); foreach ( $map as $type => $class ) { /** * CacheBase instance. * * @var CacheBase $class */ - if ( $class::shouldEnable( $this->container ) ) { + if ( $class::should_enable( $this->container ) ) { $instances[ $type ] = new $class(); $instances[ $type ]->setContainer( $this->container ); } diff --git a/includes/Cache/CachePurgingService.php b/includes/Cache/CachePurgingService.php index 9d8a332c..810865f2 100644 --- a/includes/Cache/CachePurgingService.php +++ b/includes/Cache/CachePurgingService.php @@ -2,41 +2,45 @@ namespace NewfoldLabs\WP\Module\Performance\Cache; +use NewfoldLabs\WP\Module\Performance\Performance; use NewfoldLabs\WP\Module\Performance\Cache\Types\CacheBase; use wpscholar\Url; +use function NewfoldLabs\WP\Module\Performance\to_studly_case; +use function NewfoldLabs\WP\Module\Performance\to_snake_case; + /** * Cache purging service. */ class CachePurgingService { /** - * Cache types. + * Define cache types. * - * @var CacheBase[] $cacheTypes Cache types. + * @var array|CacheBase[] $cache_types Cache types. */ - public $cacheTypes = array(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase + public $cache_types = array(); /** * Constructor. * - * @param CacheBase[] $cacheTypes Cache types. + * @param CacheBase[] $cache_types Cache types. */ - public function __construct( array $cacheTypes ) { + public function __construct( array $cache_types ) { - $this->cacheTypes = $cacheTypes; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + $this->cache_types = $cache_types; - if ( $this->canPurge() ) { + if ( $this->can_purge() ) { // Handle manual purge requests - add_action( 'init', array( $this, 'manualPurgeRequest' ) ); + add_action( 'init', array( $this, 'manual_purge_request' ) ); // Handle automatic purging - add_action( 'transition_post_status', array( $this, 'onSavePost' ), 10, 3 ); - add_action( 'edit_terms', array( $this, 'onEditTerm' ) ); - add_action( 'comment_post', array( $this, 'onUpdateComment' ) ); - add_action( 'updated_option', array( $this, 'onUpdateOption' ), 10, 3 ); - add_action( 'wp_update_nav_menu', array( $this, 'purgeAll' ) ); + add_action( 'transition_post_status', array( $this, 'on_save_post' ), 10, 3 ); + add_action( 'edit_terms', array( $this, 'on_edit_term' ) ); + add_action( 'comment_post', array( $this, 'on_update_comment' ) ); + add_action( 'updated_option', array( $this, 'on_update_option' ), 10, 3 ); + add_action( 'wp_update_nav_menu', array( $this, 'purge_all' ) ); } } @@ -46,8 +50,8 @@ public function __construct( array $cacheTypes ) { * * @return bool */ - public function canPurge() { - foreach ( $this->cacheTypes as $instance ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + public function can_purge() { + foreach ( $this->cache_types as $instance ) { if ( array_key_exists( Purgeable::class, class_implements( $instance ) ) ) { return true; } @@ -59,21 +63,21 @@ public function canPurge() { /** * Listens for purge actions and handles based on type. */ - public function manualPurgeRequest() { + public function manual_purge_request() { - $purgeAll = Performance::PURGE_ALL; - $purgeUrl = Performance::PURGE_URL; + $purge_all = Performance::PURGE_ALL; + $purge_url = Performance::PURGE_URL; - if ( ( isset( $_GET[ $purgeAll ] ) || isset( $_GET[ $purgeUrl ] ) ) && is_user_logged_in() && current_user_can( 'manage_options' ) ) { // phpcs:ignore WordPress.Security.NonceVerification + if ( ( isset( $_GET[ $purge_all ] ) || isset( $_GET[ $purge_url ] ) ) && is_user_logged_in() && current_user_can( 'manage_options' ) ) { // phpcs:ignore WordPress.Security.NonceVerification $url = new Url(); - $url->removeQueryVar( $purgeAll ); - $url->removeQueryVar( $purgeUrl ); + $url->removeQueryVar( $purge_all ); + $url->removeQueryVar( $purge_url ); - if ( isset( $_GET[ $purgeAll ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification - $this->purgeAll(); + if ( isset( $_GET[ $purge_all ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification + $this->purge_all(); } else { - $this->purgeUrl( Url::stripQueryString( $url ) ); + $this->purge_url( Url::stripQueryString( $url ) ); } wp_safe_redirect( $url, @@ -87,15 +91,15 @@ public function manualPurgeRequest() { /** * Purge everything. */ - public function purgeAll() { - foreach ( $this->cacheTypes as $instance ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + public function purge_all() { + foreach ( $this->cache_types as $instance ) { if ( array_key_exists( Purgeable::class, class_implements( $instance ) ) ) { /** * Purgeable instance. * * @var Purgeable $instance */ - $instance->purgeAll(); + $instance->purge_all(); } } } @@ -105,15 +109,15 @@ public function purgeAll() { * * @param string $url The URL to be purged. */ - public function purgeUrl( $url ) { - foreach ( $this->cacheTypes as $instance ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + public function purge_url( $url ) { + foreach ( $this->cache_types as $instance ) { if ( array_key_exists( Purgeable::class, class_implements( $instance ) ) ) { /** * Purgeable instance. * * @var Purgeable $instance */ - $instance->purgeUrl( $url ); + $instance->purge_url( $url ); } } } @@ -125,7 +129,7 @@ public function purgeUrl( $url ) { * @param string $newStatus The new post status * @param \WP_Post $post The post object of the edited or created post */ - public function onSavePost( $oldStatus, $newStatus, \WP_Post $post ) { + public function on_save_post( $oldStatus, $newStatus, \WP_Post $post ) { // Skip purging for non-public post types if ( ! get_post_type_object( $post->post_type )->public ) { @@ -140,18 +144,18 @@ public function onSavePost( $oldStatus, $newStatus, \WP_Post $post ) { // Purge post URL when post is updated. $permalink = get_permalink( $post ); if ( $permalink ) { - $this->purgeUrl( $permalink ); + $this->purge_url( $permalink ); } // Purge taxonomy term URLs for related terms. $taxonomies = get_post_taxonomies( $post ); foreach ( $taxonomies as $taxonomy ) { - if ( $this->isPublicTaxonomy( $taxonomy ) ) { + if ( $this->is_public_taxonomy( $taxonomy ) ) { $terms = get_the_terms( $post, $taxonomy ); if ( is_array( $terms ) ) { foreach ( $terms as $term ) { $term_link = get_term_link( $term ); - $this->purgeUrl( $term_link ); + $this->purge_url( $term_link ); } } } @@ -160,12 +164,12 @@ public function onSavePost( $oldStatus, $newStatus, \WP_Post $post ) { // Purge post type archive URL when post is updated. $post_type_archive = get_post_type_archive_link( $post->post_type ); if ( $post_type_archive ) { - $this->purgeUrl( $post_type_archive ); + $this->purge_url( $post_type_archive ); } // Purge date archive URL when post is updated. $year_archive = get_year_link( (int) get_the_date( 'y', $post ) ); - $this->purgeUrl( $year_archive ); + $this->purge_url( $year_archive ); } /** @@ -173,10 +177,10 @@ public function onSavePost( $oldStatus, $newStatus, \WP_Post $post ) { * * @param int $termId Term ID */ - public function onEditTerm( $termId ) { + public function on_edit_term( $termId ) { $url = get_term_link( $termId ); if ( ! is_wp_error( $url ) ) { - $this->purgeUrl( $url ); + $this->purge_url( $url ); } } @@ -185,12 +189,12 @@ public function onEditTerm( $termId ) { * * @param int $commentId ID of the comment. */ - public function onUpdateComment( $commentId ) { + public function on_update_comment( $commentId ) { $comment = get_comment( $commentId ); if ( $comment && property_exists( $comment, 'comment_post_ID' ) ) { $postUrl = get_permalink( $comment->comment_post_ID ); if ( $postUrl ) { - $this->purgeUrl( $postUrl ); + $this->purge_url( $postUrl ); } } } @@ -204,7 +208,7 @@ public function onUpdateComment( $commentId ) { * * @return bool */ - public function onUpdateOption( $option, $oldValue, $newValue ) { + public function on_update_option( $option, $oldValue, $newValue ) { // No need to process if nothing was updated if ( $oldValue === $newValue ) { return false; @@ -291,7 +295,7 @@ public function onUpdateOption( $option, $oldValue, $newValue ) { if ( ctype_upper( str_replace( array( '-', '_' ), '', $option ) ) ) { $option = strtolower( $option ); } - $option_name = '_' . toSnakeCase( toStudlyCase( $option ) ) . '_'; + $option_name = '_' . to_snake_case( to_studly_case( $option ) ) . '_'; foreach ( $forceIfContains as $slug ) { if ( false !== strpos( $option_name, $slug ) ) { @@ -308,7 +312,7 @@ public function onUpdateOption( $option, $oldValue, $newValue ) { } } - $this->purgeAll(); + $this->purge_all(); return true; } @@ -320,7 +324,7 @@ public function onUpdateOption( $option, $oldValue, $newValue ) { * * @return boolean */ - protected function isPublicTaxonomy( $taxonomy ) { + protected function is_public_taxonomy( $taxonomy ) { $public = false; $taxonomy_object = get_taxonomy( $taxonomy ); if ( $taxonomy_object && isset( $taxonomy_object->public ) ) { diff --git a/includes/Cache/Purgeable.php b/includes/Cache/Purgeable.php index f0fac709..d7ee8f05 100644 --- a/includes/Cache/Purgeable.php +++ b/includes/Cache/Purgeable.php @@ -12,7 +12,7 @@ interface Purgeable { * * @return void */ - public function purgeAll(); + public function purge_all(); /** * Purge a specific URL for the given cache type. @@ -21,5 +21,5 @@ public function purgeAll(); * * @return void */ - public function purgeUrl( $url ); + public function purge_url( $url ); } diff --git a/includes/Cache/ResponseHeaderManager.php b/includes/Cache/ResponseHeaderManager.php index 7f72ef86..bb9c19e1 100644 --- a/includes/Cache/ResponseHeaderManager.php +++ b/includes/Cache/ResponseHeaderManager.php @@ -37,7 +37,7 @@ public function __construct() { * * @return array */ - public function parseHeaders() { + public function parse_headers() { $headers = array(); @@ -64,10 +64,10 @@ public function parseHeaders() { * @param string $name Header name * @param string $value Header value */ - public function addHeader( string $name, string $value ) { - $this->setHeaders( + public function add_header( string $name, string $value ) { + $this->set_headers( array_merge( - $this->parseHeaders(), + $this->parse_headers(), array( $name => $value ) ) ); @@ -78,9 +78,9 @@ public function addHeader( string $name, string $value ) { * * @param string[] $headers Headers to add. */ - public function addHeaders( array $headers ) { - $headers = array_merge( $this->parseHeaders(), $headers ); - $this->setHeaders( $headers ); + public function add_headers( array $headers ) { + $headers = array_merge( $this->parse_headers(), $headers ); + $this->set_headers( $headers ); } /** @@ -88,17 +88,17 @@ public function addHeaders( array $headers ) { * * @param string $name Header name */ - public function removeHeader( $name ) { - $headers = $this->parseHeaders(); + public function remove_header( $name ) { + $headers = $this->parse_headers(); unset( $headers[ $name ] ); - $this->setHeaders( $headers ); + $this->set_headers( $headers ); } /** * Remove all headers. */ - public function removeAllHeaders() { - $this->setHeaders( array() ); + public function remove_all_headers() { + $this->set_headers( array() ); } /** @@ -106,7 +106,7 @@ public function removeAllHeaders() { * * @param array $headers Headers to set. */ - public function setHeaders( array $headers ) { + public function set_headers( array $headers ) { if ( empty( $headers ) ) { $this->htaccess->removeContent(); diff --git a/includes/Cache/CacheTypes/Browser.php b/includes/Cache/Types/Browser.php similarity index 90% rename from includes/Cache/CacheTypes/Browser.php rename to includes/Cache/Types/Browser.php index ad3c592a..2196bcfd 100644 --- a/includes/Cache/CacheTypes/Browser.php +++ b/includes/Cache/Types/Browser.php @@ -1,6 +1,6 @@ has( 'isApache' ) && $container->get( 'isApache' ); } @@ -42,21 +42,21 @@ public function __construct() { new OptionListener( CacheExclusion::OPTION_CACHE_EXCLUSION, array( __CLASS__, 'exclusionChange' ) ); - add_filter( 'newfold_update_htaccess', array( $this, 'onRewrite' ) ); + add_filter( 'newfold_update_htaccess', array( $this, 'on_rewrite' ) ); } /** * When updating .htaccess, also update our rules as appropriate. */ - public function onRewrite() { - self::maybeAddRules( getCacheLevel() ); + public function on_rewrite() { + self::maybeAddRules( get_cache_level() ); } /** * Manage on exlcusion option change. */ public static function exclusionChange() { - self::maybeAddRules( getCacheLevel() ); + self::maybeAddRules( get_cache_level() ); } /** @@ -183,14 +183,14 @@ protected static function getFileTypeExpirations( int $cacheLevel ) { /** * Handle activation logic. */ - public static function onActivation() { - self::maybeAddRules( getCacheLevel() ); + public static function on_activation() { + self::maybeAddRules( get_cache_level() ); } /** * Handle deactivation logic. */ - public static function onDeactivation() { + public static function on_deactivation() { self::removeRules(); } } diff --git a/includes/Cache/CacheTypes/CacheBase.php b/includes/Cache/Types/CacheBase.php similarity index 81% rename from includes/Cache/CacheTypes/CacheBase.php rename to includes/Cache/Types/CacheBase.php index 86abfb6b..f5632da6 100644 --- a/includes/Cache/CacheTypes/CacheBase.php +++ b/includes/Cache/Types/CacheBase.php @@ -1,6 +1,6 @@ isCoudflareEnabled() ) { $this->purgeRequest(); } @@ -66,7 +66,7 @@ public function purgeAll() { * * @param string $url URL to purge. */ - public function purgeUrl( $url ) { + public function purge_url( $url ) { if ( $this->isCoudflareEnabled() ) { $this->purgeRequest( array( $url ) ); } diff --git a/includes/Cache/CacheTypes/File.php b/includes/Cache/Types/File.php similarity index 85% rename from includes/Cache/CacheTypes/File.php rename to includes/Cache/Types/File.php index a7bba905..c7cdc4c7 100644 --- a/includes/Cache/CacheTypes/File.php +++ b/includes/Cache/Types/File.php @@ -1,6 +1,6 @@ has( 'isApache' ) && $container->get( 'isApache' ); } @@ -52,21 +52,21 @@ public function __construct() { new OptionListener( CacheExclusion::OPTION_CACHE_EXCLUSION, array( __CLASS__, 'exclusionChange' ) ); add_action( 'init', array( $this, 'maybeGeneratePageCache' ) ); - add_action( 'newfold_update_htaccess', array( $this, 'onRewrite' ) ); + add_action( 'newfold_update_htaccess', array( $this, 'on_rewrite' ) ); } /** * Manage on exlcusion option change. */ public static function exclusionChange() { - self::maybeAddRules( getCacheLevel() ); + self::maybeAddRules( get_cache_level() ); } /** * When updating mod rewrite rules, also update our rewrites as appropriate. */ - public function onRewrite() { - self::maybeAddRules( getCacheLevel() ); + public function on_rewrite() { + self::maybeAddRules( get_cache_level() ); } /** @@ -143,10 +143,19 @@ public function write( $content ) { $content .= "\n"; } - if ( ! is_dir( $path ) ) { - mkdir( $path, 0755, true ); + global $wp_filesystem; + + if ( ! function_exists( 'WP_Filesystem' ) ) { + require_once ABSPATH . 'wp-admin/includes/file.php'; } - file_put_contents( $file, $content, LOCK_EX ); // phpcs:ignore WordPress.WP.AlternativeFunctions + + WP_Filesystem(); + + if ( ! $wp_filesystem->is_dir( $path ) ) { + $wp_filesystem->mkdir( $path, 0755 ); + } + + $wp_filesystem->put_contents( $file, $content, FS_CHMOD_FILE ); } @@ -224,7 +233,7 @@ public function isCacheable() { public function shouldCache() { // If page caching is disabled, then don't cache - if ( ! shouldCachePages() ) { + if ( ! should_cache_pages() ) { return false; } @@ -265,7 +274,7 @@ protected function exclusions() { * @return int */ protected function getExpirationTimeframe() { - switch ( getCacheLevel() ) { + switch ( get_cache_level() ) { case 2: return 2 * HOUR_IN_SECONDS; case 3: @@ -278,8 +287,8 @@ protected function getExpirationTimeframe() { /** * Purge everything from the cache. */ - public function purgeAll() { - removeDirectory( self::CACHE_DIR ); + public function purge_all() { + remove_directory( self::CACHE_DIR ); } /** @@ -287,18 +296,18 @@ public function purgeAll() { * * @param string $url the url to purge. */ - public function purgeUrl( $url ) { + public function purge_url( $url ) { $path = $this->getStoragePathForRequest(); if ( trailingslashit( self::CACHE_DIR ) === $path ) { if ( file_exists( self::CACHE_DIR . '/_index.html' ) ) { - unlink( self::CACHE_DIR . '/_index.html' ); + wp_delete_file( self::CACHE_DIR . '/_index.html' ); } return; } - removeDirectory( $this->getStoragePathForRequest() ); + remove_directory( $this->getStoragePathForRequest() ); } /** @@ -330,19 +339,19 @@ protected function getStorageFileForRequest() { /** * Handle activation logic. */ - public static function onActivation() { - self::maybeAddRules( getCacheLevel() ); + public static function on_activation() { + self::maybeAddRules( get_cache_level() ); } /** * Handle deactivation logic. */ - public static function onDeactivation() { + public static function on_deactivation() { // Remove file cache rules from .htaccess self::removeRules(); // Remove all statically cached files - removeDirectory( self::CACHE_DIR ); + remove_directory( self::CACHE_DIR ); } } diff --git a/includes/Cache/CacheTypes/Nginx.php b/includes/Cache/Types/Nginx.php similarity index 92% rename from includes/Cache/CacheTypes/Nginx.php rename to includes/Cache/Types/Nginx.php index 4f1ae96c..9ec297bb 100644 --- a/includes/Cache/CacheTypes/Nginx.php +++ b/includes/Cache/Types/Nginx.php @@ -1,6 +1,6 @@ purgeRequest(); } @@ -22,7 +22,7 @@ public function purgeAll() { * * @param string $url The URL to purge. */ - public function purgeUrl( $url ) { + public function purge_url( $url ) { $this->purgeRequest( $url ); } diff --git a/includes/Cache/CacheTypes/Sitelock.php b/includes/Cache/Types/Sitelock.php similarity index 91% rename from includes/Cache/CacheTypes/Sitelock.php rename to includes/Cache/Types/Sitelock.php index d6b1c1d7..6fa1894d 100644 --- a/includes/Cache/CacheTypes/Sitelock.php +++ b/includes/Cache/Types/Sitelock.php @@ -1,6 +1,6 @@ has( 'isApache' ) && $container->get( 'isApache' ); } @@ -49,7 +49,7 @@ public function __construct() { * When updating .htaccess, also update our rules as appropriate. */ public function onUpdateHtaccess() { - self::maybeAddRules( getSkip404Option() ); + self::maybeAddRules( get_skip404_option() ); // Remove the old option from EPC, if it exists if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'epc_skip_404_handling', 0 ) ) ) { @@ -95,14 +95,14 @@ public static function removeRules() { /** * Handle activation logic. */ - public static function onActivation() { - self::maybeAddRules( getSkip404Option() ); + public static function on_activation() { + self::maybeAddRules( get_skip404_option() ); } /** * Handle deactivation logic. */ - public static function onDeactivation() { + public static function on_deactivation() { self::removeRules(); } } diff --git a/includes/Cache/CacheTypes/WPCLI/CacheTypesCommandHandler.php b/includes/Cache/Types/WPCLI/CacheTypesCommandHandler.php similarity index 96% rename from includes/Cache/CacheTypes/WPCLI/CacheTypesCommandHandler.php rename to includes/Cache/Types/WPCLI/CacheTypesCommandHandler.php index 2de2a0ec..d556b9d3 100644 --- a/includes/Cache/CacheTypes/WPCLI/CacheTypesCommandHandler.php +++ b/includes/Cache/Types/WPCLI/CacheTypesCommandHandler.php @@ -1,11 +1,11 @@ hooks(); - new Cache( $container ); + new Cache( $container ); new PerformanceWPCLI(); new Constants( $container ); new ImageManager( $container ); @@ -64,8 +61,7 @@ public function __construct( Container $container ) { new LinkPrefetch( $container ); - - add_action( 'admin_bar_menu', array( $this, 'adminBarMenu' ), 100 ); + add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu' ), 100 ); add_action( 'admin_menu', array( $this, 'add_sub_menu_page' ) ); if ( Permissions::is_authorized_admin() || Permissions::rest_is_authorized_admin() ) { @@ -78,7 +74,6 @@ public function __construct( Container $container ) { ! defined( 'NFD_PERFORMANCE_PLUGIN_LANGUAGES_DIR' ) && define( 'NFD_PERFORMANCE_PLUGIN_LANGUAGES_DIR', dirname( $container->plugin()->file ) . '/vendor/newfold-labs/wp-module-performance/languages' ); new I18nService( $container ); - } /** @@ -97,9 +92,9 @@ public function configureContainer( Container $container ) { if ( ! $is_apache && file_exists( ABSPATH . '.htaccess' ) ) { $is_apache = true; } - }else{ - global $is_apache; - } + } else { + global $is_apache; + } $container->set( 'isApache', $is_apache ); @@ -147,7 +142,7 @@ function () { add_filter( 'action_scheduler_cleanup_batch_size', array( $this, 'nfd_as_cleanup_batch_size' ) ); } - /** + /** * Remove EPC Settings if needed * * @return void @@ -206,7 +201,7 @@ public function nfd_as_cleanup_batch_size( $batch_size ) { * * @param \WP_Admin_Bar $wp_admin_bar the admin bar. */ - public function adminBarMenu( \WP_Admin_Bar $wp_admin_bar ) { + public function admin_bar_menu( \WP_Admin_Bar $wp_admin_bar ) { // If the EPC MU plugin exists, remove its cache clearing options. if ( $this->container->get( 'hasMustUsePlugin' ) ) { @@ -287,7 +282,7 @@ public function enqueue_styles() { public function add_to_runtime( $sdk ) { $values = array( 'jetpack_boost_is_active' => defined( 'JETPACK_BOOST_VERSION' ), - 'jetpack_boost_premium_is_active' => $this->isJetPackBoostActive(), + 'jetpack_boost_premium_is_active' => $this->is_jetpackboost_active(), 'jetpack_boost_critical_css' => get_option( 'jetpack_boost_status_critical-css' ), 'jetpack_boost_blocking_js' => get_option( 'jetpack_boost_status_render-blocking-js' ), 'jetpack_boost_minify_js' => get_option( 'jetpack_boost_status_minify-js', array() ), @@ -295,7 +290,7 @@ public function add_to_runtime( $sdk ) { 'jetpack_boost_minify_css' => get_option( 'jetpack_boost_status_minify-css', array() ), 'jetpack_boost_minify_css_excludes' => implode( ',', get_option( 'jetpack_boost_ds_minify_css_excludes', array( 'admin-bar', 'dashicons', 'elementor-app' ) ) ), 'install_token' => PluginInstaller::rest_get_plugin_install_hash(), - 'skip404' => getSkip404Option(), + 'skip404' => get_skip404_option(), ); return array_merge( $sdk, array( 'performance' => $values ) ); @@ -307,7 +302,7 @@ public function add_to_runtime( $sdk ) { * * @return boolean */ - public function isJetPackBoostActive() { + public function is_jetpackboost_active() { $exists = false; if ( class_exists( 'Automattic\Jetpack\Current_Plan' ) ) { $products = Current_Plan::get_products(); diff --git a/includes/burstSafetyModeFunctions.php b/includes/burstSafetyModeFunctions.php index 15e41e16..1e8bb0cc 100644 --- a/includes/burstSafetyModeFunctions.php +++ b/includes/burstSafetyModeFunctions.php @@ -17,23 +17,23 @@ update_option( 'newfold_burst_safety_mode_site_cache_level', $current_level ); $browser = new Browser(); $browser::maybeAddRules( 3 ); - if ( function_exists( 'getSkip404Option' ) && ! getSkip404Option() ) { + if ( function_exists( 'get_skip404_option' ) && ! get_skip404_option() ) { $skip404 = new Skip404(); $skip404::maybeAddRules( true ); } $response_header_manager = new ResponseHeaderManager(); - $response_header_manager->addHeader( 'X-Newfold-Cache-Level', 3 ); + $response_header_manager->add_header( 'X-Newfold-Cache-Level', 3 ); } } elseif ( $newfold_burst_safety_mode ) { $cache_level = get_option( 'newfold_burst_safety_mode_site_cache_level' ); $browser = new Browser(); $browser::maybeAddRules( $cache_level ); - if ( function_exists( 'getSkip404Option' ) && ! getSkip404Option() ) { + if ( function_exists( 'get_skip404_option' ) && ! get_skip404_option() ) { $skip404 = new Skip404(); $skip404::maybeAddRules( false ); } $response_header_manager = new ResponseHeaderManager(); - $response_header_manager->addHeader( 'X-Newfold-Cache-Level', $cache_level ); + $response_header_manager->add_header( 'X-Newfold-Cache-Level', $cache_level ); delete_option( 'newfold_burst_safety_mode' ); delete_option( 'newfold_burst_safety_mode_site_cache_level' ); } diff --git a/includes/functions.php b/includes/functions.php index e3ae3fa8..7ef49a6c 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -19,79 +19,26 @@ function get_default_cache_exclusions() { * * @return int Cache level. */ -function getCacheLevel() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid +function get_cache_level() { return absint( get_option( CacheManager::OPTION_CACHE_LEVEL, 2 ) ); } -/** - * Get available cache levels. - * - * @return string[] Cache levels. - */ -function getCacheLevels() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid - return array( - 0 => 'Off', // Disable caching. - 1 => 'Assets Only', // Cache assets only. - 2 => 'Normal', // Cache pages and assets for a shorter time range. - 3 => 'Advanced', // Cache pages and assets for a longer time range. - ); -} - -/** - * Output the cache level select field. - */ -function getCacheLevelDropdown() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid - - $cacheLevels = getCacheLevels(); - $currentCacheLevel = getCacheLevel(); - - $name = CacheManager::OPTION_CACHE_LEVEL; - $label = __( 'Cache Level', 'wp-module-performance' ); - ?> - - - - /> - 1; +function should_cache_pages() { + return get_cache_level() > 1; } /** @@ -99,8 +46,8 @@ function shouldCachePages() { // phpcs:ignore WordPress.NamingConventions.ValidF * * @return bool */ -function shouldCacheAssets() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid - return getCacheLevel() > 0; +function should_cache_assets() { + return get_cache_level() > 0; } /** @@ -108,15 +55,30 @@ function shouldCacheAssets() { // phpcs:ignore WordPress.NamingConventions.Valid * * @param string $path Path to the directory. */ -function removeDirectory( $path ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid - if ( ! is_dir( $path ) ) { +function remove_directory( $path ) { + global $wp_filesystem; + + if ( ! function_exists( 'WP_Filesystem' ) ) { + require_once ABSPATH . 'wp-admin/includes/file.php'; + } + WP_Filesystem(); + + if ( ! $wp_filesystem || ! $wp_filesystem->is_dir( $path ) ) { return; } - $files = glob( $path . '/*' ); - foreach ( $files as $file ) { - is_dir( $file ) ? removeDirectory( $file ) : wp_delete_file( $file ); + + $files = $wp_filesystem->dirlist( $path ); + + foreach ( $files as $file => $file_info ) { + $file_path = trailingslashit( $path ) . $file; + if ( 'f' === $file_info['type'] ) { + $wp_filesystem->delete( $file_path ); + } elseif ( 'd' === $file_info['type'] ) { + remove_directory( $file_path ); + } } - rmdir( $path ); + + $wp_filesystem->rmdir( $path ); } /** @@ -127,7 +89,7 @@ function removeDirectory( $path ) { // phpcs:ignore WordPress.NamingConventions. * * @return string */ -function toSnakeCase( string $value, string $delimiter = '_' ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid +function to_snake_case( string $value, string $delimiter = '_' ) { if ( ! ctype_lower( $value ) ) { $value = preg_replace( '/(\s+)/u', '', ucwords( $value ) ); $value = trim( mb_strtolower( preg_replace( '/([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)/u', '$1' . $delimiter, $value ), 'UTF-8' ), $delimiter ); @@ -143,7 +105,7 @@ function toSnakeCase( string $value, string $delimiter = '_' ) { // phpcs:ignore * * @return string */ -function toStudlyCase( $value ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid +function to_studly_case( $value ) { return str_replace( ' ', '', ucwords( str_replace( array( '-', '_' ), ' ', $value ) ) ); } From 22cda3f4eaf7e8ec6d38524b86f8dd0471d3c7c0 Mon Sep 17 00:00:00 2001 From: Alessio Torrisi Date: Mon, 10 Mar 2025 15:24:06 +0100 Subject: [PATCH 04/14] New: Skip404 is no longer a cache type but a separated feature --- includes/BurstSafetyMode/init.php | 6 +- includes/Cache/CacheFeatureHooks.php | 6 +- includes/Cache/CacheManager.php | 3 +- includes/Cache/Types/Skip404.php | 108 ------------ .../Types/WPCLI/CacheTypesCommandHandler.php | 4 +- includes/Performance.php | 3 +- includes/RestApi/SettingsController.php | 6 +- includes/Skip404/Skip404.php | 162 ++++++++++++++++++ includes/burstSafetyModeFunctions.php | 10 +- includes/functions.php | 4 +- 10 files changed, 182 insertions(+), 130 deletions(-) delete mode 100644 includes/Cache/Types/Skip404.php create mode 100644 includes/Skip404/Skip404.php diff --git a/includes/BurstSafetyMode/init.php b/includes/BurstSafetyMode/init.php index dbf98a66..96e60a75 100644 --- a/includes/BurstSafetyMode/init.php +++ b/includes/BurstSafetyMode/init.php @@ -3,7 +3,7 @@ use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Skip404 as BurstSkip404; use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Browser as BurstBrowser; use NewfoldLabs\WP\Module\Performance\Cache\Types\Browser as CacheBrowser; -use NewfoldLabs\WP\Module\Performance\Cache\Types\Skip404 as CacheSkip404; +use NewfoldLabs\WP\Module\Performance\Skip404\Skip404 as Skip404; use NewfoldLabs\WP\Module\Performance\Cache\ResponseHeaderManager; @@ -19,8 +19,8 @@ $skip_404_handling = (bool) get_option( 'newfold_skip_404_handling', true ); if ( ! $skip_404_handling ) { - $skip404 = new CacheSkip404(); - $skip404::maybeAddRules( false ); + $skip404 = new Skip404(); + $skip404::maybe_add_rules( false ); } $response_header_manager = new ResponseHeaderManager(); diff --git a/includes/Cache/CacheFeatureHooks.php b/includes/Cache/CacheFeatureHooks.php index c6160f00..8a5cec7e 100644 --- a/includes/Cache/CacheFeatureHooks.php +++ b/includes/Cache/CacheFeatureHooks.php @@ -6,7 +6,7 @@ use NewfoldLabs\WP\Module\Performance\OptionListener; use NewfoldLabs\WP\Module\Performance\Cache\Types\Browser; use NewfoldLabs\WP\Module\Performance\Cache\Types\File; -use NewfoldLabs\WP\Module\Performance\Cache\Types\Skip404; +use NewfoldLabs\WP\Module\Performance\Skip404\Skip404; use function NewfoldLabs\WP\Module\Performance\get_cache_level; @@ -56,7 +56,7 @@ public function hooks() { * Activation hook to perform when plugin is activated or feature is enabled */ public function on_activation() { - Skip404::on_activation(); + //Skip404::on_activation(); File::on_activation(); Browser::on_activation(); // Add headers to .htaccess @@ -68,7 +68,7 @@ public function on_activation() { * Deactivation hook to perform when plugin is deactivated or feature is disabled */ public function on_deactivation() { - Skip404::on_deactivation(); + //Skip404::on_deactivation(); File::on_deactivation(); Browser::on_deactivation(); // Remove all headers from .htaccess diff --git a/includes/Cache/CacheManager.php b/includes/Cache/CacheManager.php index 93d49c24..f0f387db 100644 --- a/includes/Cache/CacheManager.php +++ b/includes/Cache/CacheManager.php @@ -53,7 +53,6 @@ protected function classMap() { 'file' => __NAMESPACE__ . '\\Types\\File', 'nginx' => __NAMESPACE__ . '\\Types\\Nginx', 'sitelock' => __NAMESPACE__ . '\\Types\\Sitelock', - 'skip404' => __NAMESPACE__ . '\\Types\\Skip404', ); } @@ -72,7 +71,7 @@ public function registered_cache_types() { * @return array */ public function enabled_cache_types() { - $default_cache_types = array( 'browser', 'skip404' ); + $default_cache_types = array( 'browser' ); if ( $this->container->has( 'cache_types' ) ) { $provided_types = $this->container->get( 'cache_types' ); diff --git a/includes/Cache/Types/Skip404.php b/includes/Cache/Types/Skip404.php deleted file mode 100644 index 1dfeef28..00000000 --- a/includes/Cache/Types/Skip404.php +++ /dev/null @@ -1,108 +0,0 @@ -has( 'isApache' ) && $container->get( 'isApache' ); - } - - /** - * Constructor. - */ - public function __construct() { - - new OptionListener( self::OPTION_SKIP_404, array( __CLASS__, 'maybeAddRules' ) ); - - add_filter( 'newfold_update_htaccess', array( $this, 'onUpdateHtaccess' ) ); - } - - /** - * When updating .htaccess, also update our rules as appropriate. - */ - public function onUpdateHtaccess() { - self::maybeAddRules( get_skip404_option() ); - - // Remove the old option from EPC, if it exists - if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'epc_skip_404_handling', 0 ) ) ) { - update_option( 'epc_skip_404_handling', 0 ); - delete_option( 'epc_skip_404_handling' ); - } - } - - /** - * Conditionally add or remove .htaccess rules based on option value. - * - * @param bool|null $shouldSkip404Handling if should skip 404 handling. - */ - public static function maybeAddRules( $shouldSkip404Handling ) { - (bool) $shouldSkip404Handling ? self::addRules() : self::removeRules(); - } - - /** - * Add our rules to the .htacces file. - */ - public static function addRules() { - $content = << - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteCond %{REQUEST_FILENAME} !-d - RewriteCond %{REQUEST_URI} !(robots\.txt|ads\.txt|[a-z0-9_\-]*sitemap[a-z0-9_\.\-]*\.(xml|xsl|html)(\.gz)?) - RewriteCond %{REQUEST_URI} \.(css|htc|less|js|js2|js3|js4|html|htm|rtf|rtx|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|avif|avifs|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|webm|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip)$ [NC] - RewriteRule .* - [L] - -HTACCESS; - - addContent( self::MARKER, $content ); - } - - /** - * Remove our rules from the .htaccess file. - */ - public static function removeRules() { - removeMarkers( self::MARKER ); - } - - /** - * Handle activation logic. - */ - public static function on_activation() { - self::maybeAddRules( get_skip404_option() ); - } - - /** - * Handle deactivation logic. - */ - public static function on_deactivation() { - self::removeRules(); - } -} diff --git a/includes/Cache/Types/WPCLI/CacheTypesCommandHandler.php b/includes/Cache/Types/WPCLI/CacheTypesCommandHandler.php index d556b9d3..7afc22c3 100644 --- a/includes/Cache/Types/WPCLI/CacheTypesCommandHandler.php +++ b/includes/Cache/Types/WPCLI/CacheTypesCommandHandler.php @@ -5,7 +5,7 @@ use NewfoldLabs\WP\Module\Performance\Cache\CacheExclusion; use NewfoldLabs\WP\Module\Performance\Cache\CacheManager; use NewfoldLabs\WP\Module\Performance\NFD_WPCLI; -use NewfoldLabs\WP\Module\Performance\Cache\Types\Skip404; +use NewfoldLabs\WP\Module\Performance\Skip404\Skip404; /** * Handles WP-CLI commands for Cache settings. @@ -91,7 +91,7 @@ public function skip_404( $args ) { NFD_WPCLI::error( __( "Invalid value. Use 'true' or 'false' for skip_404 handling.", 'wp-module-performance' ) ); } $status = filter_var( $args[0], FILTER_VALIDATE_BOOLEAN ); - update_option( Skip404::OPTION_SKIP_404, $status ); + update_option( Skip404::OPTION_NAME, $status ); NFD_WPCLI::success( sprintf( /* translators: %s is the new boolean status. */ diff --git a/includes/Performance.php b/includes/Performance.php index 3107bba1..b3c3151f 100644 --- a/includes/Performance.php +++ b/includes/Performance.php @@ -4,6 +4,7 @@ use Automattic\Jetpack\Current_Plan; +use NewfoldLabs\WP\Module\Performance\Skip404\Skip404; use NewfoldLabs\WP\ModuleLoader\Container; use NewfoldLabs\WP\Module\Installer\Services\PluginInstaller; use NewfoldLabs\WP\Module\Performance\Images\ImageManager; @@ -54,6 +55,7 @@ public function __construct( Container $container ) { $this->hooks(); new Cache( $container ); + new Skip404( $container ); new PerformanceWPCLI(); new Constants( $container ); new ImageManager( $container ); @@ -290,7 +292,6 @@ public function add_to_runtime( $sdk ) { 'jetpack_boost_minify_css' => get_option( 'jetpack_boost_status_minify-css', array() ), 'jetpack_boost_minify_css_excludes' => implode( ',', get_option( 'jetpack_boost_ds_minify_css_excludes', array( 'admin-bar', 'dashicons', 'elementor-app' ) ) ), 'install_token' => PluginInstaller::rest_get_plugin_install_hash(), - 'skip404' => get_skip404_option(), ); return array_merge( $sdk, array( 'performance' => $values ) ); diff --git a/includes/RestApi/SettingsController.php b/includes/RestApi/SettingsController.php index 110ed9f9..393f8c07 100644 --- a/includes/RestApi/SettingsController.php +++ b/includes/RestApi/SettingsController.php @@ -1,7 +1,7 @@ container = $container; + + new OptionListener( self::OPTION_NAME, array( __CLASS__, 'maybe_add_rules' ) ); + + add_filter( 'newfold_update_htaccess', array( $this, 'on_update_htaccess' ) ); + + add_action( 'newfold_container_set', array( $this, 'handle_actions_newfold_container_set' ) ); + add_action( 'plugins_loaded', array( $this, 'handle_actions_on_plugins_loaded' ) ); + + add_filter( 'newfold-runtime', array( $this, 'add_to_runtime' ), 100 ); + + register_activation_hook( $container->plugin()->file, array( $this, 'on_activation' ) ); + register_deactivation_hook( $container->plugin()->file, array( $this, 'on_deactivation' ) ); + } + + + /* public function handle_actions_newfold_container_set( Container $container ){ + $this->container = $container; + register_activation_hook( $container->plugin()->file, array( $this, 'on_activation' ) ); + register_deactivation_hook( $container->plugin()->file, array( $this, 'on_deactivation' ) ); + }*/ + + + public function handle_actions_on_plugins_loaded(){ + add_action( 'newfold/features/action/onEnable:performance', array( $this, 'on_activation' ) ); + add_action( 'newfold/features/action/onDisable:performance', array( $this, 'on_deactivation' ) ); + } + + /** + * Detect if the feature needs to be performed or not + * + * @param Container $container Dependency injection container. + * + * @return bool + */ + public static function is_active ( Container $container ) { + return (bool) $container->has( 'isApache' ) && $container->get( 'isApache' ); + } + + public static function get_value(){ + return (bool) get_option( self::OPTION_NAME, true ); + } + + /** + * When updating .htaccess, also update our rules as appropriate. + */ + public function on_update_htaccess() { + self::maybe_add_rules( self::get_value() ); + + // Remove the old option from EPC, if it exists + if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'epc_skip_404_handling', 0 ) ) ) { + update_option( 'epc_skip_404_handling', 0 ); + delete_option( 'epc_skip_404_handling' ); + } + } + + /** + * Conditionally add or remove .htaccess rules based on option value. + * + * @param bool|null $shouldSkip404Handling if should skip 404 handling. + */ + public static function maybe_add_rules( $shouldSkip404Handling ) { + (bool) $shouldSkip404Handling ? self::add_rules() : self::remove_rules(); + } + + /** + * Add our rules to the .htacces file. + */ + public static function add_rules() { + $content = << + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_URI} !(robots\.txt|ads\.txt|[a-z0-9_\-]*sitemap[a-z0-9_\.\-]*\.(xml|xsl|html)(\.gz)?) + RewriteCond %{REQUEST_URI} \.(css|htc|less|js|js2|js3|js4|html|htm|rtf|rtx|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|avif|avifs|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|webm|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip)$ [NC] + RewriteRule .* - [L] + + HTACCESS; + + addContent( self::MARKER, $content ); + } + + /** + * Remove our rules from the .htaccess file. + */ + public static function remove_rules() { + removeMarkers( self::MARKER ); + } + + /** + * Handle activation logic. + */ + public static function on_activation() { + self::maybe_add_rules( self::get_value() ); + } + + /** + * Handle deactivation logic. + */ + public static function on_deactivation() { + self::remove_rules(); + } + + /** + * Add to Newfold SDK runtime. + * + * @param array $sdk SDK data. + * @return array SDK data. + */ + public function add_to_runtime( $sdk ) { + $values = array( + 'skip404' => $this->get_value(), + ); + + return array_merge( $sdk, array( 'performance' => $values ) ); + } + + +} diff --git a/includes/burstSafetyModeFunctions.php b/includes/burstSafetyModeFunctions.php index 1e8bb0cc..e18c9013 100644 --- a/includes/burstSafetyModeFunctions.php +++ b/includes/burstSafetyModeFunctions.php @@ -1,15 +1,13 @@ add_header( 'X-Newfold-Cache-Level', 3 ); @@ -30,7 +28,7 @@ $browser::maybeAddRules( $cache_level ); if ( function_exists( 'get_skip404_option' ) && ! get_skip404_option() ) { $skip404 = new Skip404(); - $skip404::maybeAddRules( false ); + $skip404::maybe_add_rules( false ); } $response_header_manager = new ResponseHeaderManager(); $response_header_manager->add_header( 'X-Newfold-Cache-Level', $cache_level ); diff --git a/includes/functions.php b/includes/functions.php index 7ef49a6c..412b314a 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2,7 +2,7 @@ namespace NewfoldLabs\WP\Module\Performance; -use NewfoldLabs\WP\Module\Performance\Cache\Types\Skip404; +use NewfoldLabs\WP\Module\Performance\Skip404\Skip404; use NewfoldLabs\WP\Module\Performance\Cache\CacheManager; /** @@ -29,7 +29,7 @@ function get_cache_level() { * @return bool Whether to skip 404 handling for static files. */ function get_skip404_option() { - return (bool) get_option( Skip404::OPTION_SKIP_404, true ); + return (bool) get_option( Skip404::OPTION_NAME, true ); } /** From 3fad3c7c906d2849e544ce0d3419d53a8f458c0a Mon Sep 17 00:00:00 2001 From: Alessio Torrisi Date: Mon, 10 Mar 2025 16:02:22 +0100 Subject: [PATCH 05/14] Fix: localized value skip404 for newfold runtime --- components/skip404/index.js | 2 +- includes/RestApi/SettingsController.php | 2 +- includes/Skip404/Skip404.php | 5 ++--- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/components/skip404/index.js b/components/skip404/index.js index cdd1e70f..77980a4b 100644 --- a/components/skip404/index.js +++ b/components/skip404/index.js @@ -7,7 +7,7 @@ import { NewfoldRuntime } from '@newfold/wp-module-runtime'; const Skip404 = ( { methods, constants } ) => { const [ skip404, setSkip404 ] = methods.useState( - NewfoldRuntime.sdk.performance.skip404 + NewfoldRuntime.sdk.skip404.is_active ); const getSkip404NoticeTitle = () => { diff --git a/includes/RestApi/SettingsController.php b/includes/RestApi/SettingsController.php index 393f8c07..abd20a9d 100644 --- a/includes/RestApi/SettingsController.php +++ b/includes/RestApi/SettingsController.php @@ -76,7 +76,7 @@ public function set_options( $request ) { 400 ); } - error_log($field['value']); + switch ( $field['id'] ) { case 'skip404': $result = update_option( Skip404::OPTION_NAME, $field['value'] ); diff --git a/includes/Skip404/Skip404.php b/includes/Skip404/Skip404.php index 79463575..4a76ef11 100644 --- a/includes/Skip404/Skip404.php +++ b/includes/Skip404/Skip404.php @@ -7,7 +7,6 @@ use function WP_Forge\WP_Htaccess_Manager\addContent; use function WP_Forge\WP_Htaccess_Manager\removeMarkers; -use function NewfoldLabs\WP\Module\Performance\get_skip404_option; /** * Handles Skip 404 functionality. @@ -152,10 +151,10 @@ public static function on_deactivation() { */ public function add_to_runtime( $sdk ) { $values = array( - 'skip404' => $this->get_value(), + 'is_active' => $this->get_value(), ); - return array_merge( $sdk, array( 'performance' => $values ) ); + return array_merge( $sdk, array( 'skip404' => $values ) ); } From 8da4f91e835eb10ebea86e21a6a24e38f6eeaaa9 Mon Sep 17 00:00:00 2001 From: Alessio Torrisi Date: Mon, 10 Mar 2025 16:12:40 +0100 Subject: [PATCH 06/14] FIx: phpcs issues --- includes/BurstSafetyMode/init.php | 2 +- includes/Cache/CacheFeatureHooks.php | 4 +- includes/HealthChecks/HealthCheck.php | 3 +- includes/Performance.php | 2 +- includes/RestApi/SettingsController.php | 8 +- includes/Skip404/Skip404.php | 291 ++++++++++++------------ 6 files changed, 156 insertions(+), 154 deletions(-) diff --git a/includes/BurstSafetyMode/init.php b/includes/BurstSafetyMode/init.php index 96e60a75..fa934d16 100644 --- a/includes/BurstSafetyMode/init.php +++ b/includes/BurstSafetyMode/init.php @@ -3,7 +3,7 @@ use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Skip404 as BurstSkip404; use NewfoldLabs\WP\Module\Performance\BurstSafetyMode\Browser as BurstBrowser; use NewfoldLabs\WP\Module\Performance\Cache\Types\Browser as CacheBrowser; -use NewfoldLabs\WP\Module\Performance\Skip404\Skip404 as Skip404; +use NewfoldLabs\WP\Module\Performance\Skip404\Skip404; use NewfoldLabs\WP\Module\Performance\Cache\ResponseHeaderManager; diff --git a/includes/Cache/CacheFeatureHooks.php b/includes/Cache/CacheFeatureHooks.php index 8a5cec7e..3d548957 100644 --- a/includes/Cache/CacheFeatureHooks.php +++ b/includes/Cache/CacheFeatureHooks.php @@ -56,7 +56,7 @@ public function hooks() { * Activation hook to perform when plugin is activated or feature is enabled */ public function on_activation() { - //Skip404::on_activation(); + // Skip404::on_activation(); File::on_activation(); Browser::on_activation(); // Add headers to .htaccess @@ -68,7 +68,7 @@ public function on_activation() { * Deactivation hook to perform when plugin is deactivated or feature is disabled */ public function on_deactivation() { - //Skip404::on_deactivation(); + // Skip404::on_deactivation(); File::on_deactivation(); Browser::on_deactivation(); // Remove all headers from .htaccess diff --git a/includes/HealthChecks/HealthCheck.php b/includes/HealthChecks/HealthCheck.php index 7b5667d3..b345ed16 100644 --- a/includes/HealthChecks/HealthCheck.php +++ b/includes/HealthChecks/HealthCheck.php @@ -95,7 +95,8 @@ public function register_health_check( $tests ) { 'actions' => $this->actions, 'test' => $this->id, 'badge' => array( - 'label' => __( 'Performance' ), // No text domain, as we want to match the WP core badge text. + // No text domain, as we want to match the WP core badge text. + 'label' => __( 'Performance' ), // phpcs:ignore WordPress.WP.I18n.MissingArgDomain 'color' => $this->badge_color, ), ); diff --git a/includes/Performance.php b/includes/Performance.php index b3c3151f..7c6a7cc7 100644 --- a/includes/Performance.php +++ b/includes/Performance.php @@ -55,7 +55,7 @@ public function __construct( Container $container ) { $this->hooks(); new Cache( $container ); - new Skip404( $container ); + new Skip404( $container ); new PerformanceWPCLI(); new Constants( $container ); new ImageManager( $container ); diff --git a/includes/RestApi/SettingsController.php b/includes/RestApi/SettingsController.php index abd20a9d..9be7d9e7 100644 --- a/includes/RestApi/SettingsController.php +++ b/includes/RestApi/SettingsController.php @@ -59,7 +59,7 @@ public function set_options( $request ) { return new \WP_REST_Response( array( 'success' => false, - 'error' => __( "The parameter 'field' is missing or invalid.", 'newfold-performance-module' ), + 'error' => __( "The parameter 'field' is missing or invalid.", 'wp-module-performance' ), ), 400 ); @@ -71,7 +71,7 @@ public function set_options( $request ) { return new \WP_REST_Response( array( 'success' => false, - 'error' => __( "The fields 'id' and 'value' are required.", 'newfold-performance-module' ), + 'error' => __( "The fields 'id' and 'value' are required.", 'wp-module-performance' ), ), 400 ); @@ -90,7 +90,7 @@ public function set_options( $request ) { return new \WP_REST_Response( array( 'success' => false, - 'error' => __( 'An error occurred while updating the option.', 'newfold-performance-module' ), + 'error' => __( 'An error occurred while updating the option.', 'wp-module-performance' ), ), 500 ); @@ -110,7 +110,7 @@ public function set_options( $request ) { return new \WP_REST_Response( array( 'success' => false, - 'error' => __( 'An error occurred while updating the option.', 'newfold-performance-module' ) . $e->getMessage(), + 'error' => __( 'An error occurred while updating the option.', 'wp-module-performance' ) . $e->getMessage(), ), 500 ); diff --git a/includes/Skip404/Skip404.php b/includes/Skip404/Skip404.php index 4a76ef11..3c36bfa7 100644 --- a/includes/Skip404/Skip404.php +++ b/includes/Skip404/Skip404.php @@ -13,149 +13,150 @@ */ class Skip404 { - /** - * Dependency injection container. - * - * @var Container - */ - protected $container; - - /** - * Option name for skip 404 setting. - * - * @var string - */ - const OPTION_NAME = 'newfold_skip_404_handling'; - - /** - * The file marker name. - */ - const MARKER = 'Newfold Skip 404 Handling for Static Files'; - - - /** - * Constructor. - * - * @param Container $container The dependency injection container. - */ - public function __construct( Container $container ) { - $this->container = $container; - - new OptionListener( self::OPTION_NAME, array( __CLASS__, 'maybe_add_rules' ) ); - - add_filter( 'newfold_update_htaccess', array( $this, 'on_update_htaccess' ) ); - - add_action( 'newfold_container_set', array( $this, 'handle_actions_newfold_container_set' ) ); - add_action( 'plugins_loaded', array( $this, 'handle_actions_on_plugins_loaded' ) ); - - add_filter( 'newfold-runtime', array( $this, 'add_to_runtime' ), 100 ); - - register_activation_hook( $container->plugin()->file, array( $this, 'on_activation' ) ); - register_deactivation_hook( $container->plugin()->file, array( $this, 'on_deactivation' ) ); - } - - - /* public function handle_actions_newfold_container_set( Container $container ){ - $this->container = $container; - register_activation_hook( $container->plugin()->file, array( $this, 'on_activation' ) ); - register_deactivation_hook( $container->plugin()->file, array( $this, 'on_deactivation' ) ); - }*/ - - - public function handle_actions_on_plugins_loaded(){ - add_action( 'newfold/features/action/onEnable:performance', array( $this, 'on_activation' ) ); - add_action( 'newfold/features/action/onDisable:performance', array( $this, 'on_deactivation' ) ); - } - - /** - * Detect if the feature needs to be performed or not - * - * @param Container $container Dependency injection container. - * - * @return bool - */ - public static function is_active ( Container $container ) { - return (bool) $container->has( 'isApache' ) && $container->get( 'isApache' ); - } - - public static function get_value(){ - return (bool) get_option( self::OPTION_NAME, true ); - } - - /** - * When updating .htaccess, also update our rules as appropriate. - */ - public function on_update_htaccess() { - self::maybe_add_rules( self::get_value() ); - - // Remove the old option from EPC, if it exists - if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'epc_skip_404_handling', 0 ) ) ) { - update_option( 'epc_skip_404_handling', 0 ); - delete_option( 'epc_skip_404_handling' ); - } - } - - /** - * Conditionally add or remove .htaccess rules based on option value. - * - * @param bool|null $shouldSkip404Handling if should skip 404 handling. - */ - public static function maybe_add_rules( $shouldSkip404Handling ) { - (bool) $shouldSkip404Handling ? self::add_rules() : self::remove_rules(); - } - - /** - * Add our rules to the .htacces file. - */ - public static function add_rules() { - $content = << - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteCond %{REQUEST_FILENAME} !-d - RewriteCond %{REQUEST_URI} !(robots\.txt|ads\.txt|[a-z0-9_\-]*sitemap[a-z0-9_\.\-]*\.(xml|xsl|html)(\.gz)?) - RewriteCond %{REQUEST_URI} \.(css|htc|less|js|js2|js3|js4|html|htm|rtf|rtx|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|avif|avifs|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|webm|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip)$ [NC] - RewriteRule .* - [L] - - HTACCESS; - - addContent( self::MARKER, $content ); - } - - /** - * Remove our rules from the .htaccess file. - */ - public static function remove_rules() { - removeMarkers( self::MARKER ); - } - - /** - * Handle activation logic. - */ - public static function on_activation() { - self::maybe_add_rules( self::get_value() ); - } - - /** - * Handle deactivation logic. - */ - public static function on_deactivation() { - self::remove_rules(); - } - - /** - * Add to Newfold SDK runtime. - * - * @param array $sdk SDK data. - * @return array SDK data. - */ - public function add_to_runtime( $sdk ) { - $values = array( - 'is_active' => $this->get_value(), - ); - - return array_merge( $sdk, array( 'skip404' => $values ) ); - } - - + /** + * Dependency injection container. + * + * @var Container + */ + protected $container; + + /** + * Option name for skip 404 setting. + * + * @var string + */ + const OPTION_NAME = 'newfold_skip_404_handling'; + + /** + * The file marker name. + */ + const MARKER = 'Newfold Skip 404 Handling for Static Files'; + + + /** + * Constructor. + * + * @param Container $container The dependency injection container. + */ + public function __construct( Container $container ) { + $this->container = $container; + + new OptionListener( self::OPTION_NAME, array( __CLASS__, 'maybe_add_rules' ) ); + + add_filter( 'newfold_update_htaccess', array( $this, 'on_update_htaccess' ) ); + + add_action( 'newfold_container_set', array( $this, 'handle_actions_newfold_container_set' ) ); + add_action( 'plugins_loaded', array( $this, 'handle_actions_on_plugins_loaded' ) ); + + add_filter( 'newfold-runtime', array( $this, 'add_to_runtime' ), 100 ); + + register_activation_hook( $container->plugin()->file, array( $this, 'on_activation' ) ); + register_deactivation_hook( $container->plugin()->file, array( $this, 'on_deactivation' ) ); + } + + + /** + * Perform actions on enabling/disabling Performance feature + * + * @return void + */ + public function handle_actions_on_plugins_loaded() { + add_action( 'newfold/features/action/onEnable:performance', array( $this, 'on_activation' ) ); + add_action( 'newfold/features/action/onDisable:performance', array( $this, 'on_deactivation' ) ); + } + + /** + * Detect if the feature needs to be performed or not + * + * @param Container $container Dependency injection container. + * + * @return bool + */ + public static function is_active( Container $container ) { + return (bool) $container->has( 'isApache' ) && $container->get( 'isApache' ); + } + + /** + * Get value for SKIP404 option + * + * @return bool + */ + public static function get_value() { + return (bool) get_option( self::OPTION_NAME, true ); + } + + /** + * When updating .htaccess, also update our rules as appropriate. + */ + public function on_update_htaccess() { + self::maybe_add_rules( self::get_value() ); + + // Remove the old option from EPC, if it exists + if ( $this->container->get( 'hasMustUsePlugin' ) && absint( get_option( 'epc_skip_404_handling', 0 ) ) ) { + update_option( 'epc_skip_404_handling', 0 ); + delete_option( 'epc_skip_404_handling' ); + } + } + + /** + * Conditionally add or remove .htaccess rules based on option value. + * + * @param bool|null $shouldSkip404Handling if should skip 404 handling. + */ + public static function maybe_add_rules( $shouldSkip404Handling ) { + (bool) $shouldSkip404Handling ? self::add_rules() : self::remove_rules(); + } + + /** + * Add our rules to the .htacces file. + */ + public static function add_rules() { + $content = << + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_URI} !(robots\.txt|ads\.txt|[a-z0-9_\-]*sitemap[a-z0-9_\.\-]*\.(xml|xsl|html)(\.gz)?) + RewriteCond %{REQUEST_URI} \.(css|htc|less|js|js2|js3|js4|html|htm|rtf|rtx|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|avif|avifs|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|webm|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip)$ [NC] + RewriteRule .* - [L] + + HTACCESS; // phpcs:ignore Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsedHeredocCloser + + addContent( self::MARKER, $content ); + } + + /** + * Remove our rules from the .htaccess file. + */ + public static function remove_rules() { + removeMarkers( self::MARKER ); + } + + /** + * Handle activation logic. + */ + public static function on_activation() { + self::maybe_add_rules( self::get_value() ); + } + + /** + * Handle deactivation logic. + */ + public static function on_deactivation() { + self::remove_rules(); + } + + /** + * Add to Newfold SDK runtime. + * + * @param array $sdk SDK data. + * @return array SDK data. + */ + public function add_to_runtime( $sdk ) { + $values = array( + 'is_active' => $this->get_value(), + ); + + return array_merge( $sdk, array( 'skip404' => $values ) ); + } } From ab60bd30b97e11265392bf2075ba53a719981f7a Mon Sep 17 00:00:00 2001 From: Alessio Torrisi Date: Tue, 11 Mar 2025 10:35:21 +0100 Subject: [PATCH 07/14] Renamed REST API controller for SKIP 404 option --- components/skip404/index.js | 2 +- includes/Cache/CacheFeatureHooks.php | 3 --- includes/RestApi/RestApi.php | 2 +- .../RestApi/{SettingsController.php => Skip404Controller.php} | 4 ++-- 4 files changed, 4 insertions(+), 7 deletions(-) rename includes/RestApi/{SettingsController.php => Skip404Controller.php} (97%) diff --git a/components/skip404/index.js b/components/skip404/index.js index 77980a4b..db8101f9 100644 --- a/components/skip404/index.js +++ b/components/skip404/index.js @@ -17,7 +17,7 @@ const Skip404 = ( { methods, constants } ) => { const handleSkip404Change = () => { const value = ! skip404; apiFetch( { - path: 'newfold-performance/v1/settings', + path: 'newfold-performance/v1/skip404', method: 'POST', data: { field: { diff --git a/includes/Cache/CacheFeatureHooks.php b/includes/Cache/CacheFeatureHooks.php index 3d548957..aa9996b4 100644 --- a/includes/Cache/CacheFeatureHooks.php +++ b/includes/Cache/CacheFeatureHooks.php @@ -6,7 +6,6 @@ use NewfoldLabs\WP\Module\Performance\OptionListener; use NewfoldLabs\WP\Module\Performance\Cache\Types\Browser; use NewfoldLabs\WP\Module\Performance\Cache\Types\File; -use NewfoldLabs\WP\Module\Performance\Skip404\Skip404; use function NewfoldLabs\WP\Module\Performance\get_cache_level; @@ -56,7 +55,6 @@ public function hooks() { * Activation hook to perform when plugin is activated or feature is enabled */ public function on_activation() { - // Skip404::on_activation(); File::on_activation(); Browser::on_activation(); // Add headers to .htaccess @@ -68,7 +66,6 @@ public function on_activation() { * Deactivation hook to perform when plugin is deactivated or feature is disabled */ public function on_deactivation() { - // Skip404::on_deactivation(); File::on_deactivation(); Browser::on_deactivation(); // Remove all headers from .htaccess diff --git a/includes/RestApi/RestApi.php b/includes/RestApi/RestApi.php index 8eaeb703..ed90f3da 100644 --- a/includes/RestApi/RestApi.php +++ b/includes/RestApi/RestApi.php @@ -12,7 +12,7 @@ final class RestApi { * @var array */ protected $controllers = array( - 'NewfoldLabs\\WP\\Module\\Performance\\RestApi\\SettingsController', + 'NewfoldLabs\\WP\\Module\\Performance\\RestApi\\Skip404Controller', 'NewfoldLabs\\WP\\Module\\Performance\\RestApi\\LinkPrefetchController', 'NewfoldLabs\\WP\\Module\\Performance\\RestApi\\JetpackController', 'NewfoldLabs\\WP\\Module\\Performance\\RestApi\\CacheExclusionController', diff --git a/includes/RestApi/SettingsController.php b/includes/RestApi/Skip404Controller.php similarity index 97% rename from includes/RestApi/SettingsController.php rename to includes/RestApi/Skip404Controller.php index 9be7d9e7..372b2be8 100644 --- a/includes/RestApi/SettingsController.php +++ b/includes/RestApi/Skip404Controller.php @@ -8,7 +8,7 @@ * * @package NewfoldLabs\WP\Module\Performance */ -class SettingsController { +class Skip404Controller { /** * The REST route namespace. @@ -22,7 +22,7 @@ class SettingsController { * * @var string */ - protected $rest_base = '/settings'; + protected $rest_base = '/skip404'; /** * Register API routes. From 7ef7c0823e06b5ca09c8ffabf543721f00b7eccf Mon Sep 17 00:00:00 2001 From: Alessio Torrisi Date: Tue, 11 Mar 2025 10:36:30 +0100 Subject: [PATCH 08/14] Tweak: removed useless Burst Safety Mode code --- includes/BurstSafetyMode/Browser.php | 1 - includes/BurstSafetyMode/init.php | 11 +------- includes/PerformanceFeature.php | 2 -- includes/burstSafetyModeFunctions.php | 37 --------------------------- 4 files changed, 1 insertion(+), 50 deletions(-) delete mode 100644 includes/burstSafetyModeFunctions.php diff --git a/includes/BurstSafetyMode/Browser.php b/includes/BurstSafetyMode/Browser.php index ab23a494..e42c2dd3 100644 --- a/includes/BurstSafetyMode/Browser.php +++ b/includes/BurstSafetyMode/Browser.php @@ -1,7 +1,6 @@ add_header( 'X-Newfold-Cache-Level', $newfold_cache_level ); diff --git a/includes/PerformanceFeature.php b/includes/PerformanceFeature.php index 7f238578..3d27a951 100644 --- a/includes/PerformanceFeature.php +++ b/includes/PerformanceFeature.php @@ -2,8 +2,6 @@ namespace NewfoldLabs\WP\Module\Performance; -use NewfoldLabs\WP\Module\Performance\Performance; - use function NewfoldLabs\WP\ModuleLoader\container as getContainer; /** diff --git a/includes/burstSafetyModeFunctions.php b/includes/burstSafetyModeFunctions.php deleted file mode 100644 index e18c9013..00000000 --- a/includes/burstSafetyModeFunctions.php +++ /dev/null @@ -1,37 +0,0 @@ -add_header( 'X-Newfold-Cache-Level', 3 ); - } -} elseif ( $newfold_burst_safety_mode ) { - $cache_level = get_option( 'newfold_burst_safety_mode_site_cache_level' ); - $browser = new Browser(); - $browser::maybeAddRules( $cache_level ); - if ( function_exists( 'get_skip404_option' ) && ! get_skip404_option() ) { - $skip404 = new Skip404(); - $skip404::maybe_add_rules( false ); - } - $response_header_manager = new ResponseHeaderManager(); - $response_header_manager->add_header( 'X-Newfold-Cache-Level', $cache_level ); - delete_option( 'newfold_burst_safety_mode' ); - delete_option( 'newfold_burst_safety_mode_site_cache_level' ); -} From c6bc03624c6c33f0bc7fdc0cf873a0a2e28cd8d4 Mon Sep 17 00:00:00 2001 From: Alessio Torrisi Date: Thu, 20 Mar 2025 09:07:22 +0100 Subject: [PATCH 09/14] Tweak: create unique cache controller for rest api --- components/cacheExclusion/index.js | 18 +++--- components/cacheSettings/index.js | 30 ++++++---- components/clearCache/index.js | 28 ++++++--- includes/Cache/Cache.php | 19 ++++++ ...sionController.php => CacheController.php} | 60 +++++++++++++------ includes/RestApi/RestApi.php | 2 +- includes/functions.php | 10 ++++ 7 files changed, 122 insertions(+), 45 deletions(-) rename includes/RestApi/{CacheExclusionController.php => CacheController.php} (51%) diff --git a/components/cacheExclusion/index.js b/components/cacheExclusion/index.js index 74697b07..effed3b2 100644 --- a/components/cacheExclusion/index.js +++ b/components/cacheExclusion/index.js @@ -9,13 +9,16 @@ const CacheExclusion = ( { methods, constants } ) => { const [ isError, setIsError ] = methods.useState( false ); const [ isSaved, setIsSaved ] = methods.useState( false ); const [ currentValue, setCurrentValue ] = methods.useState( - methods.NewfoldRuntime.sdk.cacheExclusion + methods.NewfoldRuntime.sdk.cache.exclusion ); + const [ cacheExclusion, setCacheExclusion ] = methods.useState( - methods.NewfoldRuntime.sdk.cacheExclusion + methods.NewfoldRuntime.sdk.cache.exclusion ); + + const apiUrl = methods.NewfoldRuntime.createApiUrl( - '/newfold-performance/v1/cache-exclusion/update' + '/newfold-performance/v1/cache/settings' ); const handleCacheExclusionChange = ( e ) => { @@ -45,18 +48,17 @@ const CacheExclusion = ( { methods, constants } ) => { }; methods.useUpdateEffect( () => { - methods.setStore( { - ...constants.store, - CacheExclusion: cacheExclusion, - } ); methods.makeNotice( - 'cache-exlusion-notice', + 'cache-exclusion-notice', constants.text.cacheExclusionTitle, ! isError ? constants.text.cacheExclusionSaved : isError, ! isError ? 'success' : 'error', 5000 ); + + setIsSaved( false ); + }, [ isSaved, isError ] ); return ( diff --git a/components/cacheSettings/index.js b/components/cacheSettings/index.js index 383bd46a..6169374f 100644 --- a/components/cacheSettings/index.js +++ b/components/cacheSettings/index.js @@ -6,6 +6,10 @@ const CacheSettings = ( { methods, constants, Components } ) => { constants.store.cacheLevel ); + const apiUrl = methods.NewfoldRuntime.createApiUrl( + '/newfold-performance/v1/cache/settings' + ); + const cacheOptions = [ { label: constants.text.cacheLevel0Label, @@ -53,21 +57,23 @@ const CacheSettings = ( { methods, constants, Components } ) => { }; const handleCacheLevelChange = ( e ) => { - methods.newfoldSettingsApiFetch( - { cacheLevel: parseInt( e.target.value ) }, - methods.setError, - () => { + + methods + .apiFetch( { + url: apiUrl, + method: 'POST', + data: { cacheLevel: parseInt( e.target.value ) }, + } ) + .then( () => { setCacheLevel( parseInt( e.target.value ) ); - } - ); + constants.store.cacheLevel = parseInt( e.target.value ); + } ) + .catch( ( error ) => { + methods.setError + } ); }; methods.useUpdateEffect( () => { - methods.setStore( { - ...constants.store, - cacheLevel, - } ); - methods.makeNotice( 'cache-level-change-notice', getCacheLevelNoticeTitle(), @@ -95,7 +101,7 @@ const CacheSettings = ( { methods, constants, Components } ) => { { + + const apiUrl = methods.NewfoldRuntime.createApiUrl( + '/newfold-performance/v1/cache/settings' + ); + const clearCache = () => { - methods.newfoldPurgeCacheApiFetch( - {}, - methods.setError, - ( response ) => { + + + methods + .apiFetch( { + url: apiUrl, + method: 'DELETE', + } ) + .then( () => { methods.makeNotice( 'disable-old-posts-comments-notice', constants.text.clearCacheNoticeTitle, @@ -13,10 +22,15 @@ const ClearCache = ( { methods, constants } ) => { 'success', 5000 ); - } - ); + } ) + .catch( ( error ) => { + methods.setError( error ) + } ); }; + const cacheLevel = constants.store.cacheLevel ?? methods.NewfoldRuntime.sdk.cache.level; + + return ( {