From 9ed2e122a25c3723a8db6341c5872da903a5af20 Mon Sep 17 00:00:00 2001 From: Jacob Dunn <88040916+jacobd91@users.noreply.github.com> Date: Fri, 29 Nov 2024 11:28:22 -0500 Subject: [PATCH] Coding Standard Fixes (#1002) --- Base_Page_Settings.php | 18 + BrowserCache_ConfigLabels.php | 209 ++++++----- BrowserCache_Core.php | 64 +++- BrowserCache_Environment.php | 282 ++++++++------- BrowserCache_Environment_Apache.php | 84 +++-- BrowserCache_Environment_LiteSpeed.php | 216 ++++++----- BrowserCache_Environment_Nginx.php | 224 ++++++------ BrowserCache_Page.php | 64 +++- BrowserCache_Page_View_QuickReference.php | 6 + BrowserCache_Page_View_SectionSecurity.php | 1 + BrowserCache_Plugin.php | 396 +++++++++++++-------- BrowserCache_Plugin_Admin.php | 47 ++- Cache_Apc.php | 167 ++++++--- Cache_Apcu.php | 163 ++++++--- Cache_Base.php | 209 +++++++---- Cache_Eaccelerator.php | 157 +++++--- Cache_File_Cleaner.php | 57 +-- Cache_File_Cleaner_Generic.php | 89 +++-- Cache_File_Cleaner_Generic_HardDelete.php | 35 +- Cache_File_Generic.php | 274 ++++++++------ Extension_ImageService_Api.php | 4 + Generic_AdminActions_Config.php | 151 +++++--- Generic_AdminActions_Default.php | 113 ++++-- Generic_AdminActions_Flush.php | 282 ++++++++++----- Generic_AdminActions_Test.php | 162 +++++---- Generic_AdminNotes.php | 1 + Generic_ConfigLabels.php | 61 ++-- Generic_Environment.php | 122 ++++--- Generic_Faq.php | 81 +++-- Generic_Page_About.php | 17 +- Generic_Page_Dashboard.php | 45 ++- Generic_Page_General.php | 79 ++-- Generic_Page_PurgeLog.php | 106 ++++-- Generic_Page_PurgeLog_View.php | 6 + Generic_Plugin.php | 127 +++++-- Generic_Plugin_Admin.php | 74 ++-- Generic_Plugin_AdminCompatibility.php | 94 +++-- Generic_Plugin_AdminRowActions.php | 103 ++++-- Generic_Plugin_Admin_View_Faq.php | 6 + Generic_WidgetAccount_View.php | 2 +- Generic_WidgetBoldGrid.php | 58 ++- Generic_WidgetBoldGrid_AdminActions.php | 24 +- Generic_WidgetServices_View.php | 6 + Generic_WidgetSettings_View.php | 8 +- Generic_WidgetSpreadTheWord_Plugin.php | 67 ++-- Generic_WidgetSpreadTheWord_View.php | 6 + SetupGuide_Plugin_Admin.php | 1 + Util_Activation.php | 300 +++++++++------- Util_Admin.php | 56 +-- Util_AttachToActions.php | 5 +- Util_Bus.php | 33 +- Util_Content.php | 87 +++-- Util_Debug.php | 155 +++++--- Util_DebugPurgeLog_Reader.php | 111 ++++-- Util_Environment.php | 194 ++++++---- Util_Environment_Exception.php | 27 ++ Util_Environment_Exceptions.php | 55 ++- pub/js/setup-guide.js | 5 +- 58 files changed, 3633 insertions(+), 1963 deletions(-) diff --git a/Base_Page_Settings.php b/Base_Page_Settings.php index 5c0023ef3..01d972144 100644 --- a/Base_Page_Settings.php +++ b/Base_Page_Settings.php @@ -57,6 +57,8 @@ class Base_Page_Settings { /** * Constructor. + * + * @return void */ public function __construct() { $this->_config = Dispatcher::config(); @@ -66,6 +68,8 @@ public function __construct() { /** * Render header. + * + * @return void */ public function options() { $this->view(); @@ -73,6 +77,8 @@ public function options() { /** * Render footer. + * + * @return void */ public function render_footer() { include W3TC_INC_OPTIONS_DIR . '/common/footer.php'; @@ -106,6 +112,8 @@ protected function is_master() { * @param string $class_prefix Class prefix. * @param bool $label Label. * @param bool $force_value Override value. + * + * @return void */ protected function checkbox( $option_id, $disabled = false, $class_prefix = '', $label = true, $force_value = null ) { $disabled = $disabled || $this->_config->is_sealed( $option_id ); @@ -149,6 +157,8 @@ protected function checkbox( $option_id, $disabled = false, $class_prefix = '', * @param unknown $value Value. * @param bool $disabled Disabled flag. * @param string $class_prefix Class prefix. + * + * @return void */ protected function radio( $option_id, $value, $disabled = false, $class_prefix = '' ) { if ( is_bool( $value ) ) { @@ -176,6 +186,8 @@ protected function radio( $option_id, $value, $disabled = false, $class_prefix = * Prints checkbox for debug option. * * @param string $option_id Option ID. + * + * @return void */ protected function checkbox_debug( $option_id ) { if ( is_array( $option_id ) ) { @@ -211,6 +223,8 @@ protected function checkbox_debug( $option_id ) { * @param string $option_id Option ID. * @param unknown $label Label. * @param unknown $label_pro Pro label. + * + * @return void */ protected function checkbox_debug_pro( $option_id, $label, $label_pro ) { if ( is_array( $option_id ) ) { @@ -263,6 +277,8 @@ protected function checkbox_debug_pro( $option_id, $label, $label_pro ) { * @param string $option_id Option ID. * @param bool $disabled Disabled flag. * @param unknown $value_when_disabled Override value when disabled. + * + * @return void */ protected function value_with_disabled( $option_id, $disabled, $value_when_disabled ) { if ( $disabled ) { @@ -274,6 +290,8 @@ protected function value_with_disabled( $option_id, $disabled, $value_when_disab /** * Render header. + * + * @return void */ protected function view() { include W3TC_INC_DIR . '/options/common/header.php'; diff --git a/BrowserCache_ConfigLabels.php b/BrowserCache_ConfigLabels.php index 1ff909163..b32e95ce2 100644 --- a/BrowserCache_ConfigLabels.php +++ b/BrowserCache_ConfigLabels.php @@ -1,110 +1,129 @@ __( 'Browser Cache:', 'w3-total-cache' ), - 'browsercache.replace.exceptions' => __( 'Prevent caching exception list:', 'w3-total-cache' ), - 'browsercache.no404wp' => __( 'Do not process 404 errors for static objects with WordPress', 'w3-total-cache' ), - 'browsercache.no404wp.exceptions' => __( '404 error exception list:', 'w3-total-cache' ), - 'browsercache.cssjs.last_modified' => __( 'Set Last-Modified header', 'w3-total-cache' ), - 'browsercache.cssjs.expires' => __( 'Set expires header', 'w3-total-cache' ), - 'browsercache.cssjs.lifetime' => __( 'Expires header lifetime:', 'w3-total-cache' ), - 'browsercache.cssjs.cache.control' => __( 'Set cache control header', 'w3-total-cache' ), - 'browsercache.cssjs.cache.policy' => __( 'Cache Control policy:', 'w3-total-cache' ), - 'browsercache.cssjs.etag' => __( 'Set entity tag (eTag)', 'w3-total-cache' ), - 'browsercache.cssjs.w3tc' => __( 'Set W3 Total Cache header', 'w3-total-cache' ), - 'browsercache.cssjs.compression' => __( 'Enable HTTP (gzip) compression', 'w3-total-cache' ), - 'browsercache.cssjs.brotli' => __( 'Enable HTTP (brotli) compression', 'w3-total-cache' ), - 'browsercache.cssjs.replace' => __( 'Prevent caching of objects after settings change', 'w3-total-cache' ), - 'browsercache.cssjs.nocookies' => __( 'Disable cookies for static files', 'w3-total-cache' ), - 'browsercache.html.last_modified' => __( 'Set Last-Modified header', 'w3-total-cache' ), - 'browsercache.html.expires' => __( 'Set expires header', 'w3-total-cache' ), - 'browsercache.html.lifetime' => __( 'Expires header lifetime:', 'w3-total-cache' ), - 'browsercache.html.cache.control' => __( 'Set cache control header', 'w3-total-cache' ), - 'browsercache.html.cache.policy' => __( 'Cache Control policy:', 'w3-total-cache' ), - 'browsercache.html.etag' => __( 'Set entity tag (ETag)', 'w3-total-cache' ), - 'browsercache.html.w3tc' => __( 'Set W3 Total Cache header', 'w3-total-cache' ), - 'browsercache.html.compression' => __( 'Enable HTTP (gzip) compression', 'w3-total-cache' ), - 'browsercache.html.brotli' => __( 'Enable HTTP (brotli) compression', 'w3-total-cache' ), - 'browsercache.other.last_modified' => __( 'Set Last-Modified header', 'w3-total-cache' ), - 'browsercache.other.expires' => __( 'Set expires header', 'w3-total-cache' ), - 'browsercache.other.lifetime' => __( 'Expires header lifetime:', 'w3-total-cache' ), - 'browsercache.other.cache.control' => __( 'Set cache control header', 'w3-total-cache' ), - 'browsercache.other.cache.policy' => __( 'Cache Control policy:', 'w3-total-cache' ), - 'browsercache.other.etag' => __( 'Set entity tag (ETag)', 'w3-total-cache' ), - 'browsercache.other.w3tc' => __( 'Set W3 Total Cache header', 'w3-total-cache' ), - 'browsercache.other.compression' => __( 'Enable HTTP (gzip) compression', 'w3-total-cache' ), - 'browsercache.other.brotli' => __( 'Enable HTTP (brotli) compression', 'w3-total-cache' ), - 'browsercache.other.replace' => __( 'Prevent caching of objects after settings change', 'w3-total-cache' ), - 'browsercache.other.nocookies' => __( 'Disable cookies for static files', 'w3-total-cache' ), + return array_merge( + $config_labels, + array( + 'browsercache.enabled' => __( 'Browser Cache:', 'w3-total-cache' ), + 'browsercache.replace.exceptions' => __( 'Prevent caching exception list:', 'w3-total-cache' ), + 'browsercache.no404wp' => __( 'Do not process 404 errors for static objects with WordPress', 'w3-total-cache' ), + 'browsercache.no404wp.exceptions' => __( '404 error exception list:', 'w3-total-cache' ), + 'browsercache.cssjs.last_modified' => __( 'Set Last-Modified header', 'w3-total-cache' ), + 'browsercache.cssjs.expires' => __( 'Set expires header', 'w3-total-cache' ), + 'browsercache.cssjs.lifetime' => __( 'Expires header lifetime:', 'w3-total-cache' ), + 'browsercache.cssjs.cache.control' => __( 'Set cache control header', 'w3-total-cache' ), + 'browsercache.cssjs.cache.policy' => __( 'Cache Control policy:', 'w3-total-cache' ), + 'browsercache.cssjs.etag' => __( 'Set entity tag (eTag)', 'w3-total-cache' ), + 'browsercache.cssjs.w3tc' => __( 'Set W3 Total Cache header', 'w3-total-cache' ), + 'browsercache.cssjs.compression' => __( 'Enable HTTP (gzip) compression', 'w3-total-cache' ), + 'browsercache.cssjs.brotli' => __( 'Enable HTTP (brotli) compression', 'w3-total-cache' ), + 'browsercache.cssjs.replace' => __( 'Prevent caching of objects after settings change', 'w3-total-cache' ), + 'browsercache.cssjs.nocookies' => __( 'Disable cookies for static files', 'w3-total-cache' ), + 'browsercache.html.last_modified' => __( 'Set Last-Modified header', 'w3-total-cache' ), + 'browsercache.html.expires' => __( 'Set expires header', 'w3-total-cache' ), + 'browsercache.html.lifetime' => __( 'Expires header lifetime:', 'w3-total-cache' ), + 'browsercache.html.cache.control' => __( 'Set cache control header', 'w3-total-cache' ), + 'browsercache.html.cache.policy' => __( 'Cache Control policy:', 'w3-total-cache' ), + 'browsercache.html.etag' => __( 'Set entity tag (ETag)', 'w3-total-cache' ), + 'browsercache.html.w3tc' => __( 'Set W3 Total Cache header', 'w3-total-cache' ), + 'browsercache.html.compression' => __( 'Enable HTTP (gzip) compression', 'w3-total-cache' ), + 'browsercache.html.brotli' => __( 'Enable HTTP (brotli) compression', 'w3-total-cache' ), + 'browsercache.other.last_modified' => __( 'Set Last-Modified header', 'w3-total-cache' ), + 'browsercache.other.expires' => __( 'Set expires header', 'w3-total-cache' ), + 'browsercache.other.lifetime' => __( 'Expires header lifetime:', 'w3-total-cache' ), + 'browsercache.other.cache.control' => __( 'Set cache control header', 'w3-total-cache' ), + 'browsercache.other.cache.policy' => __( 'Cache Control policy:', 'w3-total-cache' ), + 'browsercache.other.etag' => __( 'Set entity tag (ETag)', 'w3-total-cache' ), + 'browsercache.other.w3tc' => __( 'Set W3 Total Cache header', 'w3-total-cache' ), + 'browsercache.other.compression' => __( 'Enable HTTP (gzip) compression', 'w3-total-cache' ), + 'browsercache.other.brotli' => __( 'Enable HTTP (brotli) compression', 'w3-total-cache' ), + 'browsercache.other.replace' => __( 'Prevent caching of objects after settings change', 'w3-total-cache' ), + 'browsercache.other.nocookies' => __( 'Disable cookies for static files', 'w3-total-cache' ), 'browsercache.security.session.cookie_httponly' => __( 'Access session cookies through the HTTP only:', 'w3-total-cache' ), 'browsercache.security.session.cookie_secure' => __( 'Send session cookies only to secure connections:', 'w3-total-cache' ), 'browsercache.security.session.use_only_cookies' => __( 'Use cookies to store session IDs:', 'w3-total-cache' ), - 'browsercache.hsts' => __( 'HTTP Strict Transport Security policy', 'w3-total-cache' ), - 'browsercache.security.hsts.directive' => __( 'Directive:', 'w3-total-cache' ), - 'browsercache.security.xfo' => __( 'X-Frame-Options', 'w3-total-cache' ), - 'browsercache.security.xfo.directive' => __( 'Directive:', 'w3-total-cache' ), - 'browsercache.security.xss' => __( 'X-XSS-Protection', 'w3-total-cache' ), - 'browsercache.security.xss.directive' => __( 'Directive:', 'w3-total-cache' ), - 'browsercache.security.xcto' => __( 'X-Content-Type-Options', 'w3-total-cache' ), - 'browsercache.security.pkp' => __( 'HTTP Public Key Pinning', 'w3-total-cache' ), - 'browsercache.security.pkp.pin' => __( 'Public Key:', 'w3-total-cache' ), - 'browsercache.security.pkp.pin.backup' => __( 'Public Key (Backup):', 'w3-total-cache' ), - 'browsercache.security.pkp.extra' => __( 'Extra Parameters:', 'w3-total-cache' ), - 'browsercache.security.pkp.report.url' => __( 'Report URL:', 'w3-total-cache' ), - 'browsercache.security.pkp.report.only' => __( 'Report Mode Only:', 'w3-total-cache' ), - 'browsercache.security.referrer.policy' => __( 'Referrer Policy', 'w3-total-cache' ), + 'browsercache.hsts' => __( 'HTTP Strict Transport Security policy', 'w3-total-cache' ), + 'browsercache.security.hsts.directive' => __( 'Directive:', 'w3-total-cache' ), + 'browsercache.security.xfo' => __( 'X-Frame-Options', 'w3-total-cache' ), + 'browsercache.security.xfo.directive' => __( 'Directive:', 'w3-total-cache' ), + 'browsercache.security.xss' => __( 'X-XSS-Protection', 'w3-total-cache' ), + 'browsercache.security.xss.directive' => __( 'Directive:', 'w3-total-cache' ), + 'browsercache.security.xcto' => __( 'X-Content-Type-Options', 'w3-total-cache' ), + 'browsercache.security.pkp' => __( 'HTTP Public Key Pinning', 'w3-total-cache' ), + 'browsercache.security.pkp.pin' => __( 'Public Key:', 'w3-total-cache' ), + 'browsercache.security.pkp.pin.backup' => __( 'Public Key (Backup):', 'w3-total-cache' ), + 'browsercache.security.pkp.extra' => __( 'Extra Parameters:', 'w3-total-cache' ), + 'browsercache.security.pkp.report.url' => __( 'Report URL:', 'w3-total-cache' ), + 'browsercache.security.pkp.report.only' => __( 'Report Mode Only:', 'w3-total-cache' ), + 'browsercache.security.referrer.policy' => __( 'Referrer Policy', 'w3-total-cache' ), 'browsercache.security.referrer.policy.directive' => __( 'Directive:', 'w3-total-cache' ), - 'browsercache.security.csp' => __( 'Content Security Policy', 'w3-total-cache' ), - 'browsercache.security.csp.reporturi' => __( 'report-uri:', 'w3-total-cache' ), - 'browsercache.security.csp.reportto' => __( 'report-to:', 'w3-total-cache' ), - 'browsercache.security.csp.base' => __( 'base-uri:', 'w3-total-cache' ), - 'browsercache.security.csp.frame' => __( 'frame-src:', 'w3-total-cache' ), - 'browsercache.security.csp.connect' => __( 'connect-src:', 'w3-total-cache' ), - 'browsercache.security.csp.font' => __( 'font-src:', 'w3-total-cache' ), - 'browsercache.security.csp.script' => __( 'script-src:', 'w3-total-cache' ), - 'browsercache.security.csp.style' => __( 'style-src:', 'w3-total-cache' ), - 'browsercache.security.csp.img' => __( 'img-src:', 'w3-total-cache' ), - 'browsercache.security.csp.media' => __( 'media-src:', 'w3-total-cache' ), - 'browsercache.security.csp.object' => __( 'object-src:', 'w3-total-cache' ), - 'browsercache.security.csp.plugin' => __( 'plugin-types:', 'w3-total-cache' ), - 'browsercache.security.csp.form' => __( 'form-action:', 'w3-total-cache' ), + 'browsercache.security.csp' => __( 'Content Security Policy', 'w3-total-cache' ), + 'browsercache.security.csp.reporturi' => __( 'report-uri:', 'w3-total-cache' ), + 'browsercache.security.csp.reportto' => __( 'report-to:', 'w3-total-cache' ), + 'browsercache.security.csp.base' => __( 'base-uri:', 'w3-total-cache' ), + 'browsercache.security.csp.frame' => __( 'frame-src:', 'w3-total-cache' ), + 'browsercache.security.csp.connect' => __( 'connect-src:', 'w3-total-cache' ), + 'browsercache.security.csp.font' => __( 'font-src:', 'w3-total-cache' ), + 'browsercache.security.csp.script' => __( 'script-src:', 'w3-total-cache' ), + 'browsercache.security.csp.style' => __( 'style-src:', 'w3-total-cache' ), + 'browsercache.security.csp.img' => __( 'img-src:', 'w3-total-cache' ), + 'browsercache.security.csp.media' => __( 'media-src:', 'w3-total-cache' ), + 'browsercache.security.csp.object' => __( 'object-src:', 'w3-total-cache' ), + 'browsercache.security.csp.plugin' => __( 'plugin-types:', 'w3-total-cache' ), + 'browsercache.security.csp.form' => __( 'form-action:', 'w3-total-cache' ), 'browsercache.security.csp.frame.ancestors' => __( 'frame-ancestors:', 'w3-total-cache' ), - 'browsercache.security.csp.sandbox' => __( 'sandbox:', 'w3-total-cache' ), - 'browsercache.security.csp.child' => __( 'child-src:', 'w3-total-cache' ), - 'browsercache.security.csp.manifest' => __( 'manifest-src:', 'w3-total-cache' ), - 'browsercache.security.csp.scriptelem' => __( 'script-src-elem:', 'w3-total-cache' ), - 'browsercache.security.csp.scriptattr' => __( 'script-src-attr:', 'w3-total-cache' ), - 'browsercache.security.csp.styleelem' => __( 'style-src-elem:', 'w3-total-cache' ), - 'browsercache.security.csp.styleattr' => __( 'style-src-attr:', 'w3-total-cache' ), - 'browsercache.security.csp.worker' => __( 'worker-src:', 'w3-total-cache' ), - 'browsercache.security.csp.default' => __( 'default-src:', 'w3-total-cache' ), - 'browsercache.security.cspro' => __( 'Content Security Policy Report Only', 'w3-total-cache' ), - 'browsercache.security.cspro.reporturi' => __( 'report-uri:', 'w3-total-cache' ), - 'browsercache.security.cspro.reportto' => __( 'report-to:', 'w3-total-cache' ), - 'browsercache.security.cspro.base' => __( 'base-uri:', 'w3-total-cache' ), - 'browsercache.security.cspro.frame' => __( 'frame-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.connect' => __( 'connect-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.font' => __( 'font-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.script' => __( 'script-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.style' => __( 'style-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.img' => __( 'img-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.media' => __( 'media-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.object' => __( 'object-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.plugin' => __( 'plugin-types:', 'w3-total-cache' ), - 'browsercache.security.cspro.form' => __( 'form-action:', 'w3-total-cache' ), + 'browsercache.security.csp.sandbox' => __( 'sandbox:', 'w3-total-cache' ), + 'browsercache.security.csp.child' => __( 'child-src:', 'w3-total-cache' ), + 'browsercache.security.csp.manifest' => __( 'manifest-src:', 'w3-total-cache' ), + 'browsercache.security.csp.scriptelem' => __( 'script-src-elem:', 'w3-total-cache' ), + 'browsercache.security.csp.scriptattr' => __( 'script-src-attr:', 'w3-total-cache' ), + 'browsercache.security.csp.styleelem' => __( 'style-src-elem:', 'w3-total-cache' ), + 'browsercache.security.csp.styleattr' => __( 'style-src-attr:', 'w3-total-cache' ), + 'browsercache.security.csp.worker' => __( 'worker-src:', 'w3-total-cache' ), + 'browsercache.security.csp.default' => __( 'default-src:', 'w3-total-cache' ), + 'browsercache.security.cspro' => __( 'Content Security Policy Report Only', 'w3-total-cache' ), + 'browsercache.security.cspro.reporturi' => __( 'report-uri:', 'w3-total-cache' ), + 'browsercache.security.cspro.reportto' => __( 'report-to:', 'w3-total-cache' ), + 'browsercache.security.cspro.base' => __( 'base-uri:', 'w3-total-cache' ), + 'browsercache.security.cspro.frame' => __( 'frame-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.connect' => __( 'connect-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.font' => __( 'font-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.script' => __( 'script-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.style' => __( 'style-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.img' => __( 'img-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.media' => __( 'media-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.object' => __( 'object-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.plugin' => __( 'plugin-types:', 'w3-total-cache' ), + 'browsercache.security.cspro.form' => __( 'form-action:', 'w3-total-cache' ), 'browsercache.security.cspro.frame.ancestors' => __( 'frame-ancestors:', 'w3-total-cache' ), - 'browsercache.security.cspro.sandbox' => __( 'sandbox:', 'w3-total-cache' ), - 'browsercache.security.cspro.child' => __( 'child-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.manifest' => __( 'manifest-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.sandbox' => __( 'sandbox:', 'w3-total-cache' ), + 'browsercache.security.cspro.child' => __( 'child-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.manifest' => __( 'manifest-src:', 'w3-total-cache' ), 'browsercache.security.cspro.scriptelem' => __( 'script-src-elem:', 'w3-total-cache' ), 'browsercache.security.cspro.scriptattr' => __( 'script-src-attr:', 'w3-total-cache' ), - 'browsercache.security.cspro.styleelem' => __( 'style-src-elem:', 'w3-total-cache' ), - 'browsercache.security.cspro.styleattr' => __( 'style-src-attr:', 'w3-total-cache' ), - 'browsercache.security.cspro.worker' => __( 'worker-src:', 'w3-total-cache' ), - 'browsercache.security.cspro.default' => __( 'default-src:', 'w3-total-cache' ), - ) ); + 'browsercache.security.cspro.styleelem' => __( 'style-src-elem:', 'w3-total-cache' ), + 'browsercache.security.cspro.styleattr' => __( 'style-src-attr:', 'w3-total-cache' ), + 'browsercache.security.cspro.worker' => __( 'worker-src:', 'w3-total-cache' ), + 'browsercache.security.cspro.default' => __( 'default-src:', 'w3-total-cache' ), + ) + ); } } diff --git a/BrowserCache_Core.php b/BrowserCache_Core.php index 95ca19ee4..905d05537 100644 --- a/BrowserCache_Core.php +++ b/BrowserCache_Core.php @@ -1,17 +1,28 @@ get_boolean( 'browsercache.cssjs.replace' ) ) { @@ -33,42 +44,61 @@ public function get_replace_extensions( $config ) { return $extensions; } - - /** * Returns replace extensions * + * @param Config $config Config. + * * @return array */ public function get_replace_querystring_extensions( $config ) { $extensions = array(); - if ( $config->get_boolean( 'browsercache.cssjs.replace' ) ) + if ( $config->get_boolean( 'browsercache.cssjs.replace' ) ) { $this->_fill_extensions( $extensions, $this->_get_cssjs_types(), 'replace' ); - if ( $config->get_boolean( 'browsercache.html.replace' ) ) + } + + if ( $config->get_boolean( 'browsercache.html.replace' ) ) { $this->_fill_extensions( $extensions, $this->_get_html_types(), 'replace' ); - if ( $config->get_boolean( 'browsercache.other.replace' ) ) + } + + if ( $config->get_boolean( 'browsercache.other.replace' ) ) { $this->_fill_extensions( $extensions, $this->_get_other_types(), 'replace' ); + } - if ( $config->get_boolean( 'browsercache.cssjs.querystring' ) ) + if ( $config->get_boolean( 'browsercache.cssjs.querystring' ) ) { $this->_fill_extensions( $extensions, $this->_get_cssjs_types(), 'querystring' ); - if ( $config->get_boolean( 'browsercache.html.querystring' ) ) + } + + if ( $config->get_boolean( 'browsercache.html.querystring' ) ) { $this->_fill_extensions( $extensions, $this->_get_html_types(), 'querystring' ); - if ( $config->get_boolean( 'browsercache.other.querystring' ) ) + } + + if ( $config->get_boolean( 'browsercache.other.querystring' ) ) { $this->_fill_extensions( $extensions, $this->_get_other_types(), 'querystring' ); + } return $extensions; } - - + /** + * Returns replace extensions + * + * @param array $extensions Extensions. + * @param array $types Types. + * @param string $operation Operation. + * + * @return void + */ private function _fill_extensions( &$extensions, $types, $operation ) { foreach ( array_keys( $types ) as $type ) { $type_extensions = explode( '|', $type ); foreach ( $type_extensions as $ext ) { - if ( !isset( $extensions[$ext] ) ) - $extensions[$ext] = array(); - $extensions[$ext][$operation] = true; + if ( ! isset( $extensions[ $ext ] ) ) { + $extensions[ $ext ] = array(); + } + + $extensions[ $ext ][ $operation ] = true; } } } @@ -83,8 +113,6 @@ private function _get_cssjs_types() { return $mime_types; } - - /** * Returns HTML mime types * @@ -95,8 +123,6 @@ private function _get_html_types() { return $mime_types; } - - /** * Returns other mime types * diff --git a/BrowserCache_Environment.php b/BrowserCache_Environment.php index 5fbe49a51..aa35945ad 100644 --- a/BrowserCache_Environment.php +++ b/BrowserCache_Environment.php @@ -1,23 +1,36 @@ exceptions() ) > 0 ) + if ( count( $exs->exceptions() ) > 0 ) { throw $exs; + } } /** * Fixes environment once event occurs * - * @throws Util_Environment_Exceptions + * @param Config $config Config. + * @param string $event Event. + * @param Config $old_config Old config. + * + * @throws Util_Environment_Exceptions Environment Exceptions. */ public function fix_on_event( $config, $event, $old_config = null ) { } @@ -45,21 +63,23 @@ public function fix_on_event( $config, $event, $old_config = null ) { /** * Fixes environment after plugin deactivation * - * @throws Util_Environment_Exceptions + * @throws Util_Environment_Exceptions Environment Exceptions. */ public function fix_after_deactivation() { $exs = new Util_Environment_Exceptions(); $this->rules_cache_remove( $exs ); - if ( count( $exs->exceptions() ) > 0 ) + if ( count( $exs->exceptions() ) > 0 ) { throw $exs; + } } /** * Returns required rules for module * - * @param Config $config + * @param Config $config Config. + * * @return array */ public function get_required_rules( $config ) { @@ -72,26 +92,25 @@ public function get_required_rules( $config ) { switch ( true ) { case Util_Environment::is_apache(): $generator_apache = new BrowserCache_Environment_Apache( $config ); - $rewrite_rules = array( + $rewrite_rules = array( array( 'filename' => Util_Rule::get_apache_rules_path(), - 'content' => - W3TC_MARKER_BEGIN_BROWSERCACHE_CACHE . "\n" . + 'content' => W3TC_MARKER_BEGIN_BROWSERCACHE_CACHE . "\n" . $this->rules_cache_generate_apache( $config ) . $generator_apache->rules_no404wp( $mime_types ) . - W3TC_MARKER_END_BROWSERCACHE_CACHE . "\n" - ) + W3TC_MARKER_END_BROWSERCACHE_CACHE . "\n", + ), ); break; case Util_Environment::is_litespeed(): $generator_litespeed = new BrowserCache_Environment_LiteSpeed( $config ); - $rewrite_rules = $generator_litespeed->get_required_rules( $mime_types ); + $rewrite_rules = $generator_litespeed->get_required_rules( $mime_types ); break; case Util_Environment::is_nginx(): $generator_nginx = new BrowserCache_Environment_Nginx( $config ); - $rewrite_rules = $generator_nginx->get_required_rules( $mime_types ); + $rewrite_rules = $generator_nginx->get_required_rules( $mime_types ); break; default: @@ -140,39 +159,39 @@ public function get_mime_types() { /** * Generate rules for FTP upload * - * @param Config $config + * @param Config $config Config. + * * @return string */ public function rules_cache_generate_for_ftp( $config ) { return $this->rules_cache_generate_apache( $config ); } - - - /* - * rules cache - */ - /** * Writes cache rules * - * @throws Util_WpFile_FilesystemOperationException with S/FTP form if it can't get the required filesystem credentials + * @param Config $config Config. + * @param array $exs Extras. + * + * @throws Util_WpFile_FilesystemOperationException FilesystemOperation Exceptions. + * With S/FTP form if it can't get the required filesystem credentials. */ private function rules_cache_add( $config, $exs ) { $rules = $this->get_required_rules( $config ); foreach ( $rules as $i ) { - Util_Rule::add_rules( $exs, + Util_Rule::add_rules( + $exs, $i['filename'], $i['content'], W3TC_MARKER_BEGIN_BROWSERCACHE_CACHE, W3TC_MARKER_END_BROWSERCACHE_CACHE, array( - W3TC_MARKER_BEGIN_MINIFY_CORE => 0, + W3TC_MARKER_BEGIN_MINIFY_CORE => 0, W3TC_MARKER_BEGIN_PGCACHE_CORE => 0, - W3TC_MARKER_BEGIN_WORDPRESS => 0, - W3TC_MARKER_END_PGCACHE_CACHE => strlen( W3TC_MARKER_END_PGCACHE_CACHE ) + 1, - W3TC_MARKER_END_MINIFY_CACHE => strlen( W3TC_MARKER_END_MINIFY_CACHE ) + 1 + W3TC_MARKER_BEGIN_WORDPRESS => 0, + W3TC_MARKER_END_PGCACHE_CACHE => strlen( W3TC_MARKER_END_PGCACHE_CACHE ) + 1, + W3TC_MARKER_END_MINIFY_CACHE => strlen( W3TC_MARKER_END_MINIFY_CACHE ) + 1, ) ); } @@ -181,31 +200,36 @@ private function rules_cache_add( $config, $exs ) { /** * Removes cache directives * - * @throws Util_WpFile_FilesystemOperationException with S/FTP form if it can't get the required filesystem credentials + * @param array $exs Extras. + * + * @throws Util_WpFile_FilesystemOperationException FilesystemOperation Exceptions. + * With S/FTP form if it can't get the required filesystem credentials. */ private function rules_cache_remove( $exs ) { $filenames = array(); switch ( true ) { - case Util_Environment::is_apache(): - $filenames[] = Util_Rule::get_apache_rules_path(); - break; - - case Util_Environment::is_litespeed(): - $filenames[] = Util_Rule::get_apache_rules_path(); - $filenames[] = Util_Rule::get_litespeed_rules_path(); - break; - - case Util_Environment::is_nginx(): - $filenames[] = Util_Rule::get_nginx_rules_path(); - break; + case Util_Environment::is_apache(): + $filenames[] = Util_Rule::get_apache_rules_path(); + break; + + case Util_Environment::is_litespeed(): + $filenames[] = Util_Rule::get_apache_rules_path(); + $filenames[] = Util_Rule::get_litespeed_rules_path(); + break; + + case Util_Environment::is_nginx(): + $filenames[] = Util_Rule::get_nginx_rules_path(); + break; } foreach ( $filenames as $i ) { - Util_Rule::remove_rules( $exs, + Util_Rule::remove_rules( + $exs, $i, W3TC_MARKER_BEGIN_BROWSERCACHE_CACHE, - W3TC_MARKER_END_BROWSERCACHE_CACHE ); + W3TC_MARKER_END_BROWSERCACHE_CACHE + ); } } @@ -213,6 +237,7 @@ private function rules_cache_remove( $exs ) { * Returns cache rules. * * @param Config $config Configuration. + * * @return string */ private function rules_cache_generate_apache( Config $config ): string { @@ -314,7 +339,7 @@ private function rules_cache_generate_apache( Config $config ): string { // For mod_brotli. $cssjs_brotli = $config->get_boolean( 'browsercache.cssjs.brotli' ); - $html_brotli = $config->get_boolean( 'browsercache.html.brotli' ); + $html_brotli = $config->get_boolean( 'browsercache.html.brotli' ); $other_brotli = $config->get_boolean( 'browsercache.other.brotli' ); if ( $cssjs_brotli || $html_brotli || $other_brotli ) { @@ -366,7 +391,7 @@ private function rules_cache_generate_apache( Config $config ): string { // For mod_deflate. $cssjs_compression = $config->get_boolean( 'browsercache.cssjs.compression' ); - $html_compression = $config->get_boolean( 'browsercache.html.compression' ); + $html_compression = $config->get_boolean( 'browsercache.html.compression' ); $other_compression = $config->get_boolean( 'browsercache.other.compression' ); if ( $cssjs_compression || $html_compression || $other_compression ) { @@ -459,15 +484,15 @@ private function rules_cache_generate_apache( Config $config ): string { // For mod_headers. if ( $config->get_boolean( 'browsercache.hsts' ) || - $config->get_boolean( 'browsercache.security.xfo' ) || - $config->get_boolean( 'browsercache.security.xss' ) || - $config->get_boolean( 'browsercache.security.xcto' ) || - $config->get_boolean( 'browsercache.security.pkp' ) || - $config->get_boolean( 'browsercache.security.referrer.policy' ) || - $config->get_boolean( 'browsercache.security.csp' ) || - $config->get_boolean( 'browsercache.security.cspro' ) || - $config->get_boolean( 'browsercache.security.fp' ) - ) { + $config->get_boolean( 'browsercache.security.xfo' ) || + $config->get_boolean( 'browsercache.security.xss' ) || + $config->get_boolean( 'browsercache.security.xcto' ) || + $config->get_boolean( 'browsercache.security.pkp' ) || + $config->get_boolean( 'browsercache.security.referrer.policy' ) || + $config->get_boolean( 'browsercache.security.csp' ) || + $config->get_boolean( 'browsercache.security.cspro' ) || + $config->get_boolean( 'browsercache.security.fp' ) + ) { $lifetime = $config->get_integer( 'browsercache.other.lifetime' ); // Rules for mod_headers. @@ -506,7 +531,7 @@ private function rules_cache_generate_apache( Config $config ): string { $pinbak = trim( $config->get_string( 'browsercache.security.pkp.pin.backup' ) ); $extra = $config->get_string( 'browsercache.security.pkp.extra' ); $url = trim( $config->get_string( 'browsercache.security.pkp.report.url' ) ); - $rep_only = $config->get_string( 'browsercache.security.pkp.report.only' ) == '1' ? true : false; + $rep_only = '1' === $config->get_string( 'browsercache.security.pkp.report.only' ) ? true : false; $rules_headers .= ' Header set ' . ( $rep_only ? 'Public-Key-Pins-Report-Only' : 'Public-Key-Pins' ) . ' "pin-sha256="$pin"; pin-sha256="$pinbak"; max-age=' . $lifetime . ( strpos( $extra, 'inc' ) ? '; includeSubDomains' : '' ) . ( ! empty( $url ) ? '; report-uri="$url"' : '' ) . "\"\n"; @@ -687,26 +712,25 @@ private function rules_cache_generate_apache( Config $config ): string { /** * Writes cache rules * - * @param Config $config - * @param array $mime_types - * @param string $section + * @param Config $config Config. + * @param array $mime_types Mime types. + * @param string $section Section. + * * @return string */ private function _rules_cache_generate_apache_for_type( $config, $mime_types, $section ) { - $is_disc_enhanced = $config->get_boolean( 'pgcache.enabled' ) && - $config->get_string( 'pgcache.engine' ) == 'file_generic'; - $cache_control = $config->get_boolean( 'browsercache.' . $section . '.cache.control' ); - $etag = $config->get_boolean( 'browsercache.' . $section . '.etag' ); - $w3tc = $config->get_boolean( 'browsercache.' . $section . '.w3tc' ); - $unset_setcookie = $config->get_boolean( 'browsercache.' . $section . '.nocookies' ); + $is_disc_enhanced = $config->get_boolean( 'pgcache.enabled' ) && 'file_generic' === $config->get_string( 'pgcache.engine' ); + $cache_control = $config->get_boolean( 'browsercache.' . $section . '.cache.control' ); + $etag = $config->get_boolean( 'browsercache.' . $section . '.etag' ); + $w3tc = $config->get_boolean( 'browsercache.' . $section . '.w3tc' ); + $unset_setcookie = $config->get_boolean( 'browsercache.' . $section . '.nocookies' ); $set_last_modified = $config->get_boolean( 'browsercache.' . $section . '.last_modified' ); - $compatibility = $config->get_boolean( 'pgcache.compatibility' ); + $compatibility = $config->get_boolean( 'pgcache.compatibility' ); - $mime_types2 = apply_filters( 'w3tc_browsercache_rules_section_extensions', - $mime_types, $config, $section ); - $extensions = array_keys( $mime_types2 ); + $mime_types2 = apply_filters( 'w3tc_browsercache_rules_section_extensions', $mime_types, $config, $section ); + $extensions = array_keys( $mime_types2 ); - // Remove ext from filesmatch if its the same as permalink extension + // Remove ext from filesmatch if its the same as permalink extension. $pext = strtolower( pathinfo( get_option( 'permalink_structure' ), PATHINFO_EXTENSION ) ); if ( $pext ) { $extensions = Util_Rule::remove_extension_from_list( $extensions, $pext ); @@ -715,63 +739,65 @@ private function _rules_cache_generate_apache_for_type( $config, $mime_types, $s $extensions_lowercase = array_map( 'strtolower', $extensions ); $extensions_uppercase = array_map( 'strtoupper', $extensions ); - $rules = ''; + $rules = ''; $headers_rules = ''; if ( $cache_control ) { $cache_policy = $config->get_string( 'browsercache.' . $section . '.cache.policy' ); switch ( $cache_policy ) { - case 'cache': - $headers_rules .= " Header set Pragma \"public\"\n"; - $headers_rules .= " Header set Cache-Control \"public\"\n"; - break; + case 'cache': + $headers_rules .= " Header set Pragma \"public\"\n"; + $headers_rules .= " Header set Cache-Control \"public\"\n"; + break; - case 'cache_public_maxage': - $expires = $config->get_boolean( 'browsercache.' . $section . '.expires' ); - $lifetime = $config->get_integer( 'browsercache.' . $section . '.lifetime' ); + case 'cache_public_maxage': + $expires = $config->get_boolean( 'browsercache.' . $section . '.expires' ); + $lifetime = $config->get_integer( 'browsercache.' . $section . '.lifetime' ); - $headers_rules .= " Header set Pragma \"public\"\n"; + $headers_rules .= " Header set Pragma \"public\"\n"; - if ( $expires ) - $headers_rules .= " Header append Cache-Control \"public\"\n"; - else - $headers_rules .= " Header set Cache-Control \"max-age=" . $lifetime . ", public\"\n"; + if ( $expires ) { + $headers_rules .= " Header append Cache-Control \"public\"\n"; + } else { + $headers_rules .= " Header set Cache-Control \"max-age=" . $lifetime . ", public\"\n"; + } - break; + break; - case 'cache_validation': - $headers_rules .= " Header set Pragma \"public\"\n"; - $headers_rules .= " Header set Cache-Control \"public, must-revalidate, proxy-revalidate\"\n"; - break; + case 'cache_validation': + $headers_rules .= " Header set Pragma \"public\"\n"; + $headers_rules .= " Header set Cache-Control \"public, must-revalidate, proxy-revalidate\"\n"; + break; - case 'cache_noproxy': - $headers_rules .= " Header set Pragma \"public\"\n"; - $headers_rules .= " Header set Cache-Control \"private, must-revalidate\"\n"; - break; + case 'cache_noproxy': + $headers_rules .= " Header set Pragma \"public\"\n"; + $headers_rules .= " Header set Cache-Control \"private, must-revalidate\"\n"; + break; - case 'cache_maxage': - $expires = $config->get_boolean( 'browsercache.' . $section . '.expires' ); - $lifetime = $config->get_integer( 'browsercache.' . $section . '.lifetime' ); + case 'cache_maxage': + $expires = $config->get_boolean( 'browsercache.' . $section . '.expires' ); + $lifetime = $config->get_integer( 'browsercache.' . $section . '.lifetime' ); - $headers_rules .= " Header set Pragma \"public\"\n"; + $headers_rules .= " Header set Pragma \"public\"\n"; - if ( $expires ) - $headers_rules .= " Header append Cache-Control \"public, must-revalidate, proxy-revalidate\"\n"; - else - $headers_rules .= " Header set Cache-Control \"max-age=" . $lifetime . ", public, must-revalidate, proxy-revalidate\"\n"; + if ( $expires ) { + $headers_rules .= " Header append Cache-Control \"public, must-revalidate, proxy-revalidate\"\n"; + } else { + $headers_rules .= " Header set Cache-Control \"max-age=" . $lifetime . ", public, must-revalidate, proxy-revalidate\"\n"; + } - break; + break; - case 'no_cache': - $headers_rules .= " Header set Pragma \"no-cache\"\n"; - $headers_rules .= " Header set Cache-Control \"private, no-cache\"\n"; - break; + case 'no_cache': + $headers_rules .= " Header set Pragma \"no-cache\"\n"; + $headers_rules .= " Header set Cache-Control \"private, no-cache\"\n"; + break; - case 'no_store': - $headers_rules .= " Header set Pragma \"no-store\"\n"; - $headers_rules .= " Header set Cache-Control \"no-store\"\n"; - break; + case 'no_store': + $headers_rules .= " Header set Pragma \"no-store\"\n"; + $headers_rules .= " Header set Cache-Control \"no-store\"\n"; + break; } } @@ -779,20 +805,22 @@ private function _rules_cache_generate_apache_for_type( $config, $mime_types, $s $rules .= " FileETag MTime Size\n"; } else { if ( $compatibility ) { - $rules .= " FileETag None\n"; + $rules .= " FileETag None\n"; $headers_rules .= " Header unset ETag\n"; } } - if ( $unset_setcookie ) + if ( $unset_setcookie ) { $headers_rules .= " Header unset Set-Cookie\n"; + } - if ( !$set_last_modified ) + if ( ! $set_last_modified ) { $headers_rules .= " Header unset Last-Modified\n"; + } - if ( $w3tc ) - $headers_rules .= " Header set X-Powered-By \"" . - Util_Environment::w3tc_header() . "\"\n"; + if ( $w3tc ) { + $headers_rules .= " Header set X-Powered-By \"" . Util_Environment::w3tc_header() . "\"\n"; + } if ( strlen( $headers_rules ) > 0 ) { $rules .= " \n"; @@ -801,22 +829,24 @@ private function _rules_cache_generate_apache_for_type( $config, $mime_types, $s } if ( strlen( $rules ) > 0 ) { - $rules = "\n" . $rules; + $rules = "\n" . $rules; $rules .= "\n"; } return $rules; } - /* - * rules_no404wp + /** + * Return CDN rules section + * + * @param array $section_rules Section rules. + * @param Config $config Config. + * + * @return array */ - public function w3tc_cdn_rules_section( $section_rules, $config ) { if ( Util_Environment::is_litespeed() ) { - $o = new BrowserCache_Environment_LiteSpeed( $config ); + $o = new BrowserCache_Environment_LiteSpeed( $config ); $section_rules = $o->w3tc_cdn_rules_section( $section_rules ); } diff --git a/BrowserCache_Environment_Apache.php b/BrowserCache_Environment_Apache.php index 280d4aaae..e716ef685 100644 --- a/BrowserCache_Environment_Apache.php +++ b/BrowserCache_Environment_Apache.php @@ -1,34 +1,56 @@ c = $config; } - - + /** + * Rules rewrite + * + * @return string + */ public function rules_rewrite() { if ( ! $this->c->get_boolean( 'browsercache.rewrite' ) ) { return ''; } - $core = Dispatcher::component( 'BrowserCache_Core' ); + $core = Dispatcher::component( 'BrowserCache_Core' ); $extensions = $core->get_replace_extensions( $this->c ); - $rules = array(); + $rules = array(); $rules[] = ''; $rules[] = ' RewriteCond %{REQUEST_FILENAME} !-f'; - $rules[] = ' RewriteRule ^(.+)\.(x[0-9]{5})\.(' . - implode( '|', $extensions ) . ')$ $1.$3 [L]'; + $rules[] = ' RewriteRule ^(.+)\.(x[0-9]{5})\.(' . implode( '|', $extensions ) . ')$ $1.$3 [L]'; $rules[] = ''; $rules[] = ''; @@ -38,7 +60,8 @@ public function rules_rewrite() { /** * Generate rules related to prevent for media 404 error by WP * - * @param Config $config + * @param array $mime_types Mime types. + * * @return string */ public function rules_no404wp( $mime_types ) { @@ -47,57 +70,52 @@ public function rules_no404wp( $mime_types ) { } $cssjs_types = $mime_types['cssjs']; - $html_types = $mime_types['html']; + $html_types = $mime_types['html']; $other_types = $mime_types['other']; - $extensions = array_merge( array_keys( $cssjs_types ), - array_keys( $html_types ), array_keys( $other_types ) ); + $extensions = array_merge( array_keys( $cssjs_types ), array_keys( $html_types ), array_keys( $other_types ) ); - $permalink_structure = get_option( 'permalink_structure' ); - $permalink_structure_ext = ltrim( strrchr( $permalink_structure, '.' ), - '.' ); + $permalink_structure = get_option( 'permalink_structure' ); + $permalink_structure_ext = ltrim( strrchr( $permalink_structure, '.' ), '.' ); - if ( $permalink_structure_ext != '' ) { + if ( '' !== $permalink_structure_ext ) { foreach ( $extensions as $index => $extension ) { if ( strstr( $extension, $permalink_structure_ext ) !== false ) { - $extensions[$index] = preg_replace( '~\|?' . - Util_Environment::preg_quote( $permalink_structure_ext ) . - '\|?~', '', $extension ); + $extensions[ $index ] = preg_replace( '~\|?' . Util_Environment::preg_quote( $permalink_structure_ext ) . '\|?~', '', $extension ); } } } $exceptions = $this->c->get_array( 'browsercache.no404wp.exceptions' ); + $wp_uri = network_home_url( '', 'relative' ); $wp_uri = rtrim( $wp_uri, '/' ); - $rules = ''; + $rules = ''; $rules .= "\n"; $rules .= " RewriteEngine On\n"; - // in subdir - rewrite theme files and similar to upper folder if file exists - if ( Util_Environment::is_wpmu() && - !Util_Environment::is_wpmu_subdomain() ) { + // in subdir - rewrite theme files and similar to upper folder if file exists. + if ( Util_Environment::is_wpmu() && ! Util_Environment::is_wpmu_subdomain() ) { + $document_root = Util_Rule::apache_docroot_variable(); + $rules .= " RewriteCond %{REQUEST_FILENAME} !-f\n"; $rules .= " RewriteCond %{REQUEST_FILENAME} !-d\n"; - $rules .= " RewriteCond %{REQUEST_URI} ^$wp_uri/([_0-9a-zA-Z-]+/)(.*\.)(" . - implode( '|', $extensions ) . ")$ [NC]\n"; - $document_root = Util_Rule::apache_docroot_variable(); - $rules .= ' RewriteCond "' . $document_root . $wp_uri . - '/%2%3" -f' . "\n"; + $rules .= " RewriteCond %{REQUEST_URI} ^$wp_uri/([_0-9a-zA-Z-]+/)(.*\.)(" . implode( '|', $extensions ) . ")$ [NC]\n"; + $rules .= ' RewriteCond "' . $document_root . $wp_uri . '/%2%3" -f' . "\n"; $rules .= " RewriteRule .* $wp_uri/%2%3 [L]\n\n"; } - $rules .= " RewriteCond %{REQUEST_FILENAME} !-f\n"; $rules .= " RewriteCond %{REQUEST_FILENAME} !-d\n"; $imploded = implode( '|', $exceptions ); - if ( !empty( $imploded ) ) - $rules .= " RewriteCond %{REQUEST_URI} !(" . $imploded. ")\n"; - $rules .= " RewriteCond %{REQUEST_URI} \\.(" . - implode( '|', $extensions ) . ")$ [NC]\n"; + if ( ! empty( $imploded ) ) { + $rules .= " RewriteCond %{REQUEST_URI} !(" . $imploded . ")\n"; + } + + $rules .= " RewriteCond %{REQUEST_URI} \\.(" . implode( '|', $extensions ) . ")$ [NC]\n"; $rules .= " RewriteRule .* - [L]\n"; $rules .= "\n"; diff --git a/BrowserCache_Environment_LiteSpeed.php b/BrowserCache_Environment_LiteSpeed.php index c0a2922e6..a6459bf32 100644 --- a/BrowserCache_Environment_LiteSpeed.php +++ b/BrowserCache_Environment_LiteSpeed.php @@ -1,57 +1,84 @@ c = $config; } - - + /** + * Get required rules + * + * @param array $mime_types Mime types. + * + * @return string + */ public function get_required_rules( $mime_types ) { $rewrite_rules = array(); $rewrite_rules[] = array( 'filename' => Util_Rule::get_litespeed_rules_path(), - 'content' => $this->generate( $mime_types ) + 'content' => $this->generate( $mime_types ), ); - if ( $this->c->get_boolean( 'browsercache.rewrite' ) || - $this->c->get_boolean( 'browsercache.no404wp' ) ) { - $g = new BrowserCache_Environment_Apache( $this->c ); + if ( $this->c->get_boolean( 'browsercache.rewrite' ) || $this->c->get_boolean( 'browsercache.no404wp' ) ) { + $g = new BrowserCache_Environment_Apache( $this->c ); $rewrite_rules[] = array( 'filename' => Util_Rule::get_apache_rules_path(), - 'content' => + 'content' => W3TC_MARKER_BEGIN_BROWSERCACHE_CACHE . "\n" . $g->rules_rewrite() . $g->rules_no404wp( $mime_types ) . - W3TC_MARKER_END_BROWSERCACHE_CACHE . "\n" + W3TC_MARKER_END_BROWSERCACHE_CACHE . "\n", ); } return $rewrite_rules; } - - /** - * Returns cache rules + * Generate cache rules + * + * @param array $mime_types Mime types. + * @param bool $cdnftp CDN FTP flag. + * + * @return array */ public function generate( $mime_types, $cdnftp = false ) { - $cssjs_types = $mime_types['cssjs']; - $cssjs_types = array_unique( $cssjs_types ); - $html_types = $mime_types['html']; - $other_types = $mime_types['other']; + $cssjs_types = $mime_types['cssjs']; + $cssjs_types = array_unique( $cssjs_types ); + $html_types = $mime_types['html']; + $other_types = $mime_types['other']; $other_compression_types = $mime_types['other_compression']; - $rules = ''; + $rules = ''; $rules .= W3TC_MARKER_BEGIN_BROWSERCACHE_CACHE . "\n"; $this->generate_section( $rules, $mime_types['cssjs'], 'cssjs' ); @@ -59,13 +86,12 @@ public function generate( $mime_types, $cdnftp = false ) { $this->generate_section( $rules, $mime_types['other'], 'other' ); if ( $this->c->get_boolean( 'browsercache.rewrite' ) ) { - $core = Dispatcher::component( 'BrowserCache_Core' ); + $core = Dispatcher::component( 'BrowserCache_Core' ); $extensions = $core->get_replace_extensions( $this->c ); $rules .= "\n"; $rules .= " RewriteCond %{REQUEST_FILENAME} !-f\n"; - $rules .= ' RewriteRule ^(.+)\.(x[0-9]{5})\.(' . - implode( '|', $extensions ) . ')$ $1.$3 [L]' . "\n"; + $rules .= ' RewriteRule ^(.+)\.(x[0-9]{5})\.(' . implode( '|', $extensions ) . ')$ $1.$3 [L]' . "\n"; $rules .= "\n"; } @@ -74,14 +100,13 @@ public function generate( $mime_types, $cdnftp = false ) { return $rules; } - - /** * Adds cache rules for type to &$rules. * * @param string $rules Rules. * @param array $mime_types MIME types. * @param string $section Section. + * * @return void */ private function generate_section( &$rules, $mime_types, $section ) { @@ -97,7 +122,8 @@ private function generate_section( &$rules, $mime_types, $section ) { $this->c, $section ); - $extensions = array_keys( $mime_types2 ); + + $extensions = array_keys( $mime_types2 ); // Remove ext from filesmatch if its the same as permalink extension. $pext = strtolower( pathinfo( get_option( 'permalink_structure' ), PATHINFO_EXTENSION ) ); @@ -108,14 +134,12 @@ private function generate_section( &$rules, $mime_types, $section ) { $extensions_string = implode( '|', $extensions ); - $section_rules = self::section_rules( $section ); - $section_rules = apply_filters( 'w3tc_browsercache_rules_section', - $section_rules, $this->c, $section ); + $section_rules = apply_filters( 'w3tc_browsercache_rules_section', $section_rules, $this->c, $section ); $context_rules = $section_rules['other']; - if ( !empty( $section_rules['add_header'] ) ) { + if ( ! empty( $section_rules['add_header'] ) ) { $context_rules[] = " extraHeaders <<c->get_boolean( "browsercache.$section.expires" ); + $expires = $this->c->get_boolean( "browsercache.$section.expires" ); $lifetime = $this->c->get_integer( "browsercache.$section.lifetime" ); if ( $expires ) { @@ -156,8 +183,8 @@ public function section_rules( $section ) { } /* + Lastmod support not implemented if ( $this->c->get_boolean( "browsercache.$section.last_modified" ) ) - lastmod support not implemented */ $add_header_rules = array(); @@ -165,72 +192,81 @@ public function section_rules( $section ) { $cache_policy = $this->c->get_string( "browsercache.$section.cache.policy" ); switch ( $cache_policy ) { - case 'cache': - $add_header_rules[] = 'unset Pragma'; - $add_header_rules[] = 'set Pragma public'; - $add_header_rules[] = 'set Cache-Control public'; - break; - - case 'cache_public_maxage': - $add_header_rules[] = 'unset Pragma'; - $add_header_rules[] = 'set Pragma public'; - break; - - case 'cache_validation': - $add_header_rules[] = 'unset Pragma'; - $add_header_rules[] = 'set Pragma public'; - $add_header_rules[] = 'unset Cache-Control'; - $add_header_rules[] = 'set Cache-Control "public, must-revalidate, proxy-revalidate"'; - break; - - case 'cache_noproxy': - $add_header_rules[] = 'unset Pragma'; - $add_header_rules[] = 'set Pragma public'; - $add_header_rules[] = 'unset Cache-Control'; - $add_header_rules[] = 'set Cache-Control "private, must-revalidate"'; - break; - - case 'cache_maxage': - $add_header_rules[] = 'unset Pragma'; - $add_header_rules[] = 'set Pragma "public"'; - - $add_header_rules[] = 'unset Cache-Control'; - if ( $expires ) { + case 'cache': + $add_header_rules[] = 'unset Pragma'; + $add_header_rules[] = 'set Pragma public'; + $add_header_rules[] = 'set Cache-Control public'; + break; + + case 'cache_public_maxage': + $add_header_rules[] = 'unset Pragma'; + $add_header_rules[] = 'set Pragma public'; + break; + + case 'cache_validation': + $add_header_rules[] = 'unset Pragma'; + $add_header_rules[] = 'set Pragma public'; + $add_header_rules[] = 'unset Cache-Control'; $add_header_rules[] = 'set Cache-Control "public, must-revalidate, proxy-revalidate"'; - } else { - $add_header_rules[] = "set Cache-Control \"max-age=$lifetime, public, must-revalidate, proxy-revalidate\""; - } - break; - - case 'no_cache': - $add_header_rules[] = 'unset Pragma'; - $add_header_rules[] = 'set Pragma "no-cache"'; - $add_header_rules[] = 'unset Cache-Control'; - $add_header_rules[] = 'set Cache-Control "private, no-cache"'; - break; - - case 'no_store': - $add_header_rules[] = 'unset Pragma'; - $add_header_rules[] = 'set Pragma "no-store"'; - $add_header_rules[] = 'unset Cache-Control'; - $add_header_rules[] = 'set Cache-Control "no-store"'; - break; + break; + + case 'cache_noproxy': + $add_header_rules[] = 'unset Pragma'; + $add_header_rules[] = 'set Pragma public'; + $add_header_rules[] = 'unset Cache-Control'; + $add_header_rules[] = 'set Cache-Control "private, must-revalidate"'; + break; + + case 'cache_maxage': + $add_header_rules[] = 'unset Pragma'; + $add_header_rules[] = 'set Pragma "public"'; + + $add_header_rules[] = 'unset Cache-Control'; + + if ( $expires ) { + $add_header_rules[] = 'set Cache-Control "public, must-revalidate, proxy-revalidate"'; + } else { + $add_header_rules[] = "set Cache-Control \"max-age=$lifetime, public, must-revalidate, proxy-revalidate\""; + } + break; + + case 'no_cache': + $add_header_rules[] = 'unset Pragma'; + $add_header_rules[] = 'set Pragma "no-cache"'; + $add_header_rules[] = 'unset Cache-Control'; + $add_header_rules[] = 'set Cache-Control "private, no-cache"'; + break; + + case 'no_store': + $add_header_rules[] = 'unset Pragma'; + $add_header_rules[] = 'set Pragma "no-store"'; + $add_header_rules[] = 'unset Cache-Control'; + $add_header_rules[] = 'set Cache-Control "no-store"'; + break; } } - // need htaccess for rewrites + // Need htaccess for rewrites. $rewrite = $this->c->get_boolean( 'browsercache.rewrite' ); - return array( 'add_header' => $add_header_rules, 'other' => $rules, 'rewrite' => $rewrite ); + return array( + 'add_header' => $add_header_rules, + 'other' => $rules, + 'rewrite' => $rewrite, + ); } - - + /** + * Returns CDN rules section + * + * @param array $section_rules Section rules. + * + * @return array + */ public function w3tc_cdn_rules_section( $section_rules ) { - $section_rules_bc = $this->section_rules( 'other' ); - $section_rules['other'] = array_merge( $section_rules['other'], $section_rules_bc['other'] ); - $section_rules['add_header'] = array_merge( - $section_rules['add_header'], $section_rules_bc['add_header'] ); + $section_rules_bc = $this->section_rules( 'other' ); + $section_rules['other'] = array_merge( $section_rules['other'], $section_rules_bc['other'] ); + $section_rules['add_header'] = array_merge( $section_rules['add_header'], $section_rules_bc['add_header'] ); return $section_rules; } diff --git a/BrowserCache_Environment_Nginx.php b/BrowserCache_Environment_Nginx.php index 4fc07f247..5688992b1 100644 --- a/BrowserCache_Environment_Nginx.php +++ b/BrowserCache_Environment_Nginx.php @@ -1,20 +1,45 @@ c = $config; } - - + /** + * Returns required rules + * + * @param array $mime_types Mime types. + * + * @return array + */ public function get_required_rules( $mime_types ) { return array( array( @@ -24,46 +49,45 @@ public function get_required_rules( $mime_types ) { ); } - - /** * Returns cache rules + * + * @param array $mime_types Mime types. + * @param bool $cdnftp CDN FTP flag. + * + * @return string */ public function generate( $mime_types, $cdnftp = false ) { - $cssjs_types = $mime_types['cssjs']; - $cssjs_types = array_unique( $cssjs_types ); - $html_types = $mime_types['html']; - $other_types = $mime_types['other']; + $cssjs_types = $mime_types['cssjs']; + $cssjs_types = array_unique( $cssjs_types ); + $html_types = $mime_types['html']; + $other_types = $mime_types['other']; $other_compression_types = $mime_types['other_compression']; - $rules = ''; + $rules = ''; $rules .= W3TC_MARKER_BEGIN_BROWSERCACHE_CACHE . "\n"; if ( $this->c->get_boolean( 'browsercache.rewrite' ) ) { - $core = Dispatcher::component( 'BrowserCache_Core' ); + $core = Dispatcher::component( 'BrowserCache_Core' ); $extensions = $core->get_replace_extensions( $this->c ); $exts = implode( '|', $extensions ); $rules .= "set \$w3tcbc_rewrite_filename '';\n"; $rules .= "set \$w3tcbc_rewrite_uri '';\n"; - $rules .= "if (\$uri ~ '^(?.+)\.(x[0-9]{5})" . - "(?\.($exts))$') {\n"; + $rules .= "if (\$uri ~ '^(?.+)\.(x[0-9]{5})(?\.($exts))$') {\n"; $rules .= " set \$w3tcbc_rewrite_filename \$document_root\$w3tcbc_base\$w3tcbc_ext;\n"; $rules .= " set \$w3tcbc_rewrite_uri \$w3tcbc_base\$w3tcbc_ext;\n"; $rules .= "}\n"; - if ( Util_Environment::is_wpmu() && - !Util_Environment::is_wpmu_subdomain() ) { - // WPMU subdir extra rewrite - + if ( Util_Environment::is_wpmu() && ! Util_Environment::is_wpmu_subdomain() ) { + // WPMU subdir extra rewrite. if ( defined( 'W3TC_HOME_URI' ) ) { $home_uri = W3TC_HOME_URI; } else { $primary_blog_id = get_network()->site_id; - $home_uri = parse_url( get_home_url( $primary_blog_id ), - PHP_URL_PATH ); - $home_uri = rtrim( $home_uri, '/' ); + $home_uri = wp_parse_url( get_home_url( $primary_blog_id ), PHP_URL_PATH ); + $home_uri = rtrim( $home_uri, '/' ); } $rules .= "if (\$uri ~ '^$home_uri/[_0-9a-zA-Z-]+(?/wp-.+)\.(x[0-9]{5})(?\.($exts))$') {\n"; @@ -78,7 +102,7 @@ public function generate( $mime_types, $cdnftp = false ) { } $cssjs_brotli = $this->c->get_boolean( 'browsercache.cssjs.brotli' ); - $html_brotli = $this->c->get_boolean( 'browsercache.html.brotli' ); + $html_brotli = $this->c->get_boolean( 'browsercache.html.brotli' ); $other_brotli = $this->c->get_boolean( 'browsercache.other.brotli' ); if ( $cssjs_brotli || $html_brotli || $other_brotli ) { @@ -93,22 +117,20 @@ public function generate( $mime_types, $cdnftp = false ) { } if ( $other_brotli ) { - $brotli_types = array_merge( $brotli_types, - $other_compression_types ); + $brotli_types = array_merge( $brotli_types, $other_compression_types ); } unset( $brotli_types['html|htm'] ); - // some nginx cant handle values longer than 47 chars + // some nginx cant handle values longer than 47 chars. unset( $brotli_types['odp'] ); $rules .= "brotli on;\n"; - $rules .= 'brotli_types ' . - implode( ' ', array_unique( $brotli_types ) ) . ";\n"; + $rules .= 'brotli_types ' . implode( ' ', array_unique( $brotli_types ) ) . ";\n"; } $cssjs_compression = $this->c->get_boolean( 'browsercache.cssjs.compression' ); - $html_compression = $this->c->get_boolean( 'browsercache.html.compression' ); + $html_compression = $this->c->get_boolean( 'browsercache.html.compression' ); $other_compression = $this->c->get_boolean( 'browsercache.other.compression' ); if ( $cssjs_compression || $html_compression || $other_compression ) { @@ -123,31 +145,28 @@ public function generate( $mime_types, $cdnftp = false ) { } if ( $other_compression ) { - $compression_types = array_merge( $compression_types, - $other_compression_types ); + $compression_types = array_merge( $compression_types, $other_compression_types ); } unset( $compression_types['html|htm'] ); - // some nginx cant handle values longer than 47 chars + // some nginx cant handle values longer than 47 chars. unset( $compression_types['odp'] ); $rules .= "gzip on;\n"; - $rules .= "gzip_types " . - implode( ' ', array_unique( $compression_types ) ) . ";\n"; + $rules .= "gzip_types " . implode( ' ', array_unique( $compression_types ) ) . ";\n"; } if ( $this->c->get_boolean( 'browsercache.no404wp' ) ) { $exceptions = $this->c->get_array( 'browsercache.no404wp.exceptions' ); $impoloded = implode( '|', $exceptions ); - if ( !empty( $impoloded ) ) { + if ( ! empty( $impoloded ) ) { $wp_uri = network_home_url( '', 'relative' ); $wp_uri = rtrim( $wp_uri, '/' ); $rules .= "location ~ (" . $impoloded . ") {\n"; - $rules .= ' try_files $uri $uri/ ' . $wp_uri . - '/index.php?$args;' . "\n"; + $rules .= ' try_files $uri $uri/ ' . $wp_uri . '/index.php?$args;' . "\n"; $rules .= "}\n"; } } @@ -162,13 +181,13 @@ public function generate( $mime_types, $cdnftp = false ) { return $rules; } - - /** * Returns security header directives + * + * @return array */ private function security_rules() { - $rules = []; + $rules = array(); if ( $this->c->get_boolean( 'browsercache.hsts' ) || $this->c->get_boolean( 'browsercache.security.xfo' ) || @@ -179,12 +198,12 @@ private function security_rules() { $this->c->get_boolean( 'browsercache.security.csp' ) || $this->c->get_boolean( 'browsercache.security.cspro' ) || $this->c->get_boolean( 'browsercache.security.fp' ) - ) { + ) { $lifetime = $this->c->get_integer( 'browsercache.other.lifetime' ); if ( $this->c->get_boolean( 'browsercache.hsts' ) ) { - $dir = $this->c->get_string( 'browsercache.security.hsts.directive' ); - $rules[] = "add_header Strict-Transport-Security \"max-age=$lifetime" . ( strpos( $dir,"inc" ) ? "; includeSubDomains" : "" ) . ( strpos( $dir, "pre" ) ? "; preload" : "" ) . "\";"; + $dir = $this->c->get_string( 'browsercache.security.hsts.directive' ); + $rules[] = "add_header Strict-Transport-Security \"max-age=$lifetime" . ( strpos( $dir, "inc" ) ? "; includeSubDomains" : "" ) . ( strpos( $dir, "pre" ) ? "; preload" : "" ) . "\";"; } if ( $this->c->get_boolean( 'browsercache.security.xfo' ) ) { @@ -193,12 +212,12 @@ private function security_rules() { if ( empty( $url ) ) { $url = Util_Environment::home_url_maybe_https(); } - $rules[] = "add_header X-Frame-Options \"" . ( $dir == "same" ? "SAMEORIGIN" : ( $dir == "deny" ? "DENY" : "ALLOW-FROM $url" ) ) . "\";"; + $rules[] = "add_header X-Frame-Options \"" . ( 'same' === $dir ? "SAMEORIGIN" : ( 'deny' === $dir ? "DENY" : "ALLOW-FROM $url" ) ) . "\";"; } if ( $this->c->get_boolean( 'browsercache.security.xss' ) ) { - $dir = $this->c->get_string( 'browsercache.security.xss.directive' ); - $rules[] = "add_header X-XSS-Protection \"" . ( $dir == "block" ? "1; mode=block" : $dir ) . "\";"; + $dir = $this->c->get_string( 'browsercache.security.xss.directive' ); + $rules[] = "add_header X-XSS-Protection \"" . ( 'block' === $dir ? "1; mode=block" : $dir ) . "\";"; } if ( $this->c->get_boolean( 'browsercache.security.xcto' ) ) { @@ -206,17 +225,17 @@ private function security_rules() { } if ( $this->c->get_boolean( 'browsercache.security.pkp' ) ) { - $pin = trim( $this->c->get_string( 'browsercache.security.pkp.pin' ) ); - $pinbak = trim( $this->c->get_string( 'browsercache.security.pkp.pin.backup' ) ); - $extra = $this->c->get_string( 'browsercache.security.pkp.extra' ); - $url = trim( $this->c->get_string( 'browsercache.security.pkp.report.url' ) ); - $rep_only = $this->c->get_string( 'browsercache.security.pkp.report.only' ) == '1' ? true : false; - $rules[] = "add_header " . ( $rep_only ? "Public-Key-Pins-Report-Only" : "Public-Key-Pins" ) . " 'pin-sha256=\"$pin\"; pin-sha256=\"$pinbak\"; max-age=$lifetime" . ( strpos( $extra,"inc" ) ? "; includeSubDomains" : "" ) . ( !empty( $url ) ? "; report-uri=\"$url\"" : "" ) . "';"; + $pin = trim( $this->c->get_string( 'browsercache.security.pkp.pin' ) ); + $pinbak = trim( $this->c->get_string( 'browsercache.security.pkp.pin.backup' ) ); + $extra = $this->c->get_string( 'browsercache.security.pkp.extra' ); + $url = trim( $this->c->get_string( 'browsercache.security.pkp.report.url' ) ); + $rep_only = '1' === $this->c->get_string( 'browsercache.security.pkp.report.only' ) ? true : false; + $rules[] = "add_header " . ( $rep_only ? "Public-Key-Pins-Report-Only" : "Public-Key-Pins" ) . " 'pin-sha256=\"$pin\"; pin-sha256=\"$pinbak\"; max-age=$lifetime" . ( strpos( $extra, "inc" ) ? "; includeSubDomains" : "" ) . ( ! empty( $url ) ? "; report-uri=\"$url\"" : "" ) . "';"; } if ( $this->c->get_boolean( 'browsercache.security.referrer.policy' ) ) { - $dir = $this->c->get_string( 'browsercache.security.referrer.policy.directive' ); - $rules[] = "add_header Referrer-Policy \"" . ( $dir == "0" ? "" : $dir ) . "\";"; + $dir = $this->c->get_string( 'browsercache.security.referrer.policy.directive' ); + $rules[] = "add_header Referrer-Policy \"" . ( '0' === $dir ? "" : $dir ) . "\";"; } if ( $this->c->get_boolean( 'browsercache.security.csp' ) ) { @@ -362,6 +381,7 @@ private function security_rules() { * @param string $rules Rules. * @param array $mime_types MIME types. * @param string $section Section. + * * @return void */ private function generate_section( &$rules, $mime_types, $section ) { @@ -421,16 +441,19 @@ private function generate_section( &$rules, $mime_types, $section ) { } /** - * Returns directives plugin applies to files of specific section - * Without location + * Returns directives plugin applies to files of specific section without location + * + * $extra_add_headers_set specifies if other add_header directives will be added to location block generated * - * $extra_add_headers_set specifies if other add_header directives will - * be added to location block generated + * @param string $section Section. + * @param bool $extra_add_headers_set Extra add headers flag. + * + * @return array */ public function section_rules( $section, $extra_add_headers_set = false ) { $rules = array(); - $expires = $this->c->get_boolean( "browsercache.$section.expires" ); + $expires = $this->c->get_boolean( "browsercache.$section.expires" ); $lifetime = $this->c->get_integer( "browsercache.$section.lifetime" ); if ( $expires ) { @@ -454,63 +477,64 @@ public function section_rules( $section, $extra_add_headers_set = false ) { $cache_policy = $this->c->get_string( "browsercache.$section.cache.policy" ); switch ( $cache_policy ) { - case 'cache': - $add_header_rules[] = 'add_header Pragma "public";'; - $add_header_rules[] = 'add_header Cache-Control "public";'; - break; + case 'cache': + $add_header_rules[] = 'add_header Pragma "public";'; + $add_header_rules[] = 'add_header Cache-Control "public";'; + break; - case 'cache_public_maxage': - $add_header_rules[] = 'add_header Pragma "public";'; + case 'cache_public_maxage': + $add_header_rules[] = 'add_header Pragma "public";'; - if ( $expires ) { - $add_header_rules[] = 'add_header Cache-Control "public";'; - } else { - $add_header_rules[] = "add_header Cache-Control \"max-age=$lifetime, public\";"; - } - break; + if ( $expires ) { + $add_header_rules[] = 'add_header Cache-Control "public";'; + } else { + $add_header_rules[] = "add_header Cache-Control \"max-age=$lifetime, public\";"; + } + break; - case 'cache_validation': - $add_header_rules[] = 'add_header Pragma "public";'; - $add_header_rules[] = 'add_header Cache-Control "public, must-revalidate, proxy-revalidate";'; - break; + case 'cache_validation': + $add_header_rules[] = 'add_header Pragma "public";'; + $add_header_rules[] = 'add_header Cache-Control "public, must-revalidate, proxy-revalidate";'; + break; - case 'cache_noproxy': - $add_header_rules[] = 'add_header Pragma "public";'; - $add_header_rules[] = 'add_header Cache-Control "private, must-revalidate";'; - break; + case 'cache_noproxy': + $add_header_rules[] = 'add_header Pragma "public";'; + $add_header_rules[] = 'add_header Cache-Control "private, must-revalidate";'; + break; - case 'cache_maxage': - $add_header_rules[] = 'add_header Pragma "public";'; + case 'cache_maxage': + $add_header_rules[] = 'add_header Pragma "public";'; - if ( $expires ) { - $add_header_rules[] = 'add_header Cache-Control "public, must-revalidate, proxy-revalidate";'; - } else { - $add_header_rules[] = "add_header Cache-Control \"max-age=$lifetime, public, must-revalidate, proxy-revalidate\";"; - } - break; + if ( $expires ) { + $add_header_rules[] = 'add_header Cache-Control "public, must-revalidate, proxy-revalidate";'; + } else { + $add_header_rules[] = "add_header Cache-Control \"max-age=$lifetime, public, must-revalidate, proxy-revalidate\";"; + } + break; - case 'no_cache': - $add_header_rules[] = 'add_header Pragma "no-cache";'; - $add_header_rules[] = 'add_header Cache-Control "private, no-cache";'; - break; + case 'no_cache': + $add_header_rules[] = 'add_header Pragma "no-cache";'; + $add_header_rules[] = 'add_header Cache-Control "private, no-cache";'; + break; - case 'no_store': - $add_header_rules[] = 'add_header Pragma "no-store";'; - $add_header_rules[] = 'add_header Cache-Control "no-store";'; - break; + case 'no_store': + $add_header_rules[] = 'add_header Pragma "no-store";'; + $add_header_rules[] = 'add_header Cache-Control "no-store";'; + break; } } if ( $this->c->get_boolean( "browsercache.$section.w3tc" ) ) { - $add_header_rules[] = 'add_header X-Powered-By "' . - Util_Environment::w3tc_header() . '";'; + $add_header_rules[] = 'add_header X-Powered-By "' . Util_Environment::w3tc_header() . '";'; } - if ( !empty( $add_header_rules ) || $extra_add_headers_set ) { - $add_header_rules = array_merge( $add_header_rules, - $this->security_rules() ); + if ( ! empty( $add_header_rules ) || $extra_add_headers_set ) { + $add_header_rules = array_merge( $add_header_rules, $this->security_rules() ); } - return array( 'add_header' => $add_header_rules, 'other' => $rules ); + return array( + 'add_header' => $add_header_rules, + 'other' => $rules, + ); } } diff --git a/BrowserCache_Page.php b/BrowserCache_Page.php index 9b4c8cf43..8696e5e07 100644 --- a/BrowserCache_Page.php +++ b/BrowserCache_Page.php @@ -1,35 +1,63 @@ _config->get_boolean( 'browsercache.enabled' ); - $browsercache_last_modified = ( $this->_config->get_boolean( 'browsercache.cssjs.last_modified' ) && $this->_config->get_boolean( 'browsercache.html.last_modified' ) && $this->_config->get_boolean( 'browsercache.other.last_modified' ) ); - $browsercache_expires = ( $this->_config->get_boolean( 'browsercache.cssjs.expires' ) && $this->_config->get_boolean( 'browsercache.html.expires' ) && $this->_config->get_boolean( 'browsercache.other.expires' ) ); - $browsercache_cache_control = ( $this->_config->get_boolean( 'browsercache.cssjs.cache.control' ) && $this->_config->get_boolean( 'browsercache.html.cache.control' ) && $this->_config->get_boolean( 'browsercache.other.cache.control' ) ); - $browsercache_etag = ( $this->_config->get_boolean( 'browsercache.cssjs.etag' ) && $this->_config->get_boolean( 'browsercache.html.etag' ) && $this->_config->get_boolean( 'browsercache.other.etag' ) ); - $browsercache_w3tc = ( $this->_config->get_boolean( 'browsercache.cssjs.w3tc' ) && $this->_config->get_boolean( 'browsercache.html.w3tc' ) && $this->_config->get_boolean( 'browsercache.other.w3tc' ) ); - $browsercache_compression = ( $this->_config->get_boolean( 'browsercache.cssjs.compression' ) && $this->_config->get_boolean( 'browsercache.html.compression' ) && $this->_config->get_boolean( 'browsercache.other.compression' ) ); - $browsercache_brotli = ( $this->_config->get_boolean( 'browsercache.cssjs.brotli' ) && $this->_config->get_boolean( 'browsercache.html.brotli' ) && $this->_config->get_boolean( 'browsercache.other.brotli' ) ); - $browsercache_replace = ( $this->_config->get_boolean( 'browsercache.cssjs.replace' ) && $this->_config->get_boolean( 'browsercache.other.replace' ) ); - $browsercache_querystring = ( $this->_config->get_boolean( 'browsercache.cssjs.querystring' ) && $this->_config->get_boolean( 'browsercache.other.querystring' ) ); + /** + * View browser cache options + * + * @return void + */ + public function view() { + $browsercache_enabled = $this->_config->get_boolean( 'browsercache.enabled' ); + $browsercache_last_modified = ( $this->_config->get_boolean( 'browsercache.cssjs.last_modified' ) && $this->_config->get_boolean( 'browsercache.html.last_modified' ) && $this->_config->get_boolean( 'browsercache.other.last_modified' ) ); + $browsercache_expires = ( $this->_config->get_boolean( 'browsercache.cssjs.expires' ) && $this->_config->get_boolean( 'browsercache.html.expires' ) && $this->_config->get_boolean( 'browsercache.other.expires' ) ); + $browsercache_cache_control = ( $this->_config->get_boolean( 'browsercache.cssjs.cache.control' ) && $this->_config->get_boolean( 'browsercache.html.cache.control' ) && $this->_config->get_boolean( 'browsercache.other.cache.control' ) ); + $browsercache_etag = ( $this->_config->get_boolean( 'browsercache.cssjs.etag' ) && $this->_config->get_boolean( 'browsercache.html.etag' ) && $this->_config->get_boolean( 'browsercache.other.etag' ) ); + $browsercache_w3tc = ( $this->_config->get_boolean( 'browsercache.cssjs.w3tc' ) && $this->_config->get_boolean( 'browsercache.html.w3tc' ) && $this->_config->get_boolean( 'browsercache.other.w3tc' ) ); + $browsercache_compression = ( $this->_config->get_boolean( 'browsercache.cssjs.compression' ) && $this->_config->get_boolean( 'browsercache.html.compression' ) && $this->_config->get_boolean( 'browsercache.other.compression' ) ); + $browsercache_brotli = ( $this->_config->get_boolean( 'browsercache.cssjs.brotli' ) && $this->_config->get_boolean( 'browsercache.html.brotli' ) && $this->_config->get_boolean( 'browsercache.other.brotli' ) ); + $browsercache_replace = ( $this->_config->get_boolean( 'browsercache.cssjs.replace' ) && $this->_config->get_boolean( 'browsercache.other.replace' ) ); + $browsercache_querystring = ( $this->_config->get_boolean( 'browsercache.cssjs.querystring' ) && $this->_config->get_boolean( 'browsercache.other.querystring' ) ); $browsercache_update_media_qs = ( $this->_config->get_boolean( 'browsercache.cssjs.replace' ) || $this->_config->get_boolean( 'browsercache.other.replace' ) ); - $browsercache_nocookies = - ( $this->_config->get_boolean( 'browsercache.cssjs.nocookies' ) && - $this->_config->get_boolean( 'browsercache.other.nocookies' ) ); + $browsercache_nocookies = ( $this->_config->get_boolean( 'browsercache.cssjs.nocookies' ) && $this->_config->get_boolean( 'browsercache.other.nocookies' ) ); $is_nginx = Util_Environment::is_nginx(); diff --git a/BrowserCache_Page_View_QuickReference.php b/BrowserCache_Page_View_QuickReference.php index 48c768438..8d5887502 100644 --- a/BrowserCache_Page_View_QuickReference.php +++ b/BrowserCache_Page_View_QuickReference.php @@ -1,4 +1,10 @@ _config = Dispatcher::config(); } /** * Runs plugin + * + * @return void */ - function run() { - add_filter( 'w3tc_admin_bar_menu', - array( $this, 'w3tc_admin_bar_menu' ) ); + public function run() { + add_filter( 'w3tc_admin_bar_menu', array( $this, 'w3tc_admin_bar_menu' ) ); if ( $this->_config->get_boolean( 'browsercache.html.w3tc' ) ) { - add_action( 'send_headers', - array( $this, 'send_headers' ) ); + add_action( 'send_headers', array( $this, 'send_headers' ) ); } - if ( !$this->_config->get_boolean( 'browsercache.html.etag' ) ) { - add_filter( 'wp_headers', - array( $this, 'filter_wp_headers' ), - 0, 2 ); + if ( ! $this->_config->get_boolean( 'browsercache.html.etag' ) ) { + add_filter( 'wp_headers', array( $this, 'filter_wp_headers' ), 0, 2 ); } $url_uniqualize_enabled = $this->url_uniqualize_enabled(); if ( $this->url_clean_enabled() || $url_uniqualize_enabled ) { - $this->browsercache_rewrite = - $this->_config->get_boolean( 'browsercache.rewrite' ); + $this->browsercache_rewrite = $this->_config->get_boolean( 'browsercache.rewrite' ); - // modify CDN urls - add_filter( 'w3tc_cdn_url', - array( $this, 'w3tc_cdn_url' ), 0, 3 ); + // modify CDN urls. + add_filter( 'w3tc_cdn_url', array( $this, 'w3tc_cdn_url' ), 0, 3 ); if ( $url_uniqualize_enabled ) { - add_action( 'w3tc_flush_all', - array( $this, 'w3tc_flush_all' ), 1050, 1 ); + add_action( 'w3tc_flush_all', array( $this, 'w3tc_flush_all' ), 1050, 1 ); } - if ( $this->can_ob() ) { - Util_Bus::add_ob_callback( 'browsercache', - array( $this, 'ob_callback' ) ); + Util_Bus::add_ob_callback( 'browsercache', array( $this, 'ob_callback' ) ); } } $v = $this->_config->get_string( 'browsercache.security.session.cookie_httponly' ); - if ( !empty( $v ) ) { - @ini_set( 'session.cookie_httponly', $v == 'on' ? '1': '0' ); + if ( ! empty( $v ) ) { + @ini_set( 'session.cookie_httponly', 'on' === $v ? '1' : '0' ); } + $v = $this->_config->get_string( 'browsercache.security.session.cookie_secure' ); - if ( !empty( $v ) ) { - @ini_set( 'session.cookie_secure', $v == 'on' ? '1': '0' ); + if ( ! empty( $v ) ) { + @ini_set( 'session.cookie_secure', 'on' === $v ? '1' : '0' ); } + $v = $this->_config->get_string( 'browsercache.security.session.use_only_cookies' ); - if ( !empty( $v ) ) { - @ini_set( 'session.use_only_cookies', $v == 'on' ? '1': '0' ); + if ( ! empty( $v ) ) { + @ini_set( 'session.use_only_cookies', 'on' === $v ? '1' : '0' ); } - add_filter( 'w3tc_minify_http2_preload_url', - array( $this, 'w3tc_minify_http2_preload_url' ), 4000 ); - add_filter( 'w3tc_cdn_config_headers', - array( $this, 'w3tc_cdn_config_headers' ) ); + add_filter( 'w3tc_minify_http2_preload_url', array( $this, 'w3tc_minify_http2_preload_url' ), 4000 ); + add_filter( 'w3tc_cdn_config_headers', array( $this, 'w3tc_cdn_config_headers' ) ); if ( Util_Admin::is_w3tc_admin_page() ) { add_action( 'admin_notices', array( $this, 'admin_notices' ) ); } } + /** + * Check if URL clean is enabled + * + * @return bool + */ private function url_clean_enabled() { - return - $this->_config->get_boolean( 'browsercache.cssjs.querystring' ) || + return $this->_config->get_boolean( 'browsercache.cssjs.querystring' ) || $this->_config->get_boolean( 'browsercache.html.querystring' ) || $this->_config->get_boolean( 'browsercache.other.querystring' ); } + /** + * Check if URL uniqualize is enabled + * + * @return bool + */ private function url_uniqualize_enabled() { return $this->_config->get_boolean( 'browsercache.cssjs.replace' ) || $this->_config->get_boolean( 'browsercache.html.replace' ) || $this->_config->get_boolean( 'browsercache.other.replace' ); } + /** + * Flush all + * + * @param array $extras Extras. + * + * @return void + */ public function w3tc_flush_all( $extras = array() ) { - if ( isset( $extras['only'] ) && $extras['only'] != 'browsercache' ) + if ( isset( $extras['only'] ) && 'browsercache' !== $extras['only'] ) { return; + } - update_option( 'w3tc_browsercache_flush_timestamp', - rand( 10000, 99999 ) . '' ); + update_option( 'w3tc_browsercache_flush_timestamp', wp_rand( 10000, 99999 ) . '' ); } /** @@ -101,7 +139,7 @@ public function w3tc_flush_all( $extras = array() ) { * * @return boolean */ - function can_ob() { + public function can_ob() { /** * Skip if admin */ @@ -158,29 +196,26 @@ function can_ob() { /** * Output buffer callback * - * @param string $buffer + * @param string $buffer Buffer. + * * @return mixed */ - function ob_callback( $buffer ) { - if ( $buffer != '' && Util_Content::is_html_xml( $buffer ) ) { + public function ob_callback( $buffer ) { + if ( '' !== $buffer && Util_Content::is_html_xml( $buffer ) ) { $domain_url_regexp = Util_Environment::home_domain_root_url_regexp(); $buffer = preg_replace_callback( - '~(href|src|action|extsrc|asyncsrc|w3tc_load_js\()=?([\'"])((' . - $domain_url_regexp . - ')?(/[^\'"/][^\'"]*\.([a-z-_]+)([\?#][^\'"]*)?))[\'"]~Ui', array( - $this, - 'link_replace_callback' - ), $buffer ); - - // without quotes + '~(href|src|action|extsrc|asyncsrc|w3tc_load_js\()=?([\'"])((' . $domain_url_regexp . ')?(/[^\'"/][^\'"]*\.([a-z-_]+)([\?#][^\'"]*)?))[\'"]~Ui', + array( $this, 'link_replace_callback' ), + $buffer + ); + + // without quotes. $buffer = preg_replace_callback( - '~(href|src|action|extsrc|asyncsrc)=((' . - $domain_url_regexp . - ')?(/[^\\s>][^\\s>]*\.([a-z-_]+)([\?#][^\\s>]*)?))([\\s>])~Ui', array( - $this, - 'link_replace_callback_noquote' - ), $buffer ); + '~(href|src|action|extsrc|asyncsrc)=((' . $domain_url_regexp . ')?(/[^\\s>][^\\s>]*\.([a-z-_]+)([\?#][^\\s>]*)?))([\\s>])~Ui', + array( $this, 'link_replace_callback_noquote' ), + $buffer + ); } return $buffer; @@ -189,43 +224,53 @@ function ob_callback( $buffer ) { /** * Link replace callback * - * @param string $matches + * @param string $matches Matches. + * * @return string */ - function link_replace_callback( $matches ) { + public function link_replace_callback( $matches ) { list ( $match, $attr, $quote, $url, , , , , $extension ) = $matches; $ops = $this->_get_url_mutation_operations( $url, $extension ); - if ( is_null( $ops ) ) + if ( is_null( $ops ) ) { return $match; + } - $url = $this->mutate_url( $url, $ops, !$this->browsercache_rewrite ); + $url = $this->mutate_url( $url, $ops, ! $this->browsercache_rewrite ); - if ( $attr != 'w3tc_load_js(' ) + if ( 'w3tc_load_js(' !== $attr ) { return $attr . '=' . $quote . $url . $quote; + } + return sprintf( '%s\'%s\'', $attr, $url ); } /** * Link replace callback when no quote arount attribute value * - * @param string $matches + * @param string $matches Matches. + * * @return string */ - function link_replace_callback_noquote( $matches ) { + public function link_replace_callback_noquote( $matches ) { list ( $match, $attr, $url, , , , , $extension, , $delimiter ) = $matches; $ops = $this->_get_url_mutation_operations( $url, $extension ); - if ( is_null( $ops ) ) + if ( is_null( $ops ) ) { return $match; + } - $url = $this->mutate_url( $url, $ops, !$this->browsercache_rewrite ); + $url = $this->mutate_url( $url, $ops, ! $this->browsercache_rewrite ); return $attr . '=' . $url . $delimiter; } /** * Mutate http/2 header links + * + * @param array $data Data. + * + * @return array */ public function w3tc_minify_http2_preload_url( $data ) { if ( isset( $data['browsercache_processed'] ) ) { @@ -233,11 +278,11 @@ public function w3tc_minify_http2_preload_url( $data ) { } $data['browsercache_processed'] = '*'; - $url = $data['result_link']; + $url = $data['result_link']; - // decouple extension + // decouple extension. $matches = array(); - if ( !preg_match( '/\.([a-zA-Z0-9]+)($|[\?])/', $url, $matches ) ) { + if ( ! preg_match( '/\.([a-zA-Z0-9]+)($|[\?])/', $url, $matches ) ) { return $data; } $extension = $matches[1]; @@ -247,41 +292,57 @@ public function w3tc_minify_http2_preload_url( $data ) { return $data; } - $mutate_by_querystring = !$this->browsercache_rewrite; + $mutate_by_querystring = ! $this->browsercache_rewrite; - $url = $this->mutate_url( $url, $ops, $mutate_by_querystring ); + $url = $this->mutate_url( $url, $ops, $mutate_by_querystring ); $data['result_link'] = $url; + return $data; } /** * Link replace for CDN url * - * @param string $matches + * @param string $url URL. + * @param string $original_url Original URL. + * @param bool $is_cdn_mirror Is CDN mirror. + * * @return string */ - function w3tc_cdn_url( $url, $original_url, $is_cdn_mirror ) { - // decouple extension + public function w3tc_cdn_url( $url, $original_url, $is_cdn_mirror ) { + // decouple extension. $matches = array(); - if ( !preg_match( '/\.([a-zA-Z0-9]+)($|[\?])/', $original_url, $matches ) ) + if ( ! preg_match( '/\.([a-zA-Z0-9]+)($|[\?])/', $original_url, $matches ) ) { return $url; + } $extension = $matches[1]; $ops = $this->_get_url_mutation_operations( $original_url, $extension ); - if ( is_null( $ops ) ) + if ( is_null( $ops ) ) { return $url; + } - // for push cdns each flush would require manual reupload of files - $mutate_by_querystring = !$this->browsercache_rewrite || !$is_cdn_mirror; + // for push cdns each flush would require manual reupload of files. + $mutate_by_querystring = ! $this->browsercache_rewrite || ! $is_cdn_mirror; $url = $this->mutate_url( $url, $ops, $mutate_by_querystring ); + return $url; } + /** + * Mutate url + * + * @param string $url URL. + * @param array $ops Operations data. + * @param bool $mutate_by_querystring Mutate by querystring flag. + * + * @return string + */ private function mutate_url( $url, $ops, $mutate_by_querystring ) { $query_pos = strpos( $url, '?' ); - if ( isset( $ops['querystring'] ) && $query_pos !== false ) { - $url = substr( $url, 0, $query_pos ); + if ( isset( $ops['querystring'] ) && false !== $query_pos ) { + $url = substr( $url, 0, $query_pos ); $query_pos = false; } @@ -289,29 +350,25 @@ private function mutate_url( $url, $ops, $mutate_by_querystring ) { $id = $this->get_filename_uniqualizator(); if ( $mutate_by_querystring ) { - if ( $query_pos !== false ) { - $url = substr( $url, 0, $query_pos + 1 ) . $id . '&' . - substr( $url, $query_pos + 1 ); + if ( false !== $query_pos ) { + $url = substr( $url, 0, $query_pos + 1 ) . $id . '&' . substr( $url, $query_pos + 1 ); } else { $tag_pos = strpos( $url, '#' ); - if ( $tag_pos === false ) { + if ( false === $tag_pos ) { $url .= '?' . $id; } else { - $url = substr( $url, 0, $tag_pos ) . '?' . $id . - substr( $url, $tag_pos ); + $url = substr( $url, 0, $tag_pos ) . '?' . $id . substr( $url, $tag_pos ); } } - } else { - // add $id to url before extension - + // add $id to url before extension. $url_query = ''; - if ( $query_pos !== false ) { + if ( false !== $query_pos ) { $url_query = substr( $url, $query_pos ); - $url = substr( $url, 0, $query_pos ); + $url = substr( $url, 0, $query_pos ); } - $ext_pos = strrpos( $url, '.' ); + $ext_pos = strrpos( $url, '.' ); $extension = substr( $url, $ext_pos ); $url = substr( $url, 0, strlen( $url ) - strlen( $extension ) ) . @@ -322,28 +379,39 @@ private function mutate_url( $url, $ops, $mutate_by_querystring ) { return $url; } - function _get_url_mutation_operations( $url, $extension ) { + /** + * Get mutatation url operations + * + * @param string $url URL. + * @param string $extension Operations data. + * + * @return string + */ + public function _get_url_mutation_operations( $url, $extension ) { static $extensions = null; - if ( $extensions === null ) { - $core = Dispatcher::component( 'BrowserCache_Core' ); + if ( null === $extensions ) { + $core = Dispatcher::component( 'BrowserCache_Core' ); $extensions = $core->get_replace_querystring_extensions( $this->_config ); } static $exceptions = null; - if ( $exceptions === null ) + if ( null === $exceptions ) { $exceptions = $this->_config->get_array( 'browsercache.replace.exceptions' ); + } - if ( !isset( $extensions[$extension] ) ) + if ( ! isset( $extensions[ $extension ] ) ) { return null; + } $test_url = Util_Environment::remove_query( $url ); foreach ( $exceptions as $exception ) { $escaped = str_replace( '~', '\~', $exception ); - if ( trim( $exception ) && preg_match( '~' . $escaped . '~', $test_url ) ) + if ( trim( $exception ) && preg_match( '~' . $escaped . '~', $test_url ) ) { return null; + } } - return $extensions[$extension]; + return $extensions[ $extension ]; } /** @@ -351,14 +419,14 @@ function _get_url_mutation_operations( $url, $extension ) { * * @return string */ - function get_filename_uniqualizator() { + public function get_filename_uniqualizator() { static $cache_id = null; - if ( $cache_id === null ) { + if ( null === $cache_id ) { $value = get_option( 'w3tc_browsercache_flush_timestamp' ); if ( empty( $value ) ) { - $value = rand( 10000, 99999 ) . ''; + $value = wp_rand( 10000, 99999 ) . ''; update_option( 'w3tc_browsercache_flush_timestamp', $value ); } @@ -368,19 +436,25 @@ function get_filename_uniqualizator() { return 'x' . $cache_id; } + /** + * Admin bar menu + * + * @param array $menu_items Menu items. + * + * @return array + */ public function w3tc_admin_bar_menu( $menu_items ) { - $browsercache_update_media_qs = - ( $this->_config->get_boolean( 'browsercache.cssjs.replace' ) || - $this->_config->get_boolean( 'browsercache.other.replace' ) ); + $browsercache_update_media_qs = ( + $this->_config->get_boolean( 'browsercache.cssjs.replace' ) || + $this->_config->get_boolean( 'browsercache.other.replace' ) + ); if ( $browsercache_update_media_qs ) { $menu_items['20190.browsercache'] = array( - 'id' => 'w3tc_flush_browsercache', + 'id' => 'w3tc_flush_browsercache', 'parent' => 'w3tc_flush', - 'title' => __( 'Browser Cache', 'w3-total-cache' ), - 'href' => wp_nonce_url( admin_url( - 'admin.php?page=w3tc_dashboard&w3tc_flush_browser_cache' ), - 'w3tc' ) + 'title' => __( 'Browser Cache', 'w3-total-cache' ), + 'href' => wp_nonce_url( admin_url( 'admin.php?page=w3tc_dashboard&w3tc_flush_browser_cache' ), 'w3tc' ), ); } @@ -389,26 +463,39 @@ public function w3tc_admin_bar_menu( $menu_items ) { /** * Send headers + * + * @return void */ - function send_headers() { + public function send_headers() { @header( 'X-Powered-By: ' . Util_Environment::w3tc_header() ); } /** * Returns headers config for CDN + * + * @param Config $config Config. + * + * @return Config */ - function w3tc_cdn_config_headers( $config ) { + public function w3tc_cdn_config_headers( $config ) { $sections = Util_Mime::sections_to_mime_types_map(); foreach ( $sections as $section => $v ) { - $config[$section] = $this->w3tc_cdn_config_headers_section( $section ); + $config[ $section ] = $this->w3tc_cdn_config_headers_section( $section ); } return $config; } + /** + * Gets CDN config headers section + * + * @param string $section Section. + * + * @return Config + */ private function w3tc_cdn_config_headers_section( $section ) { - $c = $this->_config; - $prefix = 'browsercache.' . $section; + $c = $this->_config; + $prefix = 'browsercache.' . $section; $lifetime = $c->get_integer( $prefix . '.lifetime' ); $headers = array(); @@ -419,61 +506,64 @@ private function w3tc_cdn_config_headers_section( $section ) { if ( $c->get_boolean( $prefix . '.cache.control' ) ) { switch ( $c->get_string( $prefix . '.cache.policy' ) ) { - case 'cache': - $headers['Pragma'] = 'public'; - $headers['Cache-Control'] = 'public'; - break; - - case 'cache_public_maxage': - $headers['Pragma'] = 'public'; - $headers['Cache-Control'] = "max-age=$lifetime, public"; - break; - - case 'cache_validation': - $headers['Pragma'] = 'public'; - $headers['Cache-Control'] = 'public, must-revalidate, proxy-revalidate'; - break; - - case 'cache_noproxy': - $headers['Pragma'] = 'public'; - $headers['Cache-Control'] = 'private, must-revalidate'; - break; - - case 'cache_maxage': - $headers['Pragma'] = 'public'; - $headers['Cache-Control'] = "max-age=$lifetime, public, must-revalidate, proxy-revalidate"; - break; - - case 'no_cache': - $headers['Pragma'] = 'no-cache'; - $headers['Cache-Control'] = 'private, no-cache'; - break; - - case 'no_store': - $headers['Pragma'] = 'no-store'; - $headers['Cache-Control'] = 'no-store'; - break; + case 'cache': + $headers['Pragma'] = 'public'; + $headers['Cache-Control'] = 'public'; + break; + + case 'cache_public_maxage': + $headers['Pragma'] = 'public'; + $headers['Cache-Control'] = "max-age=$lifetime, public"; + break; + + case 'cache_validation': + $headers['Pragma'] = 'public'; + $headers['Cache-Control'] = 'public, must-revalidate, proxy-revalidate'; + break; + + case 'cache_noproxy': + $headers['Pragma'] = 'public'; + $headers['Cache-Control'] = 'private, must-revalidate'; + break; + + case 'cache_maxage': + $headers['Pragma'] = 'public'; + $headers['Cache-Control'] = "max-age=$lifetime, public, must-revalidate, proxy-revalidate"; + break; + + case 'no_cache': + $headers['Pragma'] = 'no-cache'; + $headers['Cache-Control'] = 'private, no-cache'; + break; + + case 'no_store': + $headers['Pragma'] = 'no-store'; + $headers['Cache-Control'] = 'no-store'; + break; } } return array( - 'etag' => $c->get_boolean( $prefix . 'etag' ), - 'expires' => $c->get_boolean( $prefix . '.expires' ), + 'etag' => $c->get_boolean( $prefix . 'etag' ), + 'expires' => $c->get_boolean( $prefix . '.expires' ), 'lifetime' => $lifetime, - 'static' => $headers + 'static' => $headers, ); } /** * Filters headers set by WordPress * - * @param unknown $headers - * @param unknown $wp - * @return + * @param array $headers Headers. + * @param object $wp WP object. + * + * @return array */ - function filter_wp_headers( $headers, $wp ) { - if ( !empty( $wp->query_vars['feed'] ) ) + public function filter_wp_headers( $headers, $wp ) { + if ( ! empty( $wp->query_vars['feed'] ) ) { unset( $headers['ETag'] ); + } + return $headers; } diff --git a/BrowserCache_Plugin_Admin.php b/BrowserCache_Plugin_Admin.php index d367c2133..01bd4daee 100644 --- a/BrowserCache_Plugin_Admin.php +++ b/BrowserCache_Plugin_Admin.php @@ -1,34 +1,51 @@ $value ) { + foreach ( $_REQUEST as $key => $value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $value = Util_Request::get_string( $key ); - if ( substr( $key, 0, $prefixl ) == $prefix ) { + if ( substr( $key, 0, $prefixl ) === $prefix ) { $k = substr( $key, $prefixl ); - if ( !empty( $value ) ) { - $fp_values[$k] = $value; + if ( ! empty( $value ) ) { + $fp_values[ $k ] = $value; } } } diff --git a/Cache_Apc.php b/Cache_Apc.php index 38ce48a88..736f9e1a3 100644 --- a/Cache_Apc.php +++ b/Cache_Apc.php @@ -1,28 +1,41 @@ get( $key, $group ) === false ) { return $this->set( $key, $var, $expire, $group ); } @@ -33,13 +46,14 @@ function add( $key, &$var, $expire = 0, $group = '' ) { /** * Sets data * - * @param string $key - * @param mixed $var - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param mixed $var Value. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function set( $key, $var, $expire = 0, $group = '' ) { + public function set( $key, $var, $expire = 0, $group = '' ) { if ( ! isset( $var['key_version'] ) ) { $var['key_version'] = $this->_get_key_version( $group ); } @@ -51,21 +65,24 @@ function set( $key, $var, $expire = 0, $group = '' ) { /** * Returns data * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return mixed */ - function get_with_old( $key, $group = '' ) { + public function get_with_old( $key, $group = '' ) { $has_old_data = false; - $storage_key = $this->get_item_key( $key ); + $storage_key = $this->get_item_key( $key ); $v = @unserialize( apc_fetch( $storage_key ) ); - if ( !is_array( $v ) || !isset( $v['key_version'] ) ) + if ( ! is_array( $v ) || ! isset( $v['key_version'] ) ) { return array( null, $has_old_data ); + } $key_version = $this->_get_key_version( $group ); - if ( $v['key_version'] == $key_version ) + if ( $v['key_version'] === $key_version ) { return array( $v, $has_old_data ); + } if ( $v['key_version'] > $key_version ) { if ( ! empty( $v['key_version_at_creation'] ) && $v['key_version_at_creation'] !== $key_version ) { @@ -74,14 +91,14 @@ function get_with_old( $key, $group = '' ) { return array( $v, $has_old_data ); } - // key version is old - if ( !$this->_use_expired_data ) + // key version is old. + if ( ! $this->_use_expired_data ) { return array( null, $has_old_data ); + } - // if we have expired data - update it for future use and let - // current process recalculate it + // if we have expired data - update it for future use and let current process recalculate it. $expires_at = isset( $v['expires_at'] ) ? $v['expires_at'] : null; - if ( $expires_at == null || time() > $expires_at ) { + if ( null === $expires_at || time() > $expires_at ) { $v['expires_at'] = time() + 30; apc_store( $storage_key, serialize( $v ), 0 ); $has_old_data = true; @@ -89,7 +106,7 @@ function get_with_old( $key, $group = '' ) { return array( null, $has_old_data ); } - // return old version + // return old version. return array( $v, $has_old_data ); } @@ -97,13 +114,14 @@ function get_with_old( $key, $group = '' ) { /** * Replaces data * - * @param string $key - * @param mixed $var - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param mixed $var Value. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function replace( $key, &$var, $expire = 0, $group ='' ) { + public function replace( $key, &$var, $expire = 0, $group = '' ) { if ( $this->get( $key, $group ) !== false ) { return $this->set( $key, $var, $expire, $group ); } @@ -114,11 +132,12 @@ function replace( $key, &$var, $expire = 0, $group ='' ) { /** * Deletes data * - * @param string $key - * @param string $group + * @param string $key Key. + * @param string $group Group. + * * @return boolean */ - function delete( $key, $group = '' ) { + public function delete( $key, $group = '' ) { $storage_key = $this->get_item_key( $key ); if ( $this->_use_expired_data ) { @@ -136,10 +155,12 @@ function delete( $key, $group = '' ) { /** * Deletes _old and primary if exists. * - * @param unknown $key + * @param string $key Key. + * @param string $group Group. + * * @return bool */ - function hard_delete( $key, $group = '' ) { + public function hard_delete( $key, $group = '' ) { $storage_key = $this->get_item_key( $key ); return apc_delete( $storage_key ); } @@ -147,13 +168,15 @@ function hard_delete( $key, $group = '' ) { /** * Flushes all data * - * @param string $group Used to differentiate between groups of cache values + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function flush( $group = '' ) { - $this->_get_key_version( $group ); // initialize $this->_key_version - $this->_key_version[$group]++; - $this->_set_key_version( $this->_key_version[$group], $group ); + public function flush( $group = '' ) { + $this->_get_key_version( $group ); // initialize $this->_key_version. + $this->_key_version[ $group ]++; + $this->_set_key_version( $this->_key_version[ $group ], $group ); + return true; } @@ -200,25 +223,28 @@ public function available() { /** * Returns key postfix * - * @param string $group Used to differentiate between groups of cache values + * @param string $group Used to differentiate between groups of cache values. + * * @return integer */ private function _get_key_version( $group = '' ) { - if ( !isset( $this->_key_version[$group] ) || $this->_key_version[$group] <= 0 ) { + if ( ! isset( $this->_key_version[ $group ] ) || $this->_key_version[ $group ] <= 0 ) { $v = apc_fetch( $this->_get_key_version_key( $group ) ); $v = intval( $v ); - $this->_key_version[$group] = ( $v > 0 ? $v : 1 ); + + $this->_key_version[ $group ] = ( $v > 0 ? $v : 1 ); } - return $this->_key_version[$group]; + return $this->_key_version[ $group ]; } /** * Sets new key version * - * @param unknown $v - * @param string $group Used to differentiate between groups of cache values - * @return boolean + * @param unknown $v Key. + * @param string $group Used to differentiate between groups of cache values. + * + * @return void */ private function _set_key_version( $v, $group = '' ) { apc_store( $this->_get_key_version_key( $group ), $v, 0 ); @@ -226,36 +252,55 @@ private function _set_key_version( $v, $group = '' ) { /** * Used to replace as atomically as possible known value to new one + * + * @param string $key Key. + * @param mixed $old_value Old value. + * @param mixed $new_value New value. + * + * @return bool */ public function set_if_maybe_equals( $key, $old_value, $new_value ) { - // apc_cas doesnt fit here, since we are float but it works with - // int only - // cant guarantee atomic action here, filelocks fail often + // apc_cas doesnt fit here, since we are float but it works with int only cant + // guarantee atomic action here, filelocks fail often. $value = $this->get( $key ); - if ( isset( $old_value['content'] ) && - $value['content'] != $old_value['content'] ) + if ( isset( $old_value['content'] ) && $value['content'] !== $old_value['content'] ) { return false; + } return $this->set( $key, $new_value ); } /** * Use key as a counter and add integet value to it + * + * @param string $key Key. + * @param mixed $value Value. + * + * @return bool */ public function counter_add( $key, $value ) { - if ( $value == 0 ) + if ( 0 === $value ) { return true; + } $storage_key = $this->get_item_key( $key ); - $r = apc_inc( $storage_key, $value ); - if ( !$r ) // it doesnt initialize counter by itself + $r = apc_inc( $storage_key, $value ); + + // it doesnt initialize counter by itself. + if ( ! $r ) { $this->counter_set( $key, 0 ); + } return $r; } /** * Use key as a counter and add integet value to it + * + * @param string $key Key. + * @param mixed $value Value. + * + * @return bool */ public function counter_set( $key, $value ) { $storage_key = $this->get_item_key( $key ); @@ -264,10 +309,14 @@ public function counter_set( $key, $value ) { /** * Get counter's value + * + * @param string $key Key. + * + * @return int */ public function counter_get( $key ) { $storage_key = $this->get_item_key( $key ); - $v = (int)apc_fetch( $storage_key ); + $v = (int) apc_fetch( $storage_key ); return $v; } diff --git a/Cache_Apcu.php b/Cache_Apcu.php index fee7d61bb..f947b0036 100644 --- a/Cache_Apcu.php +++ b/Cache_Apcu.php @@ -1,27 +1,40 @@ get( $key, $group ) === false ) { return $this->set( $key, $var, $expire, $group ); } @@ -32,35 +45,39 @@ function add( $key, &$var, $expire = 0, $group = '' ) { /** * Sets data * - * @param string $key - * @param mixed $var - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param mixed $var Value. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function set( $key, $var, $expire = 0, $group = '' ) { + public function set( $key, $var, $expire = 0, $group = '' ) { if ( ! isset( $var['key_version'] ) ) { $var['key_version'] = $this->_get_key_version( $group ); } $storage_key = $this->get_item_key( $key ); + return apcu_store( $storage_key, serialize( $var ), $expire ); } /** * Returns data * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return mixed */ - function get_with_old( $key, $group = '' ) { + public function get_with_old( $key, $group = '' ) { $has_old_data = false; - $storage_key = $this->get_item_key( $key ); + $storage_key = $this->get_item_key( $key ); $v = @unserialize( apcu_fetch( $storage_key ) ); - if ( !is_array( $v ) || !isset( $v['key_version'] ) ) + if ( ! is_array( $v ) || ! isset( $v['key_version'] ) ) { return array( null, $has_old_data ); + } $key_version = $this->_get_key_version( $group ); if ( $v['key_version'] === $key_version ) { @@ -74,14 +91,14 @@ function get_with_old( $key, $group = '' ) { return array( $v, $has_old_data ); } - // key version is old - if ( !$this->_use_expired_data ) + // key version is old. + if ( ! $this->_use_expired_data ) { return array( null, $has_old_data ); + } - // if we have expired data - update it for future use and let - // current process recalculate it + // if we have expired data - update it for future use and let current process recalculate it. $expires_at = isset( $v['expires_at'] ) ? $v['expires_at'] : null; - if ( $expires_at == null || time() > $expires_at ) { + if ( null === $expires_at || time() > $expires_at ) { $v['expires_at'] = time() + 30; apcu_store( $storage_key, serialize( $v ), 0 ); $has_old_data = true; @@ -89,7 +106,7 @@ function get_with_old( $key, $group = '' ) { return array( null, $has_old_data ); } - // return old version + // return old version. return array( $v, $has_old_data ); } @@ -97,13 +114,14 @@ function get_with_old( $key, $group = '' ) { /** * Replaces data * - * @param string $key - * @param mixed $var - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param mixed $var Value. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function replace( $key, &$var, $expire = 0, $group ='' ) { + public function replace( $key, &$var, $expire = 0, $group = '' ) { if ( $this->get( $key, $group ) !== false ) { return $this->set( $key, $var, $expire, $group ); } @@ -114,11 +132,12 @@ function replace( $key, &$var, $expire = 0, $group ='' ) { /** * Deletes data * - * @param string $key - * @param string $group + * @param string $key Key. + * @param string $group Group. + * * @return boolean */ - function delete( $key, $group = '' ) { + public function delete( $key, $group = '' ) { $storage_key = $this->get_item_key( $key ); if ( $this->_use_expired_data ) { @@ -136,10 +155,12 @@ function delete( $key, $group = '' ) { /** * Deletes _old and primary if exists. * - * @param unknown $key + * @param string $key Key. + * @param string $group Group. + * * @return bool */ - function hard_delete( $key, $group = '' ) { + public function hard_delete( $key, $group = '' ) { $storage_key = $this->get_item_key( $key ); return apcu_delete( $storage_key ); } @@ -147,13 +168,15 @@ function hard_delete( $key, $group = '' ) { /** * Flushes all data * - * @param string $group Used to differentiate between groups of cache values + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function flush( $group = '' ) { - $this->_get_key_version( $group ); // initialize $this->_key_version - $this->_key_version[$group]++; - $this->_set_key_version( $this->_key_version[$group], $group ); + public function flush( $group = '' ) { + $this->_get_key_version( $group ); // initialize $this->_key_version. + $this->_key_version[ $group ]++; + $this->_set_key_version( $this->_key_version[ $group ], $group ); + return true; } @@ -200,25 +223,28 @@ public function available() { /** * Returns key postfix * - * @param string $group Used to differentiate between groups of cache values + * @param string $group Used to differentiate between groups of cache values. + * * @return integer */ private function _get_key_version( $group = '' ) { - if ( !isset( $this->_key_version[$group] ) || $this->_key_version[$group] <= 0 ) { + if ( ! isset( $this->_key_version[ $group ] ) || $this->_key_version[ $group ] <= 0 ) { $v = apcu_fetch( $this->_get_key_version_key( $group ) ); $v = intval( $v ); - $this->_key_version[$group] = ( $v > 0 ? $v : 1 ); + + $this->_key_version[ $group ] = ( $v > 0 ? $v : 1 ); } - return $this->_key_version[$group]; + return $this->_key_version[ $group ]; } /** * Sets new key version * - * @param unknown $v - * @param string $group Used to differentiate between groups of cache values - * @return boolean + * @param unknown $v Key. + * @param string $group Used to differentiate between groups of cache values. + * + * @return void */ private function _set_key_version( $v, $group = '' ) { apcu_store( $this->_get_key_version_key( $group ), $v, 0 ); @@ -226,36 +252,55 @@ private function _set_key_version( $v, $group = '' ) { /** * Used to replace as atomically as possible known value to new one + * + * @param string $key Key. + * @param mixed $old_value Old value. + * @param mixed $new_value New value. + * + * @return bool */ public function set_if_maybe_equals( $key, $old_value, $new_value ) { // apc_cas doesnt fit here, since we are float but it works with - // int only - // cant guarantee atomic action here, filelocks fail often + // int only cant guarantee atomic action here, filelocks fail often. $value = $this->get( $key ); - if ( isset( $old_value['content'] ) && - $value['content'] != $old_value['content'] ) + if ( isset( $old_value['content'] ) && $value['content'] !== $old_value['content'] ) { return false; + } return $this->set( $key, $new_value ); } /** * Use key as a counter and add integet value to it + * + * @param string $key Key. + * @param mixed $value Value. + * + * @return bool */ public function counter_add( $key, $value ) { - if ( $value == 0 ) + if ( 0 === $value ) { return true; + } $storage_key = $this->get_item_key( $key ); - $r = apcu_inc( $storage_key, $value ); - if ( !$r ) // it doesnt initialize counter by itself + $r = apcu_inc( $storage_key, $value ); + + // it doesnt initialize counter by itself. + if ( ! $r ) { $this->counter_set( $key, 0 ); + } return $r; } /** * Use key as a counter and add integet value to it + * + * @param string $key Key. + * @param mixed $value Value. + * + * @return bool */ public function counter_set( $key, $value ) { $storage_key = $this->get_item_key( $key ); @@ -264,10 +309,14 @@ public function counter_set( $key, $value ) { /** * Get counter's value + * + * @param string $key Key. + * + * @return int */ public function counter_get( $key ) { $storage_key = $this->get_item_key( $key ); - $v = (int)apcu_fetch( $storage_key ); + $v = (int) apcu_fetch( $storage_key ); return $v; } diff --git a/Cache_Base.php b/Cache_Base.php index 57baf86b2..9e7d19376 100644 --- a/Cache_Base.php +++ b/Cache_Base.php @@ -1,20 +1,28 @@ _blog_id = $config['blog_id']; - $this->_use_expired_data = isset( $config['use_expired_data'] )?$config['use_expired_data']:false; - $this->_module = isset( $config['module'] ) ? $config['module'] : 'default'; - $this->_host = isset( $config['host'] ) ? $config['host'] : ''; - $this->_instance_id = isset( $config['instance_id'] ) ? $config['instance_id'] : 0; + $this->_blog_id = $config['blog_id']; + $this->_use_expired_data = isset( $config['use_expired_data'] ) ? $config['use_expired_data'] : false; + $this->_module = isset( $config['module'] ) ? $config['module'] : 'default'; + $this->_host = isset( $config['host'] ) ? $config['host'] : ''; + $this->_instance_id = isset( $config['instance_id'] ) ? $config['instance_id'] : 0; } /** * Adds data * * @abstract - * @param string $key - * @param mixed $data - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * + * @param string $key Key. + * @param mixed $data Data. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function add( $key, &$data, $expire = 0, $group = '' ) { + public function add( $key, &$data, $expire = 0, $group = '' ) { return false; } @@ -75,24 +87,29 @@ function add( $key, &$data, $expire = 0, $group = '' ) { * Sets data * * @abstract - * @param string $key - * @param mixed $data - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * + * @param string $key Key. + * @param mixed $data Data. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function set( $key, $data, $expire = 0, $group = '' ) { + public function set( $key, $data, $expire = 0, $group = '' ) { return false; } /** * Returns data * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @abstract + * + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return mixed */ - function get( $key, $group = '' ) { + public function get( $key, $group = '' ) { list( $data, $has_old ) = $this->get_with_old( $key, $group ); return $data; } @@ -101,34 +118,42 @@ function get( $key, $group = '' ) { * Return primary data and if old exists * * @abstract - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return array|mixed */ - function get_with_old( $key, $group = '' ) { + public function get_with_old( $key, $group = '' ) { return array( null, false ); } - /** + /** * Checks if entry exists * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @abstract + * + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean true if exists, false otherwise */ - function exists( $key, $group = '' ) { + public function exists( $key, $group = '' ) { list( $data, $has_old ) = $this->get_with_old( $key, $group ); - return ! empty( $data) && ! $has_old; + return ! empty( $data ) && ! $has_old; } /** * Alias for get for minify cache * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @abstract + * + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return mixed */ - function fetch( $key, $group = '' ) { + public function fetch( $key, $group = '' ) { return $this->get( $key, $group = '' ); } @@ -136,13 +161,15 @@ function fetch( $key, $group = '' ) { * Replaces data * * @abstract - * @param string $key - * @param mixed $data - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * + * @param string $key Key. + * @param mixed $data Data. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function replace( $key, &$data, $expire = 0, $group = '' ) { + public function replace( $key, &$data, $expire = 0, $group = '' ) { return false; } @@ -150,11 +177,13 @@ function replace( $key, &$data, $expire = 0, $group = '' ) { * Deletes data * * @abstract - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function delete( $key, $group = '' ) { + public function delete( $key, $group = '' ) { return false; } @@ -162,10 +191,13 @@ function delete( $key, $group = '' ) { * Deletes primary data and old data * * @abstract - * @param string $key + * + * @param string $key Key. + * @param string $group Group. + * * @return boolean */ - function hard_delete( $key, $group = '' ) { + public function hard_delete( $key, $group = '' ) { return false; } @@ -173,10 +205,12 @@ function hard_delete( $key, $group = '' ) { * Flushes all data * * @abstract - * @param string $group Used to differentiate between groups of cache values + * + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function flush( $group = '' ) { + public function flush( $group = '' ) { return false; } @@ -211,6 +245,8 @@ public function flush_group_after_ahead_generation( $group, $extension ) { /** * Checks if engine can function properly in this environment * + * @abstract + * * @return bool */ public function available() { @@ -220,38 +256,65 @@ public function available() { /** * Constructs key version key * - * @param unknown $group + * @abstract + * + * @param unknown $group Group. + * * @return string */ protected function _get_key_version_key( $group = '' ) { - return sprintf( 'w3tc_%d_%d_%s_%s_key_version', - $this->_instance_id, $this->_blog_id, - $this->_module, $group ); + return sprintf( + 'w3tc_%d_%d_%s_%s_key_version', + $this->_instance_id, + $this->_blog_id, + $this->_module, + $group + ); } /** * Constructs item key * - * @param unknown $name + * @abstract + * + * @param unknown $name Name. + * * @return string */ public function get_item_key( $name ) { - $key = sprintf( 'w3tc_%d_%s_%d_%s_%s', - $this->_instance_id, $this->_host, $this->_blog_id, - $this->_module, $name ); - return $key; + return sprintf( + 'w3tc_%d_%s_%d_%s_%s', + $this->_instance_id, + $this->_host, + $this->_blog_id, + $this->_module, + $name + ); } - /** - * Use key as a counter and add integet value to it + * Use key as a counter and add integer value to it + * + * @abstract + * + * @param string $key Key. + * @param int $value Value. + * + * @return bool */ public function counter_add( $key, $value ) { return false; } /** - * Use key as a counter and add integet value to it + * Use key as a counter and add integer value to it + * + * @abstract + * + * @param string $key Key. + * @param int $value Value. + * + * @return bool */ public function counter_set( $key, $value ) { return false; @@ -259,6 +322,12 @@ public function counter_set( $key, $value ) { /** * Get counter's value + * + * @abstract + * + * @param string $key Key. + * + * @return bool */ public function counter_get( $key ) { return false; diff --git a/Cache_Eaccelerator.php b/Cache_Eaccelerator.php index 7eb359886..37f225aca 100644 --- a/Cache_Eaccelerator.php +++ b/Cache_Eaccelerator.php @@ -1,28 +1,41 @@ get( $key, $group ) === false ) { return $this->set( $key, $var, $expire, $group ); } @@ -33,13 +46,14 @@ function add( $key, &$var, $expire = 0, $group = '' ) { /** * Sets data * - * @param string $key - * @param mixed $var - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param mixed $var Value. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function set( $key, $var, $expire = 0, $group = '' ) { + public function set( $key, $var, $expire = 0, $group = '' ) { if ( ! isset( $var['key_version'] ) ) { $var['key_version'] = $this->_get_key_version( $group ); } @@ -51,21 +65,24 @@ function set( $key, $var, $expire = 0, $group = '' ) { /** * Returns data * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return mixed */ - function get_with_old( $key, $group = '' ) { + public function get_with_old( $key, $group = '' ) { $has_old_data = false; - $storage_key = $this->get_item_key( $key ); + $storage_key = $this->get_item_key( $key ); $v = @unserialize( eaccelerator_get( $storage_key ) ); - if ( !is_array( $v ) || !isset( $v['key_version'] ) ) + if ( ! is_array( $v ) || ! isset( $v['key_version'] ) ) { return array( null, $has_old_data ); + } $key_version = $this->_get_key_version( $group ); - if ( $v['key_version'] == $key_version ) + if ( $v['key_version'] === $key_version ) { return array( $v, $has_old_data ); + } if ( $v['key_version'] > $key_version ) { if ( ! empty( $v['key_version_at_creation'] ) && $v['key_version_at_creation'] !== $key_version ) { @@ -74,14 +91,14 @@ function get_with_old( $key, $group = '' ) { return array( $v, $has_old_data ); } - // key version is old - if ( !$this->_use_expired_data ) + // key version is old. + if ( ! $this->_use_expired_data ) { return array( null, $has_old_data ); + } - // if we have expired data - update it for future use and let - // current process recalculate it + // if we have expired data - update it for future use and let current process recalculate it. $expires_at = isset( $v['expires_at'] ) ? $v['expires_at'] : null; - if ( $expires_at == null || time() > $expires_at ) { + if ( null === $expires_at || time() > $expires_at ) { $v['expires_at'] = time() + 30; eaccelerator_put( $storage_key, serialize( $v ), 0 ); $has_old_data = true; @@ -89,20 +106,21 @@ function get_with_old( $key, $group = '' ) { return array( null, $has_old_data ); } - // return old version + // return old version. return array( $v, $has_old_data ); } /** * Replaces data * - * @param string $key - * @param mixed $var - * @param integer $expire - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param mixed $var Value. + * @param integer $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function replace( $key, &$var, $expire = 0, $group = '' ) { + public function replace( $key, &$var, $expire = 0, $group = '' ) { if ( $this->get( $key, $group ) !== false ) { return $this->set( $key, $var, $expire, $group ); } @@ -113,11 +131,12 @@ function replace( $key, &$var, $expire = 0, $group = '' ) { /** * Deletes data * - * @param string $key - * @param string $group + * @param string $key Key. + * @param string $group Group. + * * @return boolean */ - function delete( $key, $group = '' ) { + public function delete( $key, $group = '' ) { $storage_key = $this->get_item_key( $key ); if ( $this->_use_expired_data ) { @@ -136,23 +155,26 @@ function delete( $key, $group = '' ) { /** * Deletes _old and primary if exists. * - * @param unknown $key + * @param string $key Key. + * @param string $group Group. + * * @return bool */ - function hard_delete( $key, $group = '' ) { + public function hard_delete( $key, $group = '' ) { $storage_key = $this->get_item_key( $key ); return eaccelerator_rm( $storage_key ); } /** * Flushes all data * - * @param string $group Used to differentiate between groups of cache values + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function flush( $group = '' ) { - $this->_get_key_version( $group ); // initialize $this->_key_version - $this->_key_version[$group]++; - $this->_set_key_version( $this->_key_version[$group], $group ); + public function flush( $group = '' ) { + $this->_get_key_version( $group ); // initialize $this->_key_version. + $this->_key_version[ $group ]++; + $this->_set_key_version( $this->_key_version[ $group ], $group ); return true; } @@ -200,65 +222,88 @@ public function available() { /** * Returns key postfix * - * @param string $group Used to differentiate between groups of cache values + * @param string $group Used to differentiate between groups of cache values. + * * @return integer */ private function _get_key_version( $group = '' ) { - if ( !isset( $this->_key_version[$group] ) || $this->_key_version[$group] <= 0 ) { + if ( ! isset( $this->_key_version[ $group ] ) || $this->_key_version[ $group ] <= 0 ) { $v = eaccelerator_get( $this->_get_key_version_key( $group ) ); $v = intval( $v ); - $this->_key_version[$group] = ( $v > 0 ? $v : 1 ); + + $this->_key_version[ $group ] = ( $v > 0 ? $v : 1 ); } - return $this->_key_version[$group]; + return $this->_key_version[ $group ]; } /** * Sets new key version * - * @param unknown $v - * @param string $group Used to differentiate between groups of cache values + * @param unknown $v Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ private function _set_key_version( $v, $group = '' ) { - // cant guarantee atomic action here, filelocks fail often + // cant guarantee atomic action here, filelocks fail often. $value = $this->get( $key ); - if ( isset( $old_value['content'] ) && - $value['content'] != $old_value['content'] ) + if ( isset( $old_value['content'] ) && $value['content'] !== $old_value['content'] ) { return false; + } return $this->set( $key, $new_value ); } /** * Used to replace as atomically as possible known value to new one + * + * @param string $key Key. + * @param mixed $old_value Old value. + * @param mixed $new_value New value. + * + * @return bool */ public function set_if_maybe_equals( $key, $old_value, $new_value ) { - // eaccelerator cache not supported anymore by its authors + // eaccelerator cache not supported anymore by its authors. return false; } /** * Use key as a counter and add integet value to it + * + * @param string $key Key. + * @param mixed $value Value. + * + * @return bool */ public function counter_add( $key, $value ) { - // eaccelerator cache not supported anymore by its authors + // eaccelerator cache not supported anymore by its authors. return false; } /** * Use key as a counter and add integet value to it + * + * @param string $key Key. + * @param mixed $value Value. + * + * @return bool */ public function counter_set( $key, $value ) { - // eaccelerator cache not supported anymore by its authors + // eaccelerator cache not supported anymore by its authors. return false; } /** * Get counter's value + * + * @param string $key Key. + * + * @return bool */ public function counter_get( $key ) { - // eaccelerator cache not supported anymore by its authors + // eaccelerator cache not supported anymore by its authors. return false; } } diff --git a/Cache_File_Cleaner.php b/Cache_File_Cleaner.php index 5fdbacfdd..dc26d7828 100644 --- a/Cache_File_Cleaner.php +++ b/Cache_File_Cleaner.php @@ -1,8 +1,19 @@ _cache_dir = ( isset( $config['cache_dir'] ) ? trim( $config['cache_dir'] ) : 'cache' ); + public function __construct( $config = array() ) { + $this->_cache_dir = ( isset( $config['cache_dir'] ) ? trim( $config['cache_dir'] ) : 'cache' ); $this->_clean_timelimit = ( isset( $config['clean_timelimit'] ) ? (int) $config['clean_timelimit'] : 180 ); - $this->_exclude = ( isset( $config['exclude'] ) ? (array) $config['exclude'] : array() ); + $this->_exclude = ( isset( $config['exclude'] ) ? (array) $config['exclude'] : array() ); } /** * Run clean operation * - * @return boolean + * @return void */ - function clean() { + public function clean() { @set_time_limit( $this->_clean_timelimit ); $this->_clean( $this->_cache_dir, false ); @@ -53,7 +66,7 @@ function clean() { * * @return void */ - public function clean_before( $before_time ) { + public function clean_before() { @set_time_limit( $this->_clean_timelimit ); $this->_clean( $this->_cache_dir, false ); @@ -62,16 +75,17 @@ public function clean_before( $before_time ) { /** * Clean * - * @param string $path - * @param bool $remove + * @param string $path Path. + * @param bool $remove Remove flag. + * * @return void */ - function _clean( $path, $remove = true ) { + public function _clean( $path, $remove = true ) { $dir = @opendir( $path ); if ( $dir ) { - while ( ( $entry = @readdir( $dir ) ) !== false ) { - if ( $entry == '.' || $entry == '..' ) { + while ( ( $entry = @readdir( $dir ) ) !== false ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition + if ( '.' === $entry || '..' === $entry ) { continue; } @@ -85,7 +99,7 @@ function _clean( $path, $remove = true ) { if ( @is_dir( $full_path ) ) { $this->_clean( $full_path ); - } elseif ( !$this->is_valid( $full_path ) ) { + } elseif ( ! $this->is_valid( $full_path ) ) { @unlink( $full_path ); } } @@ -101,10 +115,11 @@ function _clean( $path, $remove = true ) { /** * Check if file is valid * - * @param string $file + * @param string $file File. + * * @return bool */ - function is_valid( $file ) { + public function is_valid( $file ) { $valid = false; if ( file_exists( $file ) ) { @@ -113,9 +128,9 @@ function is_valid( $file ) { if ( $fp ) { $expires = @fread( $fp, 4 ); - if ( $expires !== false ) { + if ( false !== $expires ) { list( , $expires_at ) = @unpack( 'L', $expires ); - $valid = ( time() < $expires_at ); + $valid = ( time() < $expires_at ); } @fclose( $fp ); diff --git a/Cache_File_Cleaner_Generic.php b/Cache_File_Cleaner_Generic.php index 53219a8c9..8c2559129 100644 --- a/Cache_File_Cleaner_Generic.php +++ b/Cache_File_Cleaner_Generic.php @@ -1,8 +1,18 @@ _expire = ( isset( $config['expire'] ) ? (int) $config['expire'] : 0 ); @@ -58,15 +70,23 @@ function __construct( $config = array() ) { } } - function _clean( $path, $remove = false ) { + /** + * Clean + * + * @param string $path Path. + * @param bool $remove Remove flag. + * + * @return void + */ + public function _clean( $path, $remove = false ) { $dir = false; if ( is_dir( $path ) ) { $dir = @opendir( $path ); } if ( $dir ) { - while ( ( $entry = @readdir( $dir ) ) !== false ) { - if ( $entry == '.' || $entry == '..' ) { + while ( ( $entry = @readdir( $dir ) ) !== false ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition + if ( '.' === $entry || '..' === $entry ) { continue; } @@ -86,27 +106,34 @@ function _clean( $path, $remove = false ) { } @closedir( $dir ); - if ( $this->is_empty_dir( $path ) ) + if ( $this->is_empty_dir( $path ) ) { @rmdir( $path ); + } } } - function _clean_file( $entry, $full_path ) { - if ( substr( $entry, -4 ) === '_old' ) { + /** + * Clean file + * + * @param string $entry Entry. + * @param string $full_path Full path. + * + * @return void + */ + public function _clean_file( $entry, $full_path ) { + if ( '_old' === substr( $entry, -4 ) ) { if ( ! $this->is_old_file_valid( $full_path ) ) { $this->processed_count++; - @unlink( $full_path ); //phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged + @unlink( $full_path ); } - } elseif ( !$this->is_valid( $full_path ) ) { + } elseif ( ! $this->is_valid( $full_path ) ) { $old_entry_path = $full_path . '_old'; $this->processed_count++; - if ( !@rename( $full_path, $old_entry_path ) ) { - - // if we can delete old entry - - // do second attempt to store in old-entry file + if ( ! @rename( $full_path, $old_entry_path ) ) { + // if we can delete old entry - do second attempt to store in old-entry file. if ( @unlink( $old_entry_path ) ) { - if ( !@rename( $full_path, $old_entry_path ) ) { - // last attempt - just remove entry + if ( ! @rename( $full_path, $old_entry_path ) ) { + // last attempt - just remove entry. @unlink( $full_path ); } } @@ -117,10 +144,11 @@ function _clean_file( $entry, $full_path ) { /** * Checks if file is valid * - * @param string $file + * @param string $file File. + * * @return bool */ - function is_valid( $file ) { + public function is_valid( $file ) { if ( $this->time_min_valid > 0 && file_exists( $file ) ) { $ftime = @filemtime( $file ); if ( $ftime && $ftime >= $this->time_min_valid ) { @@ -131,6 +159,13 @@ function is_valid( $file ) { return false; } + /** + * Checks if old file is valid + * + * @param string $file File. + * + * @return bool + */ public function is_old_file_valid( $file ) { if ( $this->old_file_time_min_valid > 0 && file_exists( $file ) ) { $ftime = @filemtime( $file ); @@ -143,7 +178,15 @@ public function is_old_file_valid( $file ) { return false; } - function is_empty_dir( $dir ) { - return ( $files = @scandir( $dir ) ) && count( $files ) <= 2; + /** + * Checks if directory is empty + * + * @param string $dir Directory. + * + * @return bool + */ + public function is_empty_dir( $dir ) { + $files = @scandir( $dir ); + return $files && count( $files ) <= 2; } } diff --git a/Cache_File_Cleaner_Generic_HardDelete.php b/Cache_File_Cleaner_Generic_HardDelete.php index 833abf936..6540cf09e 100644 --- a/Cache_File_Cleaner_Generic_HardDelete.php +++ b/Cache_File_Cleaner_Generic_HardDelete.php @@ -1,19 +1,44 @@ is_old_file_valid( $full_path ) ) { $this->processed_count++; - @unlink( $full_path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged - } elseif ( !$this->is_valid( $full_path ) ) { + @unlink( $full_path ); + } elseif ( ! $this->is_valid( $full_path ) ) { @unlink( $full_path ); } } diff --git a/Cache_File_Generic.php b/Cache_File_Generic.php index c82f9eca0..76f7cfcb3 100644 --- a/Cache_File_Generic.php +++ b/Cache_File_Generic.php @@ -1,8 +1,22 @@ _expire = ( isset( $config['expire'] ) ? (int) $config['expire'] : 0 ); - if ( !$this->_expire || $this->_expire > W3TC_CACHE_FILE_EXPIRE_MAX ) { + if ( ! $this->_expire || $this->_expire > W3TC_CACHE_FILE_EXPIRE_MAX ) { $this->_expire = W3TC_CACHE_FILE_EXPIRE_MAX; } } @@ -30,32 +46,36 @@ function __construct( $config = array() ) { /** * Sets data * - * @param string $key - * @param string $var - * @param int $expire - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param string $var Value. + * @param int $expire Time to expire. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function set( $key, $var, $expire = 0, $group = '' ) { - $key = $this->get_item_key( $key ); + public function set( $key, $var, $expire = 0, $group = '' ) { + $key = $this->get_item_key( $key ); $sub_path = $this->_get_path( $key, $group ); - $path = $this->_cache_dir . DIRECTORY_SEPARATOR . $sub_path; + $path = $this->_cache_dir . DIRECTORY_SEPARATOR . $sub_path; $dir = dirname( $path ); - if ( !@is_dir( $dir ) ) { - if ( !Util_File::mkdir_from_safe( $dir, dirname( W3TC_CACHE_DIR ) ) ) + if ( ! @is_dir( $dir ) ) { + if ( ! Util_File::mkdir_from_safe( $dir, dirname( W3TC_CACHE_DIR ) ) ) { return false; + } } $tmppath = $path . '.' . getmypid(); $fp = @fopen( $tmppath, 'wb' ); - if ( !$fp ) + if ( ! $fp ) { return false; + } - if ( $this->_locking ) + if ( $this->_locking ) { @flock( $fp, LOCK_EX ); + } @fputs( $fp, $var['content'] ); @fclose( $fp ); @@ -71,8 +91,7 @@ function set( $key, $var, $expire = 0, $group = '' ) { @flock( $fp, LOCK_UN ); } - // some hostings create files with restrictive permissions - // not allowing apache to read it later + // some hostings create files with restrictive permissions not allowing apache to read it later. @chmod( $path, 0644 ); if ( @filesize( $tmppath ) > 0 ) { @@ -88,8 +107,7 @@ function set( $key, $var, $expire = 0, $group = '' ) { if ( Util_Environment::is_apache() && isset( $var['headers'] ) ) { $rules = ''; - if ( isset( $var['headers']['Content-Type'] ) && - substr( $var['headers']['Content-Type'], 0, 8 ) == 'text/xml' ) { + if ( isset( $var['headers']['Content-Type'] ) && 'text/xml' === substr( $var['headers']['Content-Type'], 0, 8 ) ) { $rules .= "\n"; $rules .= " RemoveType .html_gzip\n"; @@ -103,21 +121,20 @@ function set( $key, $var, $expire = 0, $group = '' ) { $headers = array(); foreach ( $var['headers'] as $h ) { if ( isset( $h['n'] ) && isset( $h['v'] ) ) { - $h2 = apply_filters( 'w3tc_pagecache_set_header', $h, $h, - 'file_generic' ); + $h2 = apply_filters( 'w3tc_pagecache_set_header', $h, $h, 'file_generic' ); - if ( !empty( $h2 ) ) { + if ( ! empty( $h2 ) ) { $name_escaped = $this->escape_header_name( $h2['n'] ); - if ( !isset( $headers[$name_escaped] ) ) { - $headers[$name_escaped] = array( - 'values' => array(), - 'files_match' => $h2['files_match'] + if ( ! isset( $headers[ $name_escaped ] ) ) { + $headers[ $name_escaped ] = array( + 'values' => array(), + 'files_match' => $h2['files_match'], ); } $value_escaped = $this->escape_header_value( $h2['v'] ); - if ( !empty( $value_escaped ) ) { - $headers[$name_escaped]['values'][] = + if ( ! empty( $value_escaped ) ) { + $headers[ $name_escaped ]['values'][] = " Header add " . $name_escaped . " '" . $value_escaped . "'\n"; @@ -128,14 +145,14 @@ function set( $key, $var, $expire = 0, $group = '' ) { $header_rules = ''; foreach ( $headers as $name_escaped => $value ) { - // Link header doesnt apply to .xml assets + // Link header doesnt apply to .xml assets. $header_rules .= ' \n"; $header_rules .= " Header unset $name_escaped\n"; $header_rules .= implode( "\n", $value['values'] ); $header_rules .= " \n"; } - if ( !empty( $header_rules ) ) { + if ( ! empty( $header_rules ) ) { $rules .= "\n"; $rules .= $header_rules; $rules .= "\n"; @@ -159,48 +176,69 @@ function set( $key, $var, $expire = 0, $group = '' ) { return true; } + /** + * Escape header name + * + * @param string $v Value. + * + * @return array + */ private function escape_header_name( $v ) { return preg_replace( '~[^0-9A-Za-z\-]~m', '_', $v ); } + /** + * Escape header value + * + * @param string $v Value. + * + * @return array + */ private function escape_header_value( $v ) { - return str_replace( "'", "\\'", - str_replace( "\\", "\\\\\\", // htaccess need escape of \ to \\\ - preg_replace( '~[\r\n]~m', '_', trim( $v ) ) ) ); + return str_replace( + "'", + "\\'", + str_replace( + "\\", + "\\\\\\", // htaccess need escape of \ to \\\. + preg_replace( '~[\r\n]~m', '_', trim( $v ) ) + ) + ); } /** * Returns data * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return array */ - function get_with_old( $key, $group = '' ) { + public function get_with_old( $key, $group = '' ) { $has_old_data = false; - $key = $this->get_item_key( $key ); - $path = $this->_cache_dir . DIRECTORY_SEPARATOR . - $this->_get_path( $key, $group ); + $key = $this->get_item_key( $key ); + $path = $this->_cache_dir . DIRECTORY_SEPARATOR . $this->_get_path( $key, $group ); $data = $this->_read( $path ); - if ( $data != null ) + if ( null !== $data ) { return array( $data, $has_old_data ); + } - - $path_old = $path . '_old'; + $path_old = $path . '_old'; $too_old_time = time() - 30; - if ( $exists = file_exists( $path_old ) ) { + $exists = file_exists( $path_old ); + if ( $exists ) { $file_time = @filemtime( $path_old ); if ( $file_time ) { if ( $file_time > $too_old_time ) { - // return old data + // return old data. $has_old_data = true; return array( $this->_read( $path_old ), $has_old_data ); } - // use old enough time to cause recalculation on next call + // use old enough time to cause recalculation on next call. @touch( $path_old, 1479904835 ); } } @@ -212,66 +250,72 @@ function get_with_old( $key, $group = '' ) { /** * Reads file * - * @param string $path + * @param string $path Path. + * * @return array */ private function _read( $path ) { - if ( !is_readable( $path ) ) + if ( ! is_readable( $path ) ) { return null; + } - // make sure reading from cache folder - // canonicalize to avoid unexpected variants + // make sure reading from cache folder canonicalize to avoid unexpected variants. $base_path = realpath( $this->_cache_dir ); - $path = realpath( $path ); + $path = realpath( $path ); - if ( strlen( $base_path ) <= 0 || - substr( $path, 0, strlen( $base_path ) ) != $base_path ) { + if ( strlen( $base_path ) <= 0 || substr( $path, 0, strlen( $base_path ) ) !== $base_path ) { return null; } $fp = @fopen( $path, 'rb' ); - if ( !$fp ) + if ( ! $fp ) { return null; + } - if ( $this->_locking ) + if ( $this->_locking ) { @flock( $fp, LOCK_SH ); + } $var = ''; - while ( !@feof( $fp ) ) + while ( ! @feof( $fp ) ) { $var .= @fread( $fp, 4096 ); + } @fclose( $fp ); - if ( $this->_locking ) + if ( $this->_locking ) { @flock( $fp, LOCK_UN ); + } $headers = array(); - if ( substr( $path, -4 ) == '.xml' ) { + if ( '.xml' === substr( $path, -4 ) ) { $headers['Content-type'] = 'text/xml'; } return array( - '404' => false, + '404' => false, 'headers' => $headers, - 'time' => null, - 'content' => $var + 'time' => null, + 'content' => $var, ); } /** * Deletes data * - * @param string $key - * @param string $group Used to differentiate between groups of cache values + * @param string $key Key. + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function delete( $key, $group = '' ) { - $key = $this->get_item_key( $key ); + public function delete( $key, $group = '' ) { + $key = $this->get_item_key( $key ); $path = $this->_cache_dir . DIRECTORY_SEPARATOR . $this->_get_path( $key, $group ); - if ( !file_exists( $path ) ) + if ( ! file_exists( $path ) ) { return true; + } $dir = dirname( $path ); if ( file_exists( $dir . DIRECTORY_SEPARATOR . '.htaccess' ) ) { @@ -280,7 +324,7 @@ function delete( $key, $group = '' ) { $old_entry_path = $path . '_old'; if ( ! @rename( $path, $old_entry_path ) ) { - // if we can delete old entry - do second attempt to store in old-entry file + // if we can delete old entry - do second attempt to store in old-entry file. if ( ! @unlink( $old_entry_path ) || ! @rename( $path, $old_entry_path ) ) { return @unlink( $path ); } @@ -292,7 +336,7 @@ function delete( $key, $group = '' ) { * WP 5.9/6.3 this was resulting in the _old file immediately being removed during the clean * operation, resulting in failed automated tests (8/1/2023) */ - // @touch( $old_entry_path, 1479904835 ); + // @touch( $old_entry_path, 1479904835 ); phpcs:ignore Squiz.PHP.CommentedOutCode.Found return true; } @@ -313,47 +357,56 @@ public function exists( $key, $group = '' ) { /** * Key to delete, deletes _old and primary if exists. * - * @param unknown $key + * @param string $key Key. + * @param string $group Group. + * * @return bool */ - function hard_delete( $key, $group = '' ) { - $key = $this->get_item_key( $key ); - $path = $this->_cache_dir . DIRECTORY_SEPARATOR . $this->_get_path( $key, $group ); + public function hard_delete( $key, $group = '' ) { + $key = $this->get_item_key( $key ); + $path = $this->_cache_dir . DIRECTORY_SEPARATOR . $this->_get_path( $key, $group ); $old_entry_path = $path . '_old'; @unlink( $old_entry_path ); - if ( !file_exists( $path ) ) + if ( ! file_exists( $path ) ) { return true; + } + @unlink( $path ); + return true; } /** * Flushes all data * - * @param string $group Used to differentiate between groups of cache values + * @param string $group Used to differentiate between groups of cache values. + * * @return boolean */ - function flush( $group = '' ) { - if ( $group == 'sitemaps' ) { - $config = Dispatcher::config(); + public function flush( $group = '' ) { + if ( 'sitemaps' === $group ) { + $config = Dispatcher::config(); $sitemap_regex = $config->get_string( 'pgcache.purge.sitemap_regex' ); $this->_flush_based_on_regex( $sitemap_regex ); } else { $dir = $this->_flush_dir; - if ( !empty( $group ) ) { - $c = new Cache_File_Cleaner_Generic_HardDelete( array( - 'cache_dir' => $this->_flush_dir . - DIRECTORY_SEPARATOR . $group, - 'exclude' => $this->_exclude, - 'clean_timelimit' => $this->_flush_timelimit - ) ); + if ( ! empty( $group ) ) { + $c = new Cache_File_Cleaner_Generic_HardDelete( + array( + 'cache_dir' => $this->_flush_dir . DIRECTORY_SEPARATOR . $group, + 'exclude' => $this->_exclude, + 'clean_timelimit' => $this->_flush_timelimit, + ) + ); } else { - $c = new Cache_File_Cleaner_Generic( array( - 'cache_dir' => $this->_flush_dir, - 'exclude' => $this->_exclude, - 'clean_timelimit' => $this->_flush_timelimit - ) ); + $c = new Cache_File_Cleaner_Generic( + array( + 'cache_dir' => $this->_flush_dir, + 'exclude' => $this->_exclude, + 'clean_timelimit' => $this->_flush_timelimit, + ) + ); } $c->clean(); @@ -372,7 +425,7 @@ function flush( $group = '' ) { */ public function get_ahead_generation_extension( $group ) { return array( - 'before_time' => time() + 'before_time' => time(), ); } @@ -412,39 +465,48 @@ public function flush_group_after_ahead_generation( $group, $extension ) { /** * Returns cache file path by key * - * @param string $key + * @param string $key Key. + * @param string $group Group. + * * @return string */ - function _get_path( $key, $group = '' ) { + public function _get_path( $key, $group = '' ) { return ( empty( $group ) ? '' : $group . DIRECTORY_SEPARATOR ) . $key; } - function get_item_key( $key ) { + /** + * Returns item key + * + * @param string $key Key. + * + * @return string + */ + public function get_item_key( $key ) { return $key; } - /** * Flush cache based on regex * - * @param string $regex + * @param string $regex Regex. + * + * @return void */ private function _flush_based_on_regex( $regex ) { - if ( Util_Environment::is_wpmu() && !Util_Environment::is_wpmu_subdomain() ) { - $domain = get_home_url(); - $parsed = parse_url( $domain ); - $host = $parsed['host']; - $path = isset( $parsed['path'] ) ? '/' . trim( $parsed['path'], '/' ) : ''; - $flush_dir = W3TC_CACHE_PAGE_ENHANCED_DIR . - DIRECTORY_SEPARATOR . $host . $path; - } else - $flush_dir = W3TC_CACHE_PAGE_ENHANCED_DIR . - DIRECTORY_SEPARATOR . Util_Environment::host(); + if ( Util_Environment::is_wpmu() && ! Util_Environment::is_wpmu_subdomain() ) { + $domain = get_home_url(); + $parsed = wp_parse_url( $domain ); + $host = $parsed['host']; + $path = isset( $parsed['path'] ) ? '/' . trim( $parsed['path'], '/' ) : ''; + $flush_dir = W3TC_CACHE_PAGE_ENHANCED_DIR . DIRECTORY_SEPARATOR . $host . $path; + } else { + $flush_dir = W3TC_CACHE_PAGE_ENHANCED_DIR . DIRECTORY_SEPARATOR . Util_Environment::host(); + } $dir = @opendir( $flush_dir ); if ( $dir ) { - while ( ( $entry = @readdir( $dir ) ) !== false ) { - if ( $entry == '.' || $entry == '..' ) { + while ( ( $entry = @readdir( $dir ) ) !== false ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition + if ( '.' === $entry || '..' === $entry ) { continue; } if ( preg_match( '~' . $regex . '~', basename( $entry ) ) ) { diff --git a/Extension_ImageService_Api.php b/Extension_ImageService_Api.php index d1713b2e9..3bb7a323c 100644 --- a/Extension_ImageService_Api.php +++ b/Extension_ImageService_Api.php @@ -137,6 +137,10 @@ public function convert( $filepath, array $options = array() ) { 'optimize' => $options['optimize'], ); + if ( ( defined( 'W3TC_PRO' ) && W3TC_PRO ) || ( defined( 'W3TC_ENTERPRISE' ) && W3TC_ENTERPRISE ) ) { + $post_fields['pro_c'] = 1; + } + foreach ( $post_fields as $k => $v ) { $body .= '--' . $boundary . "\r\n"; $body .= 'Content-Disposition: form-data; name="' . $k . '"' . "\r\n\r\n"; diff --git a/Generic_AdminActions_Config.php b/Generic_AdminActions_Config.php index 177c7cc9f..2d12eeaf2 100644 --- a/Generic_AdminActions_Config.php +++ b/Generic_AdminActions_Config.php @@ -1,13 +1,34 @@ _config = Dispatcher::config(); } @@ -50,9 +71,18 @@ public function w3tc_config_import() { * * @return void */ - function w3tc_config_export() { - $filename = substr( get_home_url(), strpos( get_home_url(), '//' )+2 ); - @header( sprintf( __( 'Content-Disposition: attachment; filename=%s.json', 'w3-total-cache' ), $filename ) ); + public function w3tc_config_export() { + $filename = substr( get_home_url(), strpos( get_home_url(), '//' ) + 2 ); + @header( + sprintf( + // Translators: 1 filename. + __( + 'Content-Disposition: attachment; filename=%s.json', + 'w3-total-cache' + ), + $filename + ) + ); echo $this->_config->export(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped die(); } @@ -62,7 +92,7 @@ function w3tc_config_export() { * * @return void */ - function w3tc_config_reset() { + public function w3tc_config_reset() { $config = new Config(); $config->set_defaults(); Util_Admin::config_save( $this->_config, $config ); @@ -75,24 +105,28 @@ function w3tc_config_reset() { $config_state->reset(); $config_state->save(); - Util_Admin::redirect( array( - 'w3tc_note' => 'config_reset' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'config_reset', + ), + true + ); } - /** * Save preview option * * @return void */ - function w3tc_config_preview_enable() { + public function w3tc_config_preview_enable() { ConfigUtil::preview_production_copy( Util_Environment::blog_id(), -1 ); Util_Environment::set_preview( true ); - Util_Admin::redirect( array( - 'w3tc_note' => 'preview_enable' - ) ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'preview_enable', + ) + ); } /** @@ -100,14 +134,16 @@ function w3tc_config_preview_enable() { * * @return void */ - function w3tc_config_preview_disable() { + public function w3tc_config_preview_disable() { $blog_id = Util_Environment::blog_id(); ConfigUtil::remove_item( $blog_id, true ); Util_Environment::set_preview( false ); - Util_Admin::redirect( array( - 'w3tc_note' => 'preview_disable' - ) ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'preview_disable', + ) + ); } /** @@ -115,38 +151,35 @@ function w3tc_config_preview_disable() { * * @return void */ - function w3tc_config_preview_deploy() { + public function w3tc_config_preview_deploy() { ConfigUtil::preview_production_copy( Util_Environment::blog_id(), 1 ); Util_Environment::set_preview( false ); - Util_Admin::redirect( array( - 'w3tc_note' => 'preview_deploy' - ) ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'preview_deploy', + ) + ); } - - /** * Save dbcluster config action * * @return void */ - function w3tc_config_dbcluster_config_save() { + public function w3tc_config_dbcluster_config_save() { $params = array( 'page' => 'w3tc_general' ); - if ( !file_put_contents( W3TC_FILE_DB_CLUSTER_CONFIG, - Util_Request::get_string( 'newcontent' ) ) ) { + if ( ! file_put_contents( W3TC_FILE_DB_CLUSTER_CONFIG, Util_Request::get_string( 'newcontent' ) ) ) { try { Util_Activation::throw_on_write_error( W3TC_FILE_DB_CLUSTER_CONFIG ); } catch ( \Exception $e ) { $error = $e->getMessage(); - Util_Admin::redirect_with_custom_messages( $params, array( - 'dbcluster_save_failed' => $error ) ); + Util_Admin::redirect_with_custom_messages( $params, array( 'dbcluster_save_failed' => $error ) ); } } - Util_Admin::redirect_with_custom_messages( $params, null, - array( 'dbcluster_save' => __( 'Database Cluster configuration file has been successfully saved', 'w3-total-cache' ) ) ); + Util_Admin::redirect_with_custom_messages( $params, null, array( 'dbcluster_save' => __( 'Database Cluster configuration file has been successfully saved', 'w3-total-cache' ) ) ); } /** @@ -154,9 +187,9 @@ function w3tc_config_dbcluster_config_save() { * * @return void */ - function w3tc_config_save_support_us() { - $tweeted = Util_Request::get_boolean( 'tweeted' ); - $signmeup = Util_Request::get_boolean( 'signmeup' ); + public function w3tc_config_save_support_us() { + $tweeted = Util_Request::get_boolean( 'tweeted' ); + $signmeup = Util_Request::get_boolean( 'signmeup' ); $accept_terms = Util_Request::get_boolean( 'accept_terms' ); $this->_config->set( 'common.tweeted', $tweeted ); @@ -168,20 +201,30 @@ function w3tc_config_save_support_us() { $state_master->save(); if ( $signmeup ) { - if ( Util_Environment::is_w3tc_pro( $this->_config ) ) + if ( Util_Environment::is_w3tc_pro( $this->_config ) ) { $license = 'pro'; - else + } else { $license = 'community'; + } + $email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_EMAIL ); - wp_remote_post( W3TC_MAILLINGLIST_SIGNUP_URL, array( - 'body' => array( 'email' => $email, 'license' => $license ) - ) ); + wp_remote_post( + W3TC_MAILLINGLIST_SIGNUP_URL, + array( + 'body' => array( + 'email' => $email, + 'license' => $license, + ), + ) + ); } $this->_config->save(); - Util_Admin::redirect( array( - 'w3tc_note' => 'config_save' - ) ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'config_save', + ) + ); } /** @@ -189,14 +232,21 @@ function w3tc_config_save_support_us() { * * @return void */ - function w3tc_config_update_upload_path() { + public function w3tc_config_update_upload_path() { update_option( 'upload_path', '' ); Util_Admin::redirect(); } + /** + * Config overload disable. + * + * @param string $http_key HTTP Key. + * + * @return void + */ public function w3tc_config_overloaded_disable( $http_key ) { - $c = Dispatcher::config(); + $c = Dispatcher::config(); $key = Util_Ui::config_key_from_http_name( $http_key ); $c->set( $key, false ); $c->save(); @@ -204,8 +254,15 @@ public function w3tc_config_overloaded_disable( $http_key ) { Util_Admin::redirect( array() ); } + /** + * Config overload enable. + * + * @param string $http_key HTTP Key. + * + * @return void + */ public function w3tc_config_overloaded_enable( $http_key ) { - $c = Dispatcher::config(); + $c = Dispatcher::config(); $key = Util_Ui::config_key_from_http_name( $http_key ); $c->set( $key, true ); $c->save(); diff --git a/Generic_AdminActions_Default.php b/Generic_AdminActions_Default.php index 9f11f7edc..7124104e3 100644 --- a/Generic_AdminActions_Default.php +++ b/Generic_AdminActions_Default.php @@ -1,4 +1,10 @@ _config = Dispatcher::config(); $this->_config_master = Dispatcher::config_master(); @@ -30,7 +59,7 @@ function __construct() { /** * Start previewing */ - function w3tc_default_previewing() { + public function w3tc_default_previewing() { Util_Environment::set_preview( true ); Util_Environment::redirect( get_home_url() ); } @@ -38,7 +67,7 @@ function w3tc_default_previewing() { /** * Stop previewing the site */ - function w3tc_default_stop_previewing() { + public function w3tc_default_stop_previewing() { Util_Environment::set_preview( false ); Util_Admin::redirect( array(), true ); } @@ -48,7 +77,7 @@ function w3tc_default_stop_previewing() { * * @return void */ - function w3tc_default_save_license_key() { + public function w3tc_default_save_license_key() { $license = Util_Request::get_string( 'license_key' ); try { $old_config = new Config(); @@ -73,7 +102,7 @@ function w3tc_default_save_license_key() { * * @return void */ - function w3tc_default_hide_note() { + public function w3tc_default_hide_note() { $note = Util_Request::get_string( 'note' ); $setting = sprintf( 'notes.%s', $note ); @@ -84,7 +113,12 @@ function w3tc_default_hide_note() { Util_Admin::redirect( array(), true ); } - function w3tc_default_config_state() { + /** + * Set default config state + * + * @return void + */ + public function w3tc_default_config_state() { $key = Util_Request::get_string( 'key' ); $value = Util_Request::get_string( 'value' ); @@ -94,7 +128,12 @@ function w3tc_default_config_state() { Util_Admin::redirect( array(), true ); } - function w3tc_default_config_state_master() { + /** + * Set default config state master + * + * @return void + */ + public function w3tc_default_config_state_master() { $key = Util_Request::get_string( 'key' ); $value = Util_Request::get_string( 'value' ); @@ -105,7 +144,12 @@ function w3tc_default_config_state_master() { Util_Admin::redirect( array(), true ); } - function w3tc_default_config_state_note() { + /** + * Set default config state note + * + * @return void + */ + public function w3tc_default_config_state_note() { $key = Util_Request::get_string( 'key' ); $value = Util_Request::get_string( 'value' ); @@ -117,13 +161,20 @@ function w3tc_default_config_state_note() { /** * Hide note custom action + * + * @return void */ - function w3tc_default_hide_note_custom() { + public function w3tc_default_hide_note_custom() { $note = Util_Request::get_string( 'note' ); do_action( "w3tc_hide_button_custom-{$note}" ); Util_Admin::redirect( array(), true ); } + /** + * Clear purge log + * + * @return void + */ public function w3tc_default_purgelog_clear() { $module = Util_Request::get_label( 'module' ); $log_filename = Util_Debug::log_filename( $module . '-purge' ); @@ -142,8 +193,12 @@ public function w3tc_default_purgelog_clear() { ); } - function w3tc_default_remove_add_in() { - + /** + * Remove add-in + * + * @return void + */ + public function w3tc_default_remove_add_in() { $module = Util_Request::get_string( 'w3tc_default_remove_add_in' ); // in the case of missing permissions to delete @@ -157,7 +212,7 @@ function w3tc_default_remove_add_in() { $dst = W3TC_ADDIN_FILE_ADVANCED_CACHE; try { Util_WpFile::copy_file( $src, $dst ); - } catch ( Util_WpFile_FilesystemOperationException $ex ) { + } catch ( Util_WpFile_FilesystemOperationException $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch // missing exception handle? } break; @@ -181,7 +236,7 @@ function w3tc_default_remove_add_in() { * * @return void */ - function w3tc_save_options() { + public function w3tc_save_options() { $redirect_data = $this->_w3tc_save_options_process(); Util_Admin::redirect_with_custom_messages2( $redirect_data ); } @@ -207,6 +262,11 @@ public function w3tc_default_save_and_flush() { Util_Admin::redirect_with_custom_messages2( $redirect_data ); } + /** + * Process save options + * + * @return array + */ private function _w3tc_save_options_process() { $data = array( 'old_config' => $this->_config, @@ -542,6 +602,13 @@ private function _w3tc_save_options_process() { ); } + /** + * Delete htaccess files + * + * @param string $dir directory. + * + * @return void + */ private function _delete_all_htaccess_files( $dir ) { if ( ! is_dir( $dir ) ) { return; @@ -552,7 +619,7 @@ private function _delete_all_htaccess_files( $dir ) { return; } - while ( false !== ( $file = readdir( $handle ) ) ) { + while ( false !== ( $file = readdir( $handle ) ) ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition if ( '.' === $file || '..' === $file ) { continue; } @@ -651,10 +718,11 @@ public function disable_cookie_domain() { /** * Checks COOKIE_DOMAIN definition existence * - * @param string $content - * @return int + * @param string $content Content. + * + * @return int|bool */ - function is_cookie_domain_define( $content ) { + public function is_cookie_domain_define( $content ) { return preg_match( W3TC_PLUGIN_TOTALCACHE_REGEXP_COOKIEDOMAIN, $content ); } @@ -662,7 +730,8 @@ function is_cookie_domain_define( $content ) { /** * Returns true if config section is sealed * - * @param string $section + * @param string $section Section. + * * @return boolean */ protected function is_sealed( $section ) { @@ -672,9 +741,11 @@ protected function is_sealed( $section ) { /** * Reads config from request * - * @param Config $config + * @param Config $config Config. + * + * @return void */ - function read_request( $config ) { + public function read_request( $config ) { $request = Util_Request::get_request(); include W3TC_DIR . '/ConfigKeys.php'; // define $keys. diff --git a/Generic_AdminActions_Flush.php b/Generic_AdminActions_Flush.php index 2ec8d5fe3..467d99f65 100644 --- a/Generic_AdminActions_Flush.php +++ b/Generic_AdminActions_Flush.php @@ -1,12 +1,32 @@ _config = Dispatcher::config(); } @@ -15,7 +35,7 @@ function __construct() { * * @return void */ - function w3tc_flush_all() { + public function w3tc_flush_all() { w3tc_flush_all( array( 'ui_action' => 'flush_button' ) ); $state_note = Dispatcher::config_state_note(); @@ -26,22 +46,28 @@ function w3tc_flush_all() { $this->_redirect_after_flush( 'flush_all' ); } - function w3tc_flush_current_page() { + /** + * Flush current page + * + * @return void + */ + public function w3tc_flush_current_page() { $url = filter_input( INPUT_GET, 'url', FILTER_SANITIZE_URL ); if ( empty( $url ) && isset( $_SERVER['HTTP_REFERER'] ) ) { $url = sanitize_text_field( wp_unslash( $_SERVER['HTTP_REFERER'] ) ); } + w3tc_flush_url( $url ); ?>
-

Page has been flushed successfully

- Return +

+
flush_memcached(); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_memcached' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_memcached', + ), + true + ); } /** @@ -65,12 +94,15 @@ function w3tc_flush_memcached() { * * @return void */ - function w3tc_flush_opcode() { + public function w3tc_flush_opcode() { $this->flush_opcode(); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_opcode' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_opcode', + ), + true + ); } /** @@ -78,12 +110,15 @@ function w3tc_flush_opcode() { * * @return void */ - function w3tc_flush_file() { + public function w3tc_flush_file() { $this->flush_file(); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_file' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_file', + ), + true + ); } /** @@ -91,7 +126,7 @@ function w3tc_flush_file() { * * @return void */ - function w3tc_flush_statics() { + public function w3tc_flush_statics() { $cf = Dispatcher::component( 'CacheFlush' ); $cf->browsercache_flush(); w3tc_flush_posts(); @@ -101,11 +136,14 @@ function w3tc_flush_statics() { $state_note->set( 'common.show_note.flush_posts_needed', false ); $state_note->set( 'common.show_note.plugins_updated', false ); - Util_Admin::redirect_with_custom_messages2( array( + Util_Admin::redirect_with_custom_messages2( + array( 'notes' => array( - __( 'Static files cache successfully emptied.', 'w3-total-cache' ) - ) - ), true ); + __( 'Static files cache successfully emptied.', 'w3-total-cache' ), + ), + ), + true + ); } /** @@ -113,7 +151,7 @@ function w3tc_flush_statics() { * * @return void */ - function w3tc_flush_posts() { + public function w3tc_flush_posts() { w3tc_flush_posts(); $state_note = Dispatcher::config_state_note(); @@ -128,16 +166,19 @@ function w3tc_flush_posts() { * * @return void */ - function w3tc_flush_pgcache() { + public function w3tc_flush_pgcache() { w3tc_flush_posts( array( 'ui_action' => 'flush_button' ) ); $state_note = Dispatcher::config_state_note(); $state_note->set( 'common.show_note.flush_posts_needed', false ); $state_note->set( 'common.show_note.plugins_updated', false ); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_pgcache' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_pgcache', + ), + true + ); } /** @@ -145,12 +186,15 @@ function w3tc_flush_pgcache() { * * @return void */ - function w3tc_flush_dbcache() { + public function w3tc_flush_dbcache() { $this->flush_dbcache(); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_dbcache' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_dbcache', + ), + true + ); } /** @@ -158,33 +202,37 @@ function w3tc_flush_dbcache() { * * @return void */ - function w3tc_flush_objectcache() { + public function w3tc_flush_objectcache() { $this->flush_objectcache(); $state_note = Dispatcher::config_state_note(); $state_note->set( 'objectcache.show_note.flush_needed', false ); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_objectcache' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_objectcache', + ), + true + ); } - /** * Flush fragment cache action * * @return void */ - function w3tc_flush_fragmentcache() { + public function w3tc_flush_fragmentcache() { $this->flush_fragmentcache(); $this->_config->set( 'notes.need_empty_fragmentcache', false ); - $this->_config->save(); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_fragmentcache' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_fragmentcache', + ), + true + ); } /** @@ -192,15 +240,18 @@ function w3tc_flush_fragmentcache() { * * @return void */ - function w3tc_flush_minify() { + public function w3tc_flush_minify() { $this->flush_minify(); $state_note = Dispatcher::config_state_note(); $state_note->set( 'minify.show_note.need_flush', false ); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_minify' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_minify', + ), + true + ); } /** @@ -208,7 +259,7 @@ function w3tc_flush_minify() { * * @return void */ - function w3tc_flush_browser_cache() { + public function w3tc_flush_browser_cache() { $cacheflush = Dispatcher::component( 'CacheFlush' ); $cacheflush->browsercache_flush(); @@ -216,31 +267,44 @@ function w3tc_flush_browser_cache() { $state_note->set( 'common.show_note.flush_statics_needed', false ); $state_note->set( 'common.show_note.flush_posts_needed', true ); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_browser_cache' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_browser_cache', + ), + true + ); } - /* + /** * Flush varnish cache + * + * @return void */ - function w3tc_flush_varnish() { + public function w3tc_flush_varnish() { $this->flush_varnish(); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_varnish' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_varnish', + ), + true + ); } - /* + /** * Flush CDN mirror + * + * @return void */ - function w3tc_flush_cdn() { + public function w3tc_flush_cdn() { $this->flush_cdn( array( 'ui_action' => 'flush_button' ) ); - Util_Admin::redirect( array( - 'w3tc_note' => 'flush_cdn' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'flush_cdn', + ), + true + ); } @@ -249,26 +313,30 @@ function w3tc_flush_cdn() { * * @return void */ - function w3tc_flush_post() { + public function w3tc_flush_post() { $post_id = Util_Request::get_integer( 'post_id' ); w3tc_flush_post( $post_id, true, array( 'ui_action' => 'flush_button' ) ); - Util_Admin::redirect( array( - 'w3tc_note' => 'pgcache_purge_post' - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => 'pgcache_purge_post', + ), + true + ); } /** * Flush specified cache * - * @param string $type + * @param string $type Type. + * * @return void */ - function flush( $type ) { - $state = Dispatcher::config_state(); + public function flush( $type ) { + $state = Dispatcher::config_state(); $state_note = Dispatcher::config_state_note(); - if ( $this->_config->get_string( 'pgcache.engine' ) == $type && $this->_config->get_boolean( 'pgcache.enabled' ) ) { + if ( $this->_config->get_string( 'pgcache.engine' ) === $type && $this->_config->get_boolean( 'pgcache.enabled' ) ) { $state_note->set( 'common.show_note.flush_posts_needed', false ); $state_note->set( 'common.show_note.plugins_updated', false ); @@ -277,19 +345,19 @@ function flush( $type ) { $pgcacheflush->flush_post_cleanup(); } - if ( $this->_config->get_string( 'dbcache.engine' ) == $type && $this->_config->get_boolean( 'dbcache.enabled' ) ) { + if ( $this->_config->get_string( 'dbcache.engine' ) === $type && $this->_config->get_boolean( 'dbcache.enabled' ) ) { $this->flush_dbcache(); } - if ( $this->_config->get_string( 'objectcache.engine' ) == $type && $this->_config->getf_boolean( 'objectcache.enabled' ) ) { + if ( $this->_config->get_string( 'objectcache.engine' ) === $type && $this->_config->getf_boolean( 'objectcache.enabled' ) ) { $this->flush_objectcache(); } - if ( $this->_config->get_string( array( 'fragmentcache', 'engine' ) ) == $type ) { + if ( $this->_config->get_string( array( 'fragmentcache', 'engine' ) ) === $type ) { $this->flush_fragmentcache(); } - if ( $this->_config->get_string( 'minify.engine' ) == $type && $this->_config->get_boolean( 'minify.enabled' ) ) { + if ( $this->_config->get_string( 'minify.engine' ) === $type && $this->_config->get_boolean( 'minify.enabled' ) ) { $state_note->set( 'minify.show_note.need_flush', false ); $this->flush_minify(); } @@ -300,7 +368,7 @@ function flush( $type ) { * * @return void */ - function flush_memcached() { + public function flush_memcached() { $this->flush( 'memcached' ); } @@ -309,7 +377,7 @@ function flush_memcached() { * * @return void */ - function flush_opcode() { + public function flush_opcode() { $cacheflush = Dispatcher::component( 'CacheFlush' ); $cacheflush->opcache_flush(); } @@ -319,7 +387,7 @@ function flush_opcode() { * * @return void */ - function flush_file() { + public function flush_file() { $this->flush( 'file' ); $this->flush( 'file_generic' ); } @@ -329,7 +397,7 @@ function flush_file() { * * @return void */ - function flush_dbcache() { + public function flush_dbcache() { $flusher = Dispatcher::component( 'CacheFlush' ); $flusher->dbcache_flush(); } @@ -339,15 +407,17 @@ function flush_dbcache() { * * @return void */ - function flush_objectcache() { + public function flush_objectcache() { $flusher = Dispatcher::component( 'CacheFlush' ); $flusher->objectcache_flush(); } /** * Flush fragment cache + * + * @return void */ - function flush_fragmentcache() { + public function flush_fragmentcache() { $flusher = Dispatcher::component( 'CacheFlush' ); $flusher->fragmentcache_flush(); } @@ -357,17 +427,19 @@ function flush_fragmentcache() { * * @return void */ - function flush_minify() { + public function flush_minify() { $w3_minify = Dispatcher::component( 'Minify_MinifiedFileRequestHandler' ); $w3_minify->flush(); } /** * Flush varnish cache + * + * @return void */ - function flush_varnish() { + public function flush_varnish() { // this attaches execute_delayed_operations! otherwise - // specific module flush will not have effect + // specific module flush will not have effect. $cacheflush = Dispatcher::component( 'CacheFlush' ); $varnishflush = Dispatcher::component( 'Varnish_Flush' ); @@ -376,32 +448,50 @@ function flush_varnish() { /** * Flush CDN mirror + * + * @param array $extras Extras. + * + * @return void */ - function flush_cdn( $extras = array() ) { + public function flush_cdn( $extras = array() ) { $cacheflush = Dispatcher::component( 'CacheFlush' ); $cacheflush->cdn_purge_all( $extras ); } - + /** + * Redirect after flush + * + * @param string $success_note Success note. + * + * @return void + */ private function _redirect_after_flush( $success_note ) { - $flush = Dispatcher::component( 'CacheFlush' ); + $flush = Dispatcher::component( 'CacheFlush' ); $status = $flush->execute_delayed_operations(); $errors = array(); foreach ( $status as $i ) { - if ( isset( $i['error'] ) ) + if ( isset( $i['error'] ) ) { $errors[] = $i['error']; + } } if ( empty( $errors ) ) { - Util_Admin::redirect( array( - 'w3tc_note' => $success_note - ), true ); + Util_Admin::redirect( + array( + 'w3tc_note' => $success_note, + ), + true + ); } else { - Util_Admin::redirect_with_custom_messages2( array( - 'errors' => array( 'Failed to purge: ' . - implode( ', ', $errors ) ) - ), true ); + Util_Admin::redirect_with_custom_messages2( + array( + 'errors' => array( + 'Failed to purge: ' . implode( ', ', $errors ), + ), + ), + true + ); } } } diff --git a/Generic_AdminActions_Test.php b/Generic_AdminActions_Test.php index 48bba78a6..bb41ba5dc 100644 --- a/Generic_AdminActions_Test.php +++ b/Generic_AdminActions_Test.php @@ -1,10 +1,26 @@ _config = Dispatcher::config(); - - $this->_page = Util_Admin::get_current_page(); + $this->_page = Util_Admin::get_current_page(); } - /** * Test memcached * * @return void */ - function w3tc_test_memcached() { - $servers = Util_Request::get_array( 'servers' ); + public function w3tc_test_memcached() { + $servers = Util_Request::get_array( 'servers' ); $binary_protocol = Util_Request::get_boolean( 'binary_protocol', true ); $username = Util_Request::get_string( 'username', '' ); $password = Util_Request::get_string( 'password', '' ); @@ -37,11 +56,13 @@ function w3tc_test_memcached() { /** * Test redis + * + * @return void */ public function w3tc_test_redis() { $servers = Util_Request::get_array( 'servers' ); - $verify_tls_certificates = Util_Request::get_boolean('verify_tls_certificates', true ); - $password = Util_Request::get_string('password', ''); + $verify_tls_certificates = Util_Request::get_boolean( 'verify_tls_certificates', true ); + $password = Util_Request::get_string( 'password', '' ); $dbid = Util_Request::get_integer( 'dbid', 0 ); if ( empty( $servers ) ) { @@ -81,16 +102,23 @@ public function w3tc_test_redis() { $this->respond_test_result( $success ); } + /** + * Return response results + * + * @param bool $success Success. + * + * @return void + */ private function respond_test_result( $success ) { if ( $success ) { $response = array( 'result' => true, - 'error' => __( 'Test passed.', 'w3-total-cache' ) + 'error' => __( 'Test passed.', 'w3-total-cache' ), ); } else { $response = array( 'result' => false, - 'error' => __( 'Test failed.', 'w3-total-cache' ) + 'error' => __( 'Test failed.', 'w3-total-cache' ), ); } @@ -103,93 +131,105 @@ private function respond_test_result( $success ) { * * @return void */ - function w3tc_test_minifier() { - $engine = Util_Request::get_string( 'engine' ); + public function w3tc_test_minifier() { + $engine = Util_Request::get_string( 'engine' ); $path_java = Util_Request::get_string( 'path_java' ); - $path_jar = Util_Request::get_string( 'path_jar' ); + $path_jar = Util_Request::get_string( 'path_jar' ); $result = false; - $error = ''; + $error = ''; - if ( $engine != 'googleccjs' ) { - if ( !$path_java ) + if ( 'googleccjs' !== $engine ) { + if ( ! $path_java ) { $error = __( 'Empty JAVA executable path.', 'w3-total-cache' ); - elseif ( !$path_jar ) + } elseif ( ! $path_jar ) { $error = __( 'Empty JAR file path.', 'w3-total-cache' ); + } } if ( empty( $error ) ) { switch ( $engine ) { - case 'yuijs': - \W3TCL\Minify\Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); - \W3TCL\Minify\Minify_YUICompressor::$javaExecutable = $path_java; - \W3TCL\Minify\Minify_YUICompressor::$jarFile = $path_jar; - - $result = \W3TCL\Minify\Minify_YUICompressor::testJs( $error ); - break; + case 'yuijs': + \W3TCL\Minify\Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); + \W3TCL\Minify\Minify_YUICompressor::$javaExecutable = $path_java; + \W3TCL\Minify\Minify_YUICompressor::$jarFile = $path_jar; - case 'yuicss': - \W3TCL\Minify\Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); - \W3TCL\Minify\Minify_YUICompressor::$javaExecutable = $path_java; - \W3TCL\Minify\Minify_YUICompressor::$jarFile = $path_jar; + $result = \W3TCL\Minify\Minify_YUICompressor::testJs( $error ); + break; - $result = \W3TCL\Minify\Minify_YUICompressor::testCss( $error ); - break; + case 'yuicss': + \W3TCL\Minify\Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); + \W3TCL\Minify\Minify_YUICompressor::$javaExecutable = $path_java; + \W3TCL\Minify\Minify_YUICompressor::$jarFile = $path_jar; - case 'ccjs': - \W3TCL\Minify\Minify_ClosureCompiler::$tempDir = Util_File::create_tmp_dir(); - \W3TCL\Minify\Minify_ClosureCompiler::$javaExecutable = $path_java; - \W3TCL\Minify\Minify_ClosureCompiler::$jarFile = $path_jar; + $result = \W3TCL\Minify\Minify_YUICompressor::testCss( $error ); + break; - $result = \W3TCL\Minify\Minify_ClosureCompiler::test( $error ); - break; + case 'ccjs': + \W3TCL\Minify\Minify_ClosureCompiler::$tempDir = Util_File::create_tmp_dir(); + \W3TCL\Minify\Minify_ClosureCompiler::$javaExecutable = $path_java; + \W3TCL\Minify\Minify_ClosureCompiler::$jarFile = $path_jar; - case 'googleccjs': + $result = \W3TCL\Minify\Minify_ClosureCompiler::test( $error ); + break; - $result = \W3TCL\Minify\Minify_JS_ClosureCompiler::test( $error ); - break; + case 'googleccjs': + $result = \W3TCL\Minify\Minify_JS_ClosureCompiler::test( $error ); + break; - default: - $error = __( 'Invalid engine.', 'w3-total-cache' ); - break; + default: + $error = __( 'Invalid engine.', 'w3-total-cache' ); + break; } } $response = array( 'result' => $result, - 'error' => $error + 'error' => $error, ); - echo json_encode( $response ); + echo wp_json_encode( $response ); } /** * Check if memcache is available * - * @param array $servers + * @param array $servers Servers. + * @param string $binary_protocol Binary Protocol. + * @param string $username Username. + * @param string $password Password. + * * @return boolean */ private function is_memcache_available( $servers, $binary_protocol, $username, $password ) { - if ( count( $servers ) <= 0 ) + if ( count( $servers ) <= 0 ) { return false; + } foreach ( $servers as $server ) { - @$memcached = Cache::instance( 'memcached', array( - 'servers' => $server, - 'persistent' => false, + @$memcached = Cache::instance( + 'memcached', + array( + 'servers' => $server, + 'persistent' => false, 'binary_protocol' => $binary_protocol, - 'username' => $username, - 'password' => $password - ) ); - if ( is_null( $memcached ) ) + 'username' => $username, + 'password' => $password, + ) + ); + + if ( is_null( $memcached ) ) { return false; + } $test_string = sprintf( 'test_' . md5( time() ) ); - $test_value = array( 'content' => $test_string ); + $test_value = array( 'content' => $test_string ); $memcached->set( $test_string, $test_value, 60 ); $test_value = $memcached->get( $test_string ); - if ( $test_value['content'] != $test_string ) + + if ( $test_value['content'] !== $test_string ) { return false; + } } return true; @@ -197,8 +237,10 @@ private function is_memcache_available( $servers, $binary_protocol, $username, $ /** * Self test action + * + * @return void */ - function w3tc_test_self() { + public function w3tc_test_self() { include W3TC_INC_LIGHTBOX_DIR . '/self_test.php'; } @@ -207,7 +249,7 @@ function w3tc_test_self() { * * @return void */ - function w3tc_test_minify_recommendations() { + public function w3tc_test_minify_recommendations() { $options_minify = new Minify_Page(); $options_minify->recommendations(); } diff --git a/Generic_AdminNotes.php b/Generic_AdminNotes.php index 3837db31c..163bc92de 100644 --- a/Generic_AdminNotes.php +++ b/Generic_AdminNotes.php @@ -15,6 +15,7 @@ class Generic_AdminNotes { * W3TC admin notices. * * @param array $notes Notices. + * * @return string */ public function w3tc_notes( $notes ) { diff --git a/Generic_ConfigLabels.php b/Generic_ConfigLabels.php index 15a2cc734..c02d0e209 100644 --- a/Generic_ConfigLabels.php +++ b/Generic_ConfigLabels.php @@ -1,30 +1,47 @@ __( 'Enable cache purge via Amazon SNS', 'w3-total-cache' ), - 'cluster.messagebus.sns.region' => __( 'Amazon SNS region:', 'w3-total-cache' ), - 'cluster.messagebus.sns.api_key' => __( 'API key:', 'w3-total-cache' ), - 'cluster.messagebus.sns.api_secret' => __( 'API secret:', 'w3-total-cache' ), - 'cluster.messagebus.sns.topic_arn' => __( 'Topic ID:', 'w3-total-cache' ), - 'cluster.messagebus.debug' => __( 'Message Bus', 'w3-total-cache' ), - 'widget.pagespeed.access_token' => __( 'Authorize :', 'w3-total-cache' ), + return array_merge( + $config_labels, + array( + 'cluster.messagebus.enabled' => __( 'Enable cache purge via Amazon SNS', 'w3-total-cache' ), + 'cluster.messagebus.sns.region' => __( 'Amazon SNS region:', 'w3-total-cache' ), + 'cluster.messagebus.sns.api_key' => __( 'API key:', 'w3-total-cache' ), + 'cluster.messagebus.sns.api_secret' => __( 'API secret:', 'w3-total-cache' ), + 'cluster.messagebus.sns.topic_arn' => __( 'Topic ID:', 'w3-total-cache' ), + 'cluster.messagebus.debug' => __( 'Message Bus', 'w3-total-cache' ), + 'widget.pagespeed.access_token' => __( 'Authorize :', 'w3-total-cache' ), 'widget.pagespeed.w3tc_pagespeed_key' => __( 'W3 API Key:', 'w3-total-cache' ), - 'common.force_master' => __( 'Use single network configuration file for all sites.', 'w3-total-cache' ), - 'config.path' => __( 'Nginx server configuration file path', 'w3-total-cache' ), - 'config.check' => __( 'Verify rewrite rules', 'w3-total-cache' ), - 'plugin.license_key' => __( 'License:', 'w3-total-cache' ), - - 'referrer.enabled' => __( 'Referrers:', 'w3-total-cache' ), - 'referrer.rgroups' => __( 'Referrer groups', 'w3-total-cache' ), - 'mobile.enabled' => __( 'User Agents:', 'w3-total-cache' ), - 'mobile.rgroups' => __( 'User Agent groups', 'w3-total-cache' ), - - 'varnish.enabled' => __( 'Enable reverse proxy caching via varnish', 'w3-total-cache' ), - 'varnish.debug' => __( 'Reverse Proxy', 'w3-total-cache' ), - 'varnish.servers' => __( 'Varnish servers:', 'w3-total-cache' ) - ) ); + 'common.force_master' => __( 'Use single network configuration file for all sites.', 'w3-total-cache' ), + 'config.path' => __( 'Nginx server configuration file path', 'w3-total-cache' ), + 'config.check' => __( 'Verify rewrite rules', 'w3-total-cache' ), + 'plugin.license_key' => __( 'License:', 'w3-total-cache' ), + 'referrer.enabled' => __( 'Referrers:', 'w3-total-cache' ), + 'referrer.rgroups' => __( 'Referrer groups', 'w3-total-cache' ), + 'mobile.enabled' => __( 'User Agents:', 'w3-total-cache' ), + 'mobile.rgroups' => __( 'User Agent groups', 'w3-total-cache' ), + 'varnish.enabled' => __( 'Enable reverse proxy caching via varnish', 'w3-total-cache' ), + 'varnish.debug' => __( 'Reverse Proxy', 'w3-total-cache' ), + 'varnish.servers' => __( 'Varnish servers:', 'w3-total-cache' ), + ) + ); } } diff --git a/Generic_Environment.php b/Generic_Environment.php index 9f29b99b3..308ad6775 100644 --- a/Generic_Environment.php +++ b/Generic_Environment.php @@ -1,10 +1,19 @@ unschedule_purge_wpcron(); - if ( count( $exs->exceptions() ) > 0 ) + if ( count( $exs->exceptions() ) > 0 ) { throw $exs; + } } /** * Returns required rules for module * - * @var Config $config - * @return array + * @param Config $config Config. + * + * @return null */ - function get_required_rules( $config ) { + public function get_required_rules( $config ) { return null; } /** * Checks if addins in wp-content is available and correct version. * - * @param unknown $config - * @param Util_Environment_Exceptions $exs + * @param unknown $config Config. + * @param Util_Environment_Exceptions $exs Enfironment exceptions. + * + * @return void */ private function create_required_files( $config, $exs ) { $src = W3TC_INSTALL_FILE_ADVANCED_CACHE; @@ -95,22 +109,35 @@ private function create_required_files( $config, $exs ) { if ( $this->advanced_cache_installed() ) { if ( $this->is_advanced_cache_add_in() ) { - $script_data = @file_get_contents( $dst ); - if ( $script_data == @file_get_contents( $src ) ) - return; - } else if ( get_transient( 'w3tc_remove_add_in_pgcache' ) == 'yes' ) { - // user already manually asked to remove another plugin's add in, - // we should try to apply ours - // (in case of missing permissions deletion could fail) - } else if ( !$this->advanced_cache_check_old_add_in() ) { - $remove_url = Util_Ui::admin_url( 'admin.php?page=w3tc_dashboard&w3tc_default_remove_add_in=pgcache' ); - - $exs->push( new Util_WpFile_FilesystemOperationException( - sprintf( __( 'The Page Cache add-in file advanced-cache.php is not a W3 Total Cache drop-in. - It should be removed. %s', 'w3-total-cache' ), - Util_Ui::button_link( __( 'Yes, remove it for me', 'w3-total-cache' ), wp_nonce_url( $remove_url, 'w3tc' ) ) ) ) ); + $script_data = @wp_remote_get( $dst ); + if ( @wp_remote_get( $src ) === $script_data ) { return; } + } elseif ( 'yes' === get_transient( 'w3tc_remove_add_in_pgcache' ) ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedElseif + /** + * User already manually asked to remove another plugin's add in, we should + * try to apply ours (in case of missing permissions deletion could fail). + */ + } elseif ( ! $this->advanced_cache_check_old_add_in() ) { + $remove_url = Util_Ui::admin_url( 'admin.php?page=w3tc_dashboard&w3tc_default_remove_add_in=pgcache' ); + + $exs->push( + new Util_WpFile_FilesystemOperationException( + sprintf( + // Translators: 1 button link. + __( + 'The Page Cache add-in file advanced-cache.php is not a W3 Total Cache drop-in. It should be removed. %s', + 'w3-total-cache' + ), + Util_Ui::button_link( + __( 'Yes, remove it for me', 'w3-total-cache' ), + wp_nonce_url( $remove_url, 'w3tc' ) + ) + ) + ) + ); + return; + } } try { @@ -123,12 +150,15 @@ private function create_required_files( $config, $exs ) { /** * Checks if addins in wp-content are available and deletes them. * - * @param Util_Environment_Exceptions $exs + * @param Util_Environment_Exceptions $exs Environment exceptions. + * + * @return void */ private function delete_required_files( $exs ) { try { - if ( $this->is_advanced_cache_add_in() ) + if ( $this->is_advanced_cache_add_in() ) { Util_WpFile::delete_file( W3TC_ADDIN_FILE_ADVANCED_CACHE ); + } } catch ( Util_WpFile_FilesystemOperationException $ex ) { $exs->push( $ex ); } @@ -137,38 +167,41 @@ private function delete_required_files( $exs ) { /** * Checks if addins in wp-content is available and correct version. * - * @param Util_Environment_Exceptions $exs + * @param Util_Environment_Exceptions $exs Environment exceptions. + * + * @return void */ private function create_required_folders( $exs ) { - // folders that we create if not exists + // Folders that we create if not exists. $directories = array( - W3TC_CACHE_DIR + W3TC_CACHE_DIR, ); - if ( !(defined( 'W3TC_CONFIG_DATABASE' ) && W3TC_CONFIG_DATABASE ) ) { + if ( ! ( defined( 'W3TC_CONFIG_DATABASE' ) && W3TC_CONFIG_DATABASE ) ) { $directories[] = W3TC_CONFIG_DIR; } foreach ( $directories as $directory ) { - try{ + try { Util_WpFile::create_writeable_folder( $directory, WP_CONTENT_DIR ); } catch ( Util_WpFile_FilesystemOperationException $ex ) { $exs->push( $ex ); } } - // folders that we delete if exists and not writeable + // folders that we delete if exists and not writeable. $directories = array( W3TC_CACHE_TMP_DIR, W3TC_CACHE_BLOGMAP_FILENAME, W3TC_CACHE_DIR . '/object', - W3TC_CACHE_DIR . '/db' + W3TC_CACHE_DIR . '/db', ); foreach ( $directories as $directory ) { - try{ - if ( file_exists( $directory ) && !is_writeable( $directory ) ) + try { + if ( file_exists( $directory ) && ! is_writeable( $directory ) ) { Util_WpFile::delete_folder( $directory ); + } } catch ( Util_WpFile_FilesystemRmdirException $ex ) { $exs->push( $ex ); } @@ -177,15 +210,20 @@ private function create_required_folders( $exs ) { /** * Adds index files + * + * @return void */ private function add_index_to_folders() { $directories = array( W3TC_CACHE_DIR, - W3TC_CONFIG_DIR ); + W3TC_CONFIG_DIR, + ); + $add_files = array(); foreach ( $directories as $dir ) { - if ( is_dir( $dir ) && !file_exists( $dir . '/index.html' ) ) + if ( is_dir( $dir ) && ! file_exists( $dir . '/index.html' ) ) { @file_put_contents( $dir . '/index.html', '' ); + } } } @@ -204,8 +242,8 @@ public function advanced_cache_installed() { * @return boolean */ public function advanced_cache_check_old_add_in() { - return ( ( $script_data = @file_get_contents( W3TC_ADDIN_FILE_ADVANCED_CACHE ) ) - && strstr( $script_data, 'w3_instance' ) !== false ); + $script_data = @file_get_contents( W3TC_ADDIN_FILE_ADVANCED_CACHE ); + return ( $script_data && strstr( $script_data, 'w3_instance' ) !== false ); } /** @@ -214,8 +252,8 @@ public function advanced_cache_check_old_add_in() { * @return boolean */ public function is_advanced_cache_add_in() { - return ( ( $script_data = @file_get_contents( W3TC_ADDIN_FILE_ADVANCED_CACHE ) ) - && strstr( $script_data, 'PgCache_ContentGrabber' ) !== false ); + $script_data = @file_get_contents( W3TC_ADDIN_FILE_ADVANCED_CACHE ); + return ( $script_data && strstr( $script_data, 'PgCache_ContentGrabber' ) !== false ); } /** diff --git a/Generic_Faq.php b/Generic_Faq.php index e1a72eaa7..6d50ebda3 100644 --- a/Generic_Faq.php +++ b/Generic_Faq.php @@ -1,61 +1,94 @@ column where to show + /** + * Get sections + * + * @return array + */ + public static function sections() { + // name => column where to show. return array( - 'General' => 'https://api.w3-edge.com/v1/faq/general', - 'Usage' => 'https://api.w3-edge.com/v1/faq/usage', - 'Compatibility' => 'https://api.w3-edge.com/v1/faq/compatibility', - 'Minification' => 'https://api.w3-edge.com/v1/faq/minification', - 'CDN' => 'https://api.w3-edge.com/v1/faq/cdn', - 'Browser Cache' => 'https://api.w3-edge.com/v1/faq/browser-cache', + 'General' => 'https://api.w3-edge.com/v1/faq/general', + 'Usage' => 'https://api.w3-edge.com/v1/faq/usage', + 'Compatibility' => 'https://api.w3-edge.com/v1/faq/compatibility', + 'Minification' => 'https://api.w3-edge.com/v1/faq/minification', + 'CDN' => 'https://api.w3-edge.com/v1/faq/cdn', + 'Browser Cache' => 'https://api.w3-edge.com/v1/faq/browser-cache', 'Errors / Debugging' => 'https://api.w3-edge.com/v1/faq/errors-debugging', - 'Requirements' => 'https://api.w3-edge.com/v1/faq/requirements', - 'Developers' => 'https://api.w3-edge.com/v1/faq/developers', - 'Extensions' => 'https://api.w3-edge.com/v1/faq/extensions', - 'Installation' => 'https://api.w3-edge.com/v1/faq/installation' + 'Requirements' => 'https://api.w3-edge.com/v1/faq/requirements', + 'Developers' => 'https://api.w3-edge.com/v1/faq/developers', + 'Extensions' => 'https://api.w3-edge.com/v1/faq/extensions', + 'Installation' => 'https://api.w3-edge.com/v1/faq/installation', ); } /** * Returns list of questions for section + * + * @param string $section Section. + * + * @return array|null */ - static public function parse( $section ) { + public static function parse( $section ) { $faq = array(); $sections = self::sections(); - if ( !isset( $sections[ $section ] ) ) { + if ( ! isset( $sections[ $section ] ) ) { return null; } $url = $sections[ $section ]; - $response = wp_remote_get( $url ); if ( is_wp_error( $response ) ) { return null; } - $html = $response['body']; + $html = $response['body']; $questions = array(); $m = array(); - preg_match_all( '~

\s*]+href="(#[^"]+)[^>]+>.*?([^<]+)

~mi', - $html, $m ); + preg_match_all( + '~

\s*]+href="(#[^"]+)[^>]+>.*?([^<]+)

~mi', + $html, + $m + ); + if ( is_array( $m ) && count( $m ) > 1 ) { - for ( $n = 0; $n < count( $m[1] ); $n++ ) { - $questions[] = array('q' => $m[2][$n], 'a' => $url . $m[1][$n] ); + $count = count( $m[1] ); + for ( $n = 0; $n < $count; $n++ ) { + $questions[] = array( + 'q' => $m[2][ $n ], + 'a' => $url . $m[1][ $n ], + ); } } $m = array(); - preg_match_all( '~
  • \s*]+href="([^"]+)[^>]+>(.*?)\s*[.]s*
  • ~mi', - $html, $m ); + preg_match_all( + '~
  • \s*]+href="([^"]+)[^>]+>(.*?)\s*[.]s*
  • ~mi', + $html, + $m + ); + if ( is_array( $m ) && count( $m ) > 1 ) { - for ( $n = 0; $n < count( $m[1] ); $n++ ) { - $questions[] = array('q' => $m[2][$n], 'a' => $m[1][$n] ); + $count = count( $m[1] ); + for ( $n = 0; $n < $count; $n++ ) { + $questions[] = array( + 'q' => $m[2][ $n ], + 'a' => $m[1][ $n ], + ); } } diff --git a/Generic_Page_About.php b/Generic_Page_About.php index 9c16b8c34..a479393b4 100644 --- a/Generic_Page_About.php +++ b/Generic_Page_About.php @@ -1,8 +1,18 @@ _config_master; $browsercache_enabled = $module_status->is_enabled( 'browsercache' ); @@ -39,10 +60,10 @@ function view() { $can_empty_varnish = $module_status->can_empty_varnish(); - $cdn_enabled = $module_status->is_enabled( 'cdn' ); + $cdn_enabled = $module_status->is_enabled( 'cdn' ); $cdn_mirror_purge = Cdn_Util::can_purge_all( $module_status->get_module_engine( 'cdn' ) ); - // Required for Update Media Query String button + // Required for Update Media Query String button. $browsercache_update_media_qs = ( $this->_config->get_boolean( 'browsercache.cssjs.replace' ) || $this->_config->get_boolean( 'browsercache.other.replace' ) ); include W3TC_INC_DIR . '/options/dashboard.php'; diff --git a/Generic_Page_General.php b/Generic_Page_General.php index c511dfa91..7a44ba75a 100644 --- a/Generic_Page_General.php +++ b/Generic_Page_General.php @@ -1,8 +1,19 @@ render_content(); exit; } - $current_user = wp_get_current_user(); + $current_user = wp_get_current_user(); $config_master = $this->_config_master; - /** - * - * - * @var $modules W3_ModuleStatus - */ + $modules = Dispatcher::component( 'ModuleStatus' ); - $pgcache_enabled = $modules->is_enabled( 'pgcache' ); - $dbcache_enabled = $modules->is_enabled( 'dbcache' ); - $objectcache_enabled = $modules->is_enabled( 'objectcache' ); + + $pgcache_enabled = $modules->is_enabled( 'pgcache' ); + $dbcache_enabled = $modules->is_enabled( 'dbcache' ); + $objectcache_enabled = $modules->is_enabled( 'objectcache' ); $browsercache_enabled = $modules->is_enabled( 'browsercache' ); - $minify_enabled = $modules->is_enabled( 'minify' ); - $cdn_enabled = $modules->is_enabled( 'cdn' ); - $varnish_enabled = $modules->is_enabled( 'varnish' ); + $minify_enabled = $modules->is_enabled( 'minify' ); + $cdn_enabled = $modules->is_enabled( 'cdn' ); + $varnish_enabled = $modules->is_enabled( 'varnish' ); $enabled = $modules->plugin_is_enabled(); $check_rules = Util_Rule::can_check_rules(); - $disc_enhanced_enabled = !( ! $check_rules || ( !$this->is_master() && Util_Environment::is_wpmu() && $config_master->get_string( 'pgcache.engine' ) != 'file_generic' ) ); + + $disc_enhanced_enabled = $check_rules && ( + $this->is_master() || ! ( + Util_Environment::is_wpmu() && $config_master->get_string( 'pgcache.engine' ) !== 'file_generic' + ) + ); $can_empty_file = $modules->can_empty_file(); @@ -56,16 +78,19 @@ function view() { $cdn_mirror_purge = Cdn_Util::can_purge_all( $modules->get_module_engine( 'cdn' ) ); - - $file_nfs = ( $this->_config->get_boolean( 'pgcache.file.nfs' ) || $this->_config->get_boolean( 'minify.file.nfs' ) ); + $file_nfs = ( $this->_config->get_boolean( 'pgcache.file.nfs' ) || $this->_config->get_boolean( 'minify.file.nfs' ) ); $file_locking = ( $this->_config->get_boolean( 'dbcache.file.locking' ) || $this->_config->get_boolean( 'objectcache.file.locking' ) || $this->_config->get_boolean( 'pgcache.file.locking' ) || $this->_config->get_boolean( 'minify.file.locking' ) ); - $licensing_visible = ( ( !Util_Environment::is_wpmu() || is_network_admin() ) && - !ini_get( 'w3tc.license_key' ) && - get_transient( 'w3tc_license_status' ) != 'host_valid' ); + $licensing_visible = ( + ( ! Util_Environment::is_wpmu() || is_network_admin() ) && + ! ini_get( 'w3tc.license_key' ) && + get_transient( 'w3tc_license_status' ) !== 'host_valid' + ); + $is_pro = Util_Environment::is_w3tc_pro( $this->_config ); - $custom_areas = apply_filters( "w3tc_settings_general_anchors", array() ); + $custom_areas = apply_filters( 'w3tc_settings_general_anchors', array() ); + include W3TC_INC_DIR . '/options/general.php'; } } diff --git a/Generic_Page_PurgeLog.php b/Generic_Page_PurgeLog.php index 8bb8243be..e01d86f7d 100644 --- a/Generic_Page_PurgeLog.php +++ b/Generic_Page_PurgeLog.php @@ -1,27 +1,46 @@ starts_with( $p, ABSPATH ) ) { $p = substr( $p, strlen( ABSPATH ) ); } - $this->plugins_regexp = '~^(' . Util_Environment::preg_quote( $p ) . - '/)([^/]+)(.*)~'; + $this->plugins_regexp = '~^(' . Util_Environment::preg_quote( $p ) . '/)([^/]+)(.*)~'; } - - + /** + * Render content + * + * @return void + */ public function render_content() { - $module = Util_Request::get_label( 'module' ); + $module = Util_Request::get_label( 'module' ); $log_filename = Util_Debug::log_filename( $module . '-purge' ); if ( file_exists( $log_filename ) ) { $log_filefize = $this->to_human( filesize( $log_filename ) ); @@ -32,52 +51,73 @@ public function render_content() { $lines = Util_DebugPurgeLog_Reader::read( $module ); $purgelog_modules = array(); - $c = Dispatcher::config(); + $c = Dispatcher::config(); + if ( $c->get_boolean( 'pgcache.debug_purge' ) ) { $purgelog_modules[] = array( - 'label' => 'pagecache', - 'name' => 'Page Cache', - 'postfix' => '' + 'label' => 'pagecache', + 'name' => 'Page Cache', + 'postfix' => '', ); } + if ( $c->get_boolean( 'dbcache.debug_purge' ) ) { $purgelog_modules[] = array( - 'label' => 'dbcache', - 'name' => 'Database Cache', - 'postfix' => '' + 'label' => 'dbcache', + 'name' => 'Database Cache', + 'postfix' => '', ); } + if ( $c->get_boolean( 'objectcache.debug_purge' ) ) { $purgelog_modules[] = array( - 'label' => 'objectcache', - 'name' => 'Object Cache', - 'postfix' => '' + 'label' => 'objectcache', + 'name' => 'Object Cache', + 'postfix' => '', ); } - for ( $n = 0; $n < count( $purgelog_modules ) - 1; $n++ ) { - $purgelog_modules[$n]['postfix'] = '|'; + $module_count = count( $purgelog_modules ); + for ( $n = 0; $n < $module_count - 1; $n++ ) { + $purgelog_modules[ $n ]['postfix'] = '|'; } - require( __DIR__ . '/Generic_Page_PurgeLog_View.php' ); + require __DIR__ . '/Generic_Page_PurgeLog_View.php'; } - - - private function to_human($bytes, $decimals = 2) { - $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB'); - $factor = floor((strlen($bytes) - 1) / 3); - return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor]; + /** + * Converts bytes to human readable + * + * @param int $bytes Bytes. + * @param int $decimals Decimal places. + * + * @return string + */ + private function to_human( $bytes, $decimals = 2 ) { + $size = array( 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' ); + $factor = floor( ( strlen( $bytes ) - 1 ) / 3 ); + return sprintf( "%.{$decimals}f", $bytes / pow( 1024, $factor ) ) . @$size[ $factor ]; } - - + /** + * Checks if string starts with pattern. + * + * @param string $s String to check. + * @param string $prefix Matching pattern. + * + * @return bool + */ private function starts_with( $s, $prefix ) { - return substr( $s, 0, strlen( $prefix ) ) == $prefix; + return substr( $s, 0, strlen( $prefix ) ) === $prefix; } - - + /** + * Sanitizes filename. + * + * @param string $filename File name. + * + * @return string + */ private function esc_filename( $filename ) { $m = null; if ( preg_match( $this->plugins_regexp, $filename, $m ) ) { diff --git a/Generic_Page_PurgeLog_View.php b/Generic_Page_PurgeLog_View.php index 1be75a666..2d25ff125 100644 --- a/Generic_Page_PurgeLog_View.php +++ b/Generic_Page_PurgeLog_View.php @@ -1,4 +1,10 @@ _config = Dispatcher::config(); } /** * Runs plugin + * + * @return void */ - function run() { - add_filter( 'cron_schedules', array( $this, 'cron_schedules' ), 5 ); + public function run() { + add_filter( 'cron_schedules', array( $this, 'cron_schedules' ), 5 ); // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval add_action( 'w3tc_purge_all_wpcron', array( $this, 'w3tc_purgeall_wpcron' ) ); /* need this to run before wp-cron to issue w3tc redirect */ @@ -57,7 +90,11 @@ function run() { /** * Marks wp_die was called so response is system message - **/ + * + * @param callable $v Callback. + * + * @return callable + */ public function wp_die_handler( $v ) { $this->is_wp_die = true; return $v; @@ -135,7 +172,7 @@ public function w3tc_purgeall_wpcron() { * * @return void */ - function init() { + public function init() { // Load W3TC textdomain for translations. $this->reset_l10n(); load_plugin_textdomain( W3TC_TEXT_DOMAIN, false, dirname( plugin_basename( __FILE__ ) ) . '/languages' ); @@ -171,7 +208,7 @@ function init() { // redirect to the same url causes "redirect loop" error in browser, // so need to redirect to something a bit different. if ( $do_redirect ) { - if ( ( defined( 'WP_CLI' ) && WP_CLI ) || php_sapi_name() === 'cli' ) { + if ( ( defined( 'WP_CLI' ) && WP_CLI ) || php_sapi_name() === 'cli' ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf // command-line mode, no real requests made, // try to switch context in-request. } else { @@ -212,9 +249,14 @@ function init() { } } + /** + * Admin bar init + * + * @return void + */ public function admin_bar_init() { $font_base = plugins_url( 'pub/fonts/w3tc', W3TC_FILE ); - $css = " + $css = " @font-face { font-family: 'w3tc'; src: url('$font_base.eot'); @@ -230,7 +272,7 @@ public function admin_bar_init() { font-family: 'w3tc'; }"; - wp_add_inline_style( 'admin-bar', $css); + wp_add_inline_style( 'admin-bar', $css ); } /** @@ -238,7 +280,7 @@ public function admin_bar_init() { * * @return void */ - function admin_bar_menu() { + public function admin_bar_menu() { global $wp_admin_bar; $base_capability = apply_filters( 'w3tc_capability_admin_bar', 'manage_options' ); @@ -424,10 +466,11 @@ function admin_bar_menu() { /** * Template filter * - * @param unknown $template + * @param unknown $template Template. + * * @return string */ - function template( $template ) { + public function template( $template ) { $w3_mobile = Dispatcher::component( 'Mobile_UserAgent' ); $mobile_template = $w3_mobile->get_template(); @@ -450,10 +493,11 @@ function template( $template ) { /** * Stylesheet filter * - * @param unknown $stylesheet + * @param unknown $stylesheet Stylesheet. + * * @return string */ - function stylesheet( $stylesheet ) { + public function stylesheet( $stylesheet ) { $w3_mobile = Dispatcher::component( 'Mobile_UserAgent' ); $mobile_stylesheet = $w3_mobile->get_stylesheet(); @@ -476,10 +520,11 @@ function stylesheet( $stylesheet ) { /** * Template filter * - * @param unknown $template + * @param unknown $template Template. + * * @return string */ - function template_preview( $template ) { + public function template_preview( $template ) { $theme_name = Util_Request::get_string( 'w3tc_theme' ); $theme = Util_Theme::get( $theme_name ); @@ -494,10 +539,11 @@ function template_preview( $template ) { /** * Stylesheet filter * - * @param unknown $stylesheet + * @param unknown $stylesheet Stylesheet. + * * @return string */ - function stylesheet_preview( $stylesheet ) { + public function stylesheet_preview( $stylesheet ) { $theme_name = Util_Request::get_string( 'w3tc_theme' ); $theme = Util_Theme::get( $theme_name ); @@ -512,10 +558,11 @@ function stylesheet_preview( $stylesheet ) { /** * Output buffering callback * - * @param string $buffer + * @param string $buffer Buffer. + * * @return string */ - function ob_callback( $buffer ) { + public function ob_callback( $buffer ) { global $wpdb; global $w3_late_caching_succeeded; @@ -523,8 +570,8 @@ function ob_callback( $buffer ) { return $buffer; } - if ( $this->is_wp_die && ! apply_filters( 'w3tc_process_wp_die', false, $buffer ) ) { - // wp_die is dynamic output (usually fatal errors), dont process it + if ( $this->is_wp_die && ! apply_filters( 'w3tc_process_wp_die', false, $buffer ) ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf + // wp_die is dynamic output (usually fatal errors), dont process it. } else { $buffer = apply_filters( 'w3tc_process_content', $buffer ); @@ -593,7 +640,7 @@ function ob_callback( $buffer ) { * * @return boolean */ - function can_ob() { + public function can_ob() { global $w3_late_init; if ( $w3_late_init ) { return false; @@ -646,11 +693,18 @@ function can_ob() { } /** - * User login hook - * Check if current user is not listed in pgcache.reject.* rules + * User login hook. Check if current user is not listed in pgcache.reject.* rules * If so, set a role cookie so the requests wont be cached + * + * @param bool $logged_in_cookie Logged in cookie flag. + * @param string $expire Expire timestamp. + * @param int $expiration Time to expire. + * @param int $user_id User ID. + * @param string $action Action. + * + * @return void */ - function check_login_action( $logged_in_cookie = false, $expire = ' ', $expiration = 0, $user_id = 0, $action = 'logged_out' ) { + public function check_login_action( $logged_in_cookie = false, $expire = ' ', $expiration = 0, $user_id = 0, $action = 'logged_out' ) { $current_user = wp_get_current_user(); if ( isset( $current_user->ID ) && ! $current_user->ID ) { $user_id = new \WP_User( $user_id ); @@ -703,7 +757,12 @@ function check_login_action( $logged_in_cookie = false, $expire = ' ', $expirati } } - function popup_script() { + /** + * Popup script embed + * + * @return void + */ + public function popup_script() { if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) { return; } @@ -716,6 +775,11 @@ function w3tc_popupadmin_bar(url) { _config->get_boolean( 'pgcache.enabled' ) && $this->_config->get_boolean( 'pgcache.debug' ); $debug = $debug || ( $this->_config->get_boolean( 'dbcache.enabled' ) && $this->_config->get_boolean( 'dbcache.debug' ) ); @@ -727,6 +791,11 @@ private function is_debugging() { return $debug; } + /** + * Output HTML in footer if dev mode enabled + * + * @return void + */ public function pro_dev_mode() { echo '

    W3 Total Cache is currently running in Pro version Development mode.

    '; } diff --git a/Generic_Plugin_Admin.php b/Generic_Plugin_Admin.php index 3edd4776e..00413dedf 100644 --- a/Generic_Plugin_Admin.php +++ b/Generic_Plugin_Admin.php @@ -43,7 +43,9 @@ class Generic_Plugin_Admin { private $w3tc_message = null; /** - * Constructor. + * Constructor + * + * @return void */ public function __construct() { $this->_config = Dispatcher::config(); @@ -51,6 +53,8 @@ public function __construct() { /** * Runs plugin + * + * @return void */ public function run() { $this->is_w3tc_page = Util_Admin::is_w3tc_admin_page(); @@ -148,6 +152,13 @@ public function load() { } } + /** + * Save settings handler. + * + * @param array $data Data. + * + * @return array + */ public function w3tc_save_options( $data ) { $new_config = $data['new_config']; $old_config = $data['old_config']; @@ -450,8 +461,6 @@ public function admin_head() { function w3tc_ga(){dataLayer.push(arguments);} - w3tc_ga('js', new Date()); - w3tc_ga('config', '', { 'user_properties': { 'plugin': 'w3-total-cache', @@ -465,7 +474,12 @@ function w3tc_ga(){dataLayer.push(arguments);} 'w3tc_edition': '_config ) ); ?>', 'w3tc_widgets': '', 'page': '', - 'w3tc_install_date': '' + 'w3tc_install_date': '', + 'w3tc_pro': '_config ) ? 1 : 0; ?>', + 'w3tc_has_key': '_config->get_string( 'plugin.license_key' ) ? 1 : 0; ?>', + 'w3tc_pro_c': '', + 'w3tc_enterprise_c': '', + 'w3tc_plugin_type': '_config->get_string( 'plugin.type' ) ); ?>', } }); @@ -676,54 +690,54 @@ public function admin_print_scripts() { 'W3TCRemoveCssJsData', array( 'lang' => array( - 'singlesPathDescription' => __( 'Enter the path of the CSS/JS file to be managed. If a directory is used, all CSS/JS files within that directory will be managed with this entry.', 'w3-total-cache' ), - 'singlesExampleTrigger' => __( 'View Examples', 'w3-total-cache' ), - 'singlesExampleTriggerClose' => __( 'Hide Examples', 'w3-total-cache' ), - 'singlesPathExampleDirLabel' => __( 'Target all CSS/JS from a plugin/theme:', 'w3-total-cache' ), - 'singlesPathExampleDir' => wp_kses( + 'singlesPathDescription' => __( 'Enter the path of the CSS/JS file to be managed. If a directory is used, all CSS/JS files within that directory will be managed with this entry.', 'w3-total-cache' ), + 'singlesExampleTrigger' => __( 'View Examples', 'w3-total-cache' ), + 'singlesExampleTriggerClose' => __( 'Hide Examples', 'w3-total-cache' ), + 'singlesPathExampleDirLabel' => __( 'Target all CSS/JS from a plugin/theme:', 'w3-total-cache' ), + 'singlesPathExampleDir' => wp_kses( 'https://example.com/wp-content/plugins/example-plugin/
    /wp-content/plugins/example-plugin/', array( 'br' => array(), ) ), - 'singlesPathExampleFileLabel' => __( 'Target a specific CSS/JS file:', 'w3-total-cache' ), - 'singlesPathExampleFile' => wp_kses( + 'singlesPathExampleFileLabel' => __( 'Target a specific CSS/JS file:', 'w3-total-cache' ), + 'singlesPathExampleFile' => wp_kses( 'https://example.com/wp-content/themes/example-theme/example-script.js
    /wp-content/themes/example-script.js
    example-script.js', array( 'br' => array(), ) ), - 'singlesNoEntries' => __( 'No CSS/JS entries added.', 'w3-total-cache' ), - 'singlesExists' => __( 'Entry already exists!', 'w3-total-cache' ), - 'singlesPathLabel' => __( 'Target CSS/JS:', 'w3-total-cache' ), - 'singlesDelete' => __( 'Delete', 'w3-total-cache' ), - 'singlesBehaviorLabel' => __( 'Action:', 'w3-total-cache' ), - 'singlesBehaviorExcludeText' => __( 'Exclude', 'w3-total-cache' ), - 'singlesBehaviorExcludeText2' => __( '(Remove the script ONLY WHEN a condition below matches)', 'w3-total-cache' ), - 'singlesBehaviorIncludeText' => __( 'Include', 'w3-total-cache' ), - 'singlesBehaviorIncludeText2' => __( '(Allow the script ONLY WHEN a condition below matches)', 'w3-total-cache' ), - 'singlesBehaviorDescription' => __( 'When the above CSS/JS file is found within your markup.', 'w3-total-cache' ), - 'singlesIncludesLabelExclude' => __( 'Exclude on URL Match:', 'w3-total-cache' ), - 'singlesIncludesLabelInclude' => __( 'Include on URL Match:', 'w3-total-cache' ), - 'singlesIncludesDescriptionExclude' => __( 'Specify the conditions for which the target file should be excluded based on matching absolute/relative page URLs. Include one entry per line.', 'w3-total-cache' ), - 'singlesIncludesDescriptionInclude' => __( 'Specify the conditions for which the target file should be included based on matching absolute/relative page URLs. Include one entry per line.', 'w3-total-cache' ), - 'singlesIncludesExample' => wp_kses( + 'singlesNoEntries' => __( 'No CSS/JS entries added.', 'w3-total-cache' ), + 'singlesExists' => __( 'Entry already exists!', 'w3-total-cache' ), + 'singlesPathLabel' => __( 'Target CSS/JS:', 'w3-total-cache' ), + 'singlesDelete' => __( 'Delete', 'w3-total-cache' ), + 'singlesBehaviorLabel' => __( 'Action:', 'w3-total-cache' ), + 'singlesBehaviorExcludeText' => __( 'Exclude', 'w3-total-cache' ), + 'singlesBehaviorExcludeText2' => __( '(Remove the script ONLY WHEN a condition below matches)', 'w3-total-cache' ), + 'singlesBehaviorIncludeText' => __( 'Include', 'w3-total-cache' ), + 'singlesBehaviorIncludeText2' => __( '(Allow the script ONLY WHEN a condition below matches)', 'w3-total-cache' ), + 'singlesBehaviorDescription' => __( 'When the above CSS/JS file is found within your markup.', 'w3-total-cache' ), + 'singlesIncludesLabelExclude' => __( 'Exclude on URL Match:', 'w3-total-cache' ), + 'singlesIncludesLabelInclude' => __( 'Include on URL Match:', 'w3-total-cache' ), + 'singlesIncludesDescriptionExclude' => __( 'Specify the conditions for which the target file should be excluded based on matching absolute/relative page URLs. Include one entry per line.', 'w3-total-cache' ), + 'singlesIncludesDescriptionInclude' => __( 'Specify the conditions for which the target file should be included based on matching absolute/relative page URLs. Include one entry per line.', 'w3-total-cache' ), + 'singlesIncludesExample' => wp_kses( 'https://example.com/example-page/
    /example-page/
    example-page?arg=example-arg', array( 'br' => array(), ) ), - 'singlesIncludesContentLabelExclude' => __( 'Exclude on Content Match:', 'w3-total-cache' ), - 'singlesIncludesContentLabelInclude' => __( 'Include on Content Match:', 'w3-total-cache' ), + 'singlesIncludesContentLabelExclude' => __( 'Exclude on Content Match:', 'w3-total-cache' ), + 'singlesIncludesContentLabelInclude' => __( 'Include on Content Match:', 'w3-total-cache' ), 'singlesIncludesContentDescriptionExclude' => __( 'Specify the conditions for which the target file should be excluded based on matching page content. Include one entry per line.', 'w3-total-cache' ), 'singlesIncludesContentDescriptionInclude' => __( 'Specify the conditions for which the target file should be included based on matching page content. Include one entry per line.', 'w3-total-cache' ), - 'singlesIncludesContentExample' => wp_kses( + 'singlesIncludesContentExample' => wp_kses( '<div id="example-id">
    <span class="example-class">
    name="example-name"', array( 'br' => array(), ) ), - 'singlesEmptyUrl' => __( 'Empty match pattern!', 'w3-total-cache' ), + 'singlesEmptyUrl' => __( 'Empty match pattern!', 'w3-total-cache' ), ), ) ); diff --git a/Generic_Plugin_AdminCompatibility.php b/Generic_Plugin_AdminCompatibility.php index 55274bac4..1ce65c812 100644 --- a/Generic_Plugin_AdminCompatibility.php +++ b/Generic_Plugin_AdminCompatibility.php @@ -1,25 +1,44 @@ _config = Dispatcher::config(); } /** * Runs plugin + * + * @return void */ - function run() { + public function run() { add_filter( 'pre_update_option_active_plugins', array( $this, 'pre_update_option_active_plugins' ) ); add_filter( 'pre_update_site_option_active_sitewide_plugins', array( $this, 'pre_update_option_active_plugins' ) ); + if ( false === get_transient( 'w3tc.verify_plugins' ) ) { add_action( 'admin_notices', array( $this, 'verify' ) ); add_action( 'network_admin_notices', array( $this, 'verify' ) ); @@ -29,35 +48,42 @@ function run() { /** * Active plugins pre update option filter * - * @param string $new_value + * @param string $new_value New value. + * * @return string */ - function pre_update_option_active_plugins( $new_value ) { + public function pre_update_option_active_plugins( $new_value ) { delete_transient( 'w3tc.verify_plugins' ); return $new_value; } /** * Check that activated plugins are not incompatible with the plugin + * + * @return void */ - function verify() { + public function verify() { if ( is_network_admin() ) { $active_plugins = (array) get_site_option( 'active_sitewide_plugins', array() ); $active_plugins = array_keys( $active_plugins ); - } else + } else { $active_plugins = (array) get_option( 'active_plugins' ); + } $incomp_plugins = $this->_get_incompatible_plugins(); $message = ''; $matches = array_intersect( $active_plugins, $incomp_plugins ); + if ( $matches ) { $message = $this->_custom_message( $matches ); } - if ( $message ) + + if ( $message ) { Util_Ui::error_box( $message ); - else - set_transient( 'w3tc.verify_plugins', true, 7*24*3600 ); + } else { + set_transient( 'w3tc.verify_plugins', true, 7 * 24 * 3600 ); + } } /** @@ -67,45 +93,51 @@ function verify() { */ private function _get_incompatible_plugins() { return array( - 'force-gzip/force-gzip.php' - , 'wp-http-compression/wp-http-compression.php' - , 'gzippy/gzippy.php' - , 'wordpress-gzip-compression/ezgz.php' - , 'wpcompressor/wpcompressor.php' - , 'gzip-pages/filosofo-gzip-compression.php' - , 'admin-flush-w3tc-cache/admin_flush_w3tc.php' - , 'hyper-cache/plugin.php' - , 'aio-cache/aio-cache.php' - , 'lite-cache/plugin.php' - , 'quick-cache/quick-cache.php' - , 'wp-super-cache/wp-cache.php' - , 'hyper-cache-extended/plugin.php' - , 'batcache/batcache.php' - , 'cachify/cachify.php' - , 'flexicache/wp-plugin.php' + 'force-gzip/force-gzip.php', + 'wp-http-compression/wp-http-compression.php', + 'gzippy/gzippy.php', + 'wordpress-gzip-compression/ezgz.php', + 'wpcompressor/wpcompressor.php', + 'gzip-pages/filosofo-gzip-compression.php', + 'admin-flush-w3tc-cache/admin_flush_w3tc.php', + 'hyper-cache/plugin.php', + 'aio-cache/aio-cache.php', + 'lite-cache/plugin.php', + 'quick-cache/quick-cache.php', + 'wp-super-cache/wp-cache.php', + 'hyper-cache-extended/plugin.php', + 'batcache/batcache.php', + 'cachify/cachify.php', + 'flexicache/wp-plugin.php', ); } /** * Build incompatible plugins message * - * @param unknown $plugins + * @param unknown $plugins Plugins. + * * @return string */ private function _custom_message( $plugins ) { - $message = __( 'The following plugins are not compatible with W3 Total Cache and will cause unintended results:', 'w3-total-cache' ); + $plugin_names = array(); foreach ( $plugins as $plugin ) { $data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin ); $temp = "
  • {$data['Name']}
    "; - if ( is_network_admin() && current_user_can( 'manage_network_plugins' ) ) + + if ( is_network_admin() && current_user_can( 'manage_network_plugins' ) ) { $temp .= ' ' . __( 'Network Deactivate' ) . ''; - else + } else { $temp .= ' ' . __( 'Deactivate', 'w3-total-cache' ) . ''; - $temp .= "
  • "; + } + + $temp .= ''; + $plugin_names[] = $temp; } + return sprintf( "

    $message

      %s
    ", implode( '', $plugin_names ) ); } } diff --git a/Generic_Plugin_AdminRowActions.php b/Generic_Plugin_AdminRowActions.php index 9d25d18ce..a9f3727ae 100644 --- a/Generic_Plugin_AdminRowActions.php +++ b/Generic_Plugin_AdminRowActions.php @@ -1,70 +1,103 @@ sprintf( '' . __( 'Purge from cache', 'w3-total-cache' ) . '', wp_nonce_url( sprintf( 'admin.php?page=w3tc_dashboard&w3tc_flush_post&post_id=%d&force=true', $post->ID ), 'w3tc' ) ) - ) ); + if ( current_user_can( $capability ) ) { + $actions = array_merge( + $actions, + array( + 'w3tc_flush_post' => sprintf( + '' . __( 'Purge from cache', 'w3-total-cache' ) . '', + wp_nonce_url( + sprintf( + 'admin.php?page=w3tc_dashboard&w3tc_flush_post&post_id=%d&force=true', + $post->ID + ), + 'w3tc' + ) + ), + ) + ); + } return $actions; } /** - * page_row_actions filter + * Filter for page_row_actions + * + * @param array $actions Actions. + * @param object $post Post. * - * @param array $actions - * @param object $post * @return array */ - function page_row_actions( $actions, $post ) { - $capability = apply_filters( - 'w3tc_capability_row_action_w3tc_flush_post', 'manage_options' ); + public function page_row_actions( $actions, $post ) { + $capability = apply_filters( 'w3tc_capability_row_action_w3tc_flush_post', 'manage_options' ); - if ( current_user_can( $capability ) ) - $actions = array_merge( $actions, array( - 'w3tc_flush_post' => sprintf( '' . __( 'Purge from cache', 'w3-total-cache' ) . '', wp_nonce_url( sprintf( 'admin.php?page=w3tc_dashboard&w3tc_flush_post&post_id=%d&force=true', $post->ID ), 'w3tc' ) ) - ) ); + if ( current_user_can( $capability ) ) { + $actions = array_merge( + $actions, + array( + 'w3tc_flush_post' => sprintf( + '' . __( 'Purge from cache', 'w3-total-cache' ) . '', + wp_nonce_url( + sprintf( + 'admin.php?page=w3tc_dashboard&w3tc_flush_post&post_id=%d&force=true', + $post->ID + ), + 'w3tc' + ) + ), + ) + ); + } return $actions; } /** * Display Purge from cache on Page/Post post.php. + * + * @return void */ - function post_submitbox_start() { + public function post_submitbox_start() { if ( current_user_can( 'manage_options' ) ) { global $post; - if ( !is_null( $post ) ) { + if ( ! is_null( $post ) ) { $url = Util_Ui::url( array( 'page' => 'w3tc_dashboard', diff --git a/Generic_Plugin_Admin_View_Faq.php b/Generic_Plugin_Admin_View_Faq.php index 4329c8b82..d12a22ea8 100644 --- a/Generic_Plugin_Admin_View_Faq.php +++ b/Generic_Plugin_Admin_View_Faq.php @@ -1,4 +1,10 @@ license_status === 'invalid.not_present' ) ) { +if ( empty( $license ) || ( ! empty( $license ) && 'invalid.not_present' === $license->license_status ) ) { ?>

    ', array( $o, 'widget_form' ), self_admin_url( - 'plugin-install.php?tab=plugin-information&plugin=boldgrid-backup' . - '&TB_iframe=true&width=772&height=550' - ), 'normal', __( 'View Details' ), 'thickbox open-plugin-details-modal' ); + 'plugin-install.php?tab=plugin-information&plugin=boldgrid-backup&TB_iframe=true&width=772&height=550' + ), + 'normal', + __( 'View Details', 'w3-total-cache' ), + 'thickbox open-plugin-details-modal' + ); add_thickbox(); + wp_enqueue_script( 'plugin-install' ); - wp_enqueue_script( 'w3tc-boldgrid-widget', + wp_enqueue_script( + 'w3tc-boldgrid-widget', plugins_url( 'Generic_WidgetBoldGrid_View.js', W3TC_FILE ), - array( 'thickbox' ), W3TC_VERSION ); + array( 'thickbox' ), + W3TC_VERSION, + false + ); } - - /** * Determine whether or not we should show the backup widget. * @@ -38,7 +60,7 @@ static public function admin_init_w3tc_dashboard() { * * @return bool */ - static private function should_show_widget() { + private static function should_show_widget() { $plugins = get_option( 'active_plugins' ); $backup_plugins = array( @@ -47,7 +69,7 @@ static private function should_show_widget() { 'boldgrid-backup/boldgrid-backup.php', 'duplicator/duplicator.php', 'updraftplus/updraftplus.php', - 'wpvivid-backuprestore/wpvivid-backuprestore.php' + 'wpvivid-backuprestore/wpvivid-backuprestore.php', ); foreach ( $plugins as $plugin ) { @@ -59,12 +81,14 @@ static private function should_show_widget() { return true; } - - + /** + * Widget form + * + * @return void + */ public function widget_form() { - $install_url = wp_nonce_url( - 'admin.php?page=w3tc_dashboard&w3tc_boldgrid_install', 'w3tc' ); + $install_url = wp_nonce_url( 'admin.php?page=w3tc_dashboard&w3tc_boldgrid_install', 'w3tc' ); - include W3TC_DIR . '/Generic_WidgetBoldGrid_View.php'; + include W3TC_DIR . '/Generic_WidgetBoldGrid_View.php'; } } diff --git a/Generic_WidgetBoldGrid_AdminActions.php b/Generic_WidgetBoldGrid_AdminActions.php index ccb1dd306..d58fb967a 100644 --- a/Generic_WidgetBoldGrid_AdminActions.php +++ b/Generic_WidgetBoldGrid_AdminActions.php @@ -1,16 +1,30 @@

    - + - +
    _config = Dispatcher::config(); } - - /** * Runs plugin + * + * @return void */ - function run() { - if ( Util_Admin::get_current_wp_page() == 'w3tc_dashboard' ) + public function run() { + if ( 'w3tc_dashboard' === Util_Admin::get_current_wp_page() ) { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) ); + } add_action( 'w3tc_widget_setup', array( $this, 'wp_dashboard_setup' ), 900 ); add_action( 'w3tc_network_dashboard_setup', array( $this, 'wp_dashboard_setup' ), 900 ); @@ -31,35 +49,42 @@ function run() { * * @return void */ - function wp_dashboard_setup() { - Util_Widget::add( 'w3tc_spreadtheword', + public function wp_dashboard_setup() { + Util_Widget::add( + 'w3tc_spreadtheword', '' . '
    ' . __( 'Spread the Word', 'w3-total-cache' ) . '
    ', array( $this, 'widget_form' ), null, - 'bottom' ); + 'bottom' + ); } - function widget_form() { + /** + * Widget from + * + * @return void + */ + public function widget_form() { include W3TC_DIR . '/Generic_WidgetSpreadTheWord_View.php'; } + /** + * Enqueue + * + * @return void + */ public function enqueue() { wp_enqueue_style( 'w3tc-widget' ); wp_enqueue_script( 'w3tc-metadata' ); wp_enqueue_script( 'w3tc-widget' ); - wp_enqueue_script( 'w3tc_spread_the_word', - plugins_url( 'Generic_WidgetSpreadTheWord.js', W3TC_FILE ), - array( 'jquery' ), '1.0' ); + wp_enqueue_script( 'w3tc_spread_the_word', plugins_url( 'Generic_WidgetSpreadTheWord.js', W3TC_FILE ), array( 'jquery' ), '1.0', false ); - wp_localize_script( 'w3tc_spread_the_word', - 'w3tc_spread_the_word_product_url', array( W3TC_SUPPORT_US_PRODUCT_URL ) ); - wp_localize_script( 'w3tc_spread_the_word', - 'w3tc_spread_the_word_tweet', array( W3TC_SUPPORT_US_TWEET ) ); - wp_localize_script( 'w3tc_spread_the_word', - 'w3tc_spread_the_word_rate_url', array( W3TC_SUPPORT_US_RATE_URL ) ); + wp_localize_script( 'w3tc_spread_the_word', 'w3tc_spread_the_word_product_url', array( W3TC_SUPPORT_US_PRODUCT_URL ) ); + wp_localize_script( 'w3tc_spread_the_word', 'w3tc_spread_the_word_tweet', array( W3TC_SUPPORT_US_TWEET ) ); + wp_localize_script( 'w3tc_spread_the_word', 'w3tc_spread_the_word_rate_url', array( W3TC_SUPPORT_US_RATE_URL ) ); } } diff --git a/Generic_WidgetSpreadTheWord_View.php b/Generic_WidgetSpreadTheWord_View.php index 9774785dd..b5f352c65 100644 --- a/Generic_WidgetSpreadTheWord_View.php +++ b/Generic_WidgetSpreadTheWord_View.php @@ -1,4 +1,10 @@ $wpdb->db_version(), 'home_url_host' => Util_Environment::home_url_host(), 'install_version' => esc_attr( $state->get_string( 'common.install_version' ) ), + 'w3tc_install_date' => get_option( 'w3tc_install_date' ), 'w3tc_edition' => esc_attr( Util_Environment::w3tc_edition( $config ) ), 'list_widgets' => esc_attr( Util_Widget::list_widgets() ), 'ga_profile' => ( defined( 'W3TC_DEVELOPER' ) && W3TC_DEVELOPER ) ? 'G-Q3CHQJWERM' : 'G-5TFS8M5TTY', diff --git a/Util_Activation.php b/Util_Activation.php index 9a882e3f7..d65bc5c1d 100644 --- a/Util_Activation.php +++ b/Util_Activation.php @@ -1,28 +1,39 @@ ', addslashes( $reactivate_url ) ); + public static function error_on_exception( $e ) { + $reactivate_url = wp_nonce_url( 'plugins.php?action=activate&plugin=' . W3TC_FILE, 'activate-plugin_' . W3TC_FILE ); + $reactivate_button = sprintf( + '%1$sre-activate plugin', + '', + addslashes( $reactivate_url ) + ); - self::_error( sprintf( __( '%s
    then %s.', 'w3-total-cache' ), $e->getMessage(), $reactivate_button ) ); + self::_error( + sprintf( + // Translators: 1 error message, 2 reactivate button. + __( + '%1$s
    then %2$s.', + 'w3-total-cache' + ), + $e->getMessage(), + $reactivate_button + ) + ); } /** * W3 writable error * - * @param string $path - * @param string[] $chmod_dirs Directories that should be chmod 777 inorder to write + * @param string $path Path. + * @param string[] $chmod_dirs Directories that should be chmod 777 inorder to write. + * + * @throws \Exception Exception. + * + * @return void */ - static public function throw_on_write_error( $path, $chmod_dirs = array() ) { - + public static function throw_on_write_error( $path, $chmod_dirs = array() ) { $chmods = ''; if ( $chmod_dirs ) { $chmods = '
      '; foreach ( $chmod_dirs as $dir ) { - $chmods .= sprintf( __( '
    • chmod 777 %s
    • ', 'w3-total-cache' ), $dir ); + $chmods .= sprintf( + // Translators: 1 opening HTML li tag followed by opening HTML strong tag, 2 directory name + // Translators: 3 closing HTML strong tag followed by closing HTML li tag. + __( + '%1$schmod 777 %2$s%3$s', + 'w3-total-cache' + ), + '
    • ', + $dir, + '
    • ' + ); } } else { - $chmods = sprintf( 'chmod 777 %s', - ( file_exists( $path ) ? $path : dirname( $path ) ) ); + $chmods = sprintf( + 'chmod 777 %s', + file_exists( $path ) ? $path : dirname( $path ) + ); } if ( Util_File::check_open_basedir( $path ) ) { $error = sprintf( - __( '%s could not be created, please run following command:
      %s', - 'w3-total-cache' ), - $path, $chmods ); + // Translators: 1 opening HTML strong tag, 2 file path, 3 closing HTML strong tag + // Translators: 4 HTML line break, 5 chmod values. + __( + '%1$s%2$s%3$s could not be created, please run following command:%4$s%5$s', + 'w3-total-cache' + ), + '', + $path, + '', + '
      ', + $chmods + ); } else { $error = sprintf( - __( '%s could not be created, open_basedir restriction in effect, please check your php.ini settings:
      open_basedir = "%s"', - 'w3-total-cache' ), - $path, ini_get( 'open_basedir' ) ); + // Translators: 1 opening HTML strong tag, 2 file path, 3 closing HTML strong tag + // Translators: 4 HTML line break followed by opening HTML strong tag, 5 open basedir value. + __( + '%1$s%2$s%3$s could not be created, %1$sopen_basedir%3$s restriction in effect, please check your php.ini settings:%4$sopen_basedir = "%5$s"%3$s', + 'w3-total-cache' + ), + '', + $path, + '', + '
      ', + ini_get( 'open_basedir' ) + ); } throw new \Exception( $error ); @@ -93,153 +155,154 @@ static public function throw_on_write_error( $path, $chmod_dirs = array() ) { /** * Creates maintenance mode file * - * @param unknown $time + * @param unknown $time Time. + * + * @return void */ - static public function enable_maintenance_mode( $time = null ) { - if ( is_null( $time ) ) + public static function enable_maintenance_mode( $time = null ) { + if ( is_null( $time ) ) { $time = 'time()'; + } + Util_WpFile::write_to_file( Util_Environment::site_path() . '/.maintenance', "" ); } /** * Deletes maintenance mode file + * + * @return void */ - static public function disable_maintenance_mode() { + public static function disable_maintenance_mode() { Util_WpFile::delete_file( Util_Environment::site_path() . '/.maintenance' ); } /** * Used to display Util_Environment_Exceptions in UI * - * @param Util_Environment_Exceptions $exs + * @param Util_Environment_Exceptions $exs Environment exceptions. + * * @return array(before_errors = [], required_changes =>, later_errors => []) */ - static public function parse_environment_exceptions( $exs ) { + public static function parse_environment_exceptions( $exs ) { $exceptions = $exs->exceptions(); - $commands = ''; - $required_changes = ''; - $before_errors = array(); - $later_errors = array(); + $commands = ''; + $required_changes = ''; + $before_errors = array(); + $later_errors = array(); $operation_error_already_shown = false; foreach ( $exceptions as $ex ) { if ( $ex instanceof Util_WpFile_FilesystemOperationException ) { - if ( !$operation_error_already_shown ) { + if ( ! $operation_error_already_shown ) { $m = $ex->getMessage(); if ( strlen( $m ) > 0 ) { $before_errors[] = $m; - // if multiple operations failed when - // they tried to fix environment - show only first - // otherwise can duplication information about - // absense of permissions + // if multiple operations failed when they tried to fix environment - show only first + // otherwise can duplication information about absense of permissions. $operation_error_already_shown = true; } if ( $ex instanceof Util_WpFile_FilesystemWriteException ) { $required_changes .= sprintf( - __( 'Create the %s file and paste the following text into it:
      ', - 'w3-total-cache' ), - $ex->filename(), esc_textarea( $ex->file_contents() ) ); - } else if ( $ex instanceof Util_WpFile_FilesystemModifyException ) { - $modification_content = $ex->file_contents(); - if ( strlen( $modification_content ) > 0 ) - $modification_content = - ''; - $required_changes .= - $ex->modification_description() . - $modification_content . - '
      '; - } else if ( $ex instanceof Util_WpFile_FilesystemCopyException ) { - $commands .= 'cp ' . $ex->source_filename() . ' ' . - $ex->destination_filename() . '
      '; - } else if ( $ex instanceof Util_WpFile_FilesystemMkdirException ) { - $commands .= 'mkdir ' . $ex->folder() . '
      '; - $commands .= 'chmod 777 ' . $ex->folder() . '
      '; - } else if ( $ex instanceof Util_WpFile_FilesystemRmException ) { - $commands .= 'rm ' . $ex->filename() . '
      '; - } else if ( $ex instanceof Util_WpFile_FilesystemRmdirException ) { - $commands .= 'rm -rf ' . $ex->folder() . '
      '; - } else if ( $ex instanceof Util_WpFile_FilesystemChmodException ) { - $commands .= 'chmod 777 ' . $ex->filename() . '
      '; + // Translators: 1 opening HTML strong tag, 2 file path, 3 closing HTML strong tag + // Translators: 4 opening HTML textarea tag, 5 textarea content, 6 closing HTML textarea tag followed by line break. + __( + 'Create the %1$s%2$s%3$s file and paste the following text into it: %4$s%5$s%6$s', + 'w3-total-cache' + ), + '', + $ex->filename(), + '', + '
      ' + ); + } elseif ( $ex instanceof Util_WpFile_FilesystemModifyException ) { + $modification_content = $ex->file_contents(); + if ( strlen( $modification_content ) > 0 ) { + $modification_content = ''; } - } - } else if ( $ex instanceof Util_Environment_Exception ) { - $t = $ex->technical_message(); - if ( strlen( $t ) > 0 ) { - $t = '
      ' . - '' . - __( 'Technical info', 'w3-total-cache' ).'' . - ''; + $required_changes .= $ex->modification_description() . $modification_content . '
      '; + } elseif ( $ex instanceof Util_WpFile_FilesystemCopyException ) { + $commands .= 'cp ' . $ex->source_filename() . ' ' . + $ex->destination_filename() . '
      '; + } elseif ( $ex instanceof Util_WpFile_FilesystemMkdirException ) { + $commands .= 'mkdir ' . $ex->folder() . '
      '; + $commands .= 'chmod 777 ' . $ex->folder() . '
      '; + } elseif ( $ex instanceof Util_WpFile_FilesystemRmException ) { + $commands .= 'rm ' . $ex->filename() . '
      '; + } elseif ( $ex instanceof Util_WpFile_FilesystemRmdirException ) { + $commands .= 'rm -rf ' . $ex->folder() . '
      '; + } elseif ( $ex instanceof Util_WpFile_FilesystemChmodException ) { + $commands .= 'chmod 777 ' . $ex->filename() . '
      '; } - - $later_errors[] = $ex->getMessage() . $t; - } else { - // unknown command + } + } elseif ( $ex instanceof Util_Environment_Exception ) { + $t = $ex->technical_message(); + if ( strlen( $t ) > 0 ) { + $t = '
      ' . __( 'Technical info', 'w3-total-cache' ) . + ''; + } + $later_errors[] = $ex->getMessage() . $t; + } else { + // unknown command. $later_errors[] = $ex->getMessage(); } } if ( strlen( $commands ) > 0 ) { - $required_changes .= __( 'Execute next commands in a shell:', 'w3-total-cache' ) . - '
      ' . $commands . ''; + $required_changes .= __( 'Execute next commands in a shell:', 'w3-total-cache' ) . '
      ' . $commands . ''; } return array( - 'before_errors' => $before_errors, + 'before_errors' => $before_errors, 'required_changes' => $required_changes, - 'later_errors' => $later_errors + 'later_errors' => $later_errors, ); } /** - * + * Deactivate plugin * * @return string[] error messages */ - static public function deactivate_plugin() { + public static function deactivate_plugin() { $errors = array(); try { $environment = Dispatcher::component( 'Root_Environment' ); $environment->fix_after_deactivation(); deactivate_plugins( plugin_basename( W3TC_FILE ) ); } catch ( SelfTestExceptions $exs ) { - $r = Util_Activation::parse_environment_exceptions( $exs ); + $r = self::parse_environment_exceptions( $exs ); - foreach ( $r['before_errors'] as $e ) + foreach ( $r['before_errors'] as $e ) { $errors[] = $e; + } if ( strlen( $r['required_changes'] ) > 0 ) { - $changes_style = 'border: 1px solid black; ' . - 'background: white; ' . - 'margin: 10px 30px 10px 30px; ' . - 'padding: 10px; display: none'; - $ftp_style = 'border: 1px solid black; background: white; ' . - 'margin: 10px 30px 10px 30px; ' . - 'padding: 10px; display: none'; - $ftp_form = str_replace( 'class="wrap"', '', - $exs->credentials_form() ); - $ftp_form = str_replace( '
      ', '', $ftp_form ); - $ftp_form = str_replace( '
      ', '', $ftp_form ); - $ftp_form = str_replace( 'id="upgrade" class="button"', - 'id="upgrade" class="button w3tc-button-save"', $ftp_form ); + $changes_style = 'border: 1px solid black; background: white; margin: 10px 30px 10px 30px; padding: 10px; display: none'; + $ftp_style = 'border: 1px solid black; background: white; margin: 10px 30px 10px 30px; padding: 10px; display: none'; + $ftp_form = str_replace( 'class="wrap"', '', $exs->credentials_form() ); + $ftp_form = str_replace( '
      ', '', $ftp_form ); + $ftp_form = str_replace( '
      ', '', $ftp_form ); + $ftp_form = str_replace( 'id="upgrade" class="button"', 'id="upgrade" class="button w3tc-button-save"', $ftp_form ); - $error = sprintf( ' - %s + $error = sprintf( + '%s - - - - - - - -
      %s%s
      %s%s
      ', - __( 'W3 Total Cache Error: Files and directories could not be automatically deleted.' , 'w3-total-cache' ), - __( 'Please execute commands manually' , 'w3-total-cache' ), - __( 'or use FTP form to allow W3 Total Cache make it automatically.' , - 'w3-total-cache' ), + + %s + %s + + + %s + %s + + ', + __( 'W3 Total Cache Error: Files and directories could not be automatically deleted.', 'w3-total-cache' ), + __( 'Please execute commands manually', 'w3-total-cache' ), + __( 'or use FTP form to allow W3 Total Cache make it automatically.', 'w3-total-cache' ), Util_Ui::button( __( 'View required changes', 'w3-total-cache' ), '', @@ -250,13 +313,12 @@ static public function deactivate_plugin() { '', 'w3tc-show-ftp-form' ) - ) . '
      ' . $r['required_changes'] . '
      ' . - '
      ' . - $ftp_form . '
      '; + ) . '
      ' . $r['required_changes'] . '
      ' . + '
      ' . $ftp_form . '
      '; $errors[] = $error; } + return $errors; } } diff --git a/Util_Admin.php b/Util_Admin.php index eb349c3ea..8ec5a187e 100644 --- a/Util_Admin.php +++ b/Util_Admin.php @@ -9,6 +9,9 @@ /** * Class: Util_Admin + * + * phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize + * phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged */ class Util_Admin { /** @@ -149,7 +152,7 @@ public static function single_system_item( $a ) { $first_key = array_keys( $a ); $first_key = $first_key[0]; - $pos = strpos( $a[ $first_key ], ' ' ); + $pos = strpos( $a[ $first_key ], ' ' ); if ( false === $pos ) { return true; @@ -178,15 +181,15 @@ public static function single_system_item( $a ) { public static function config_save( $current_config, $new_config ) { $master_config = ( $new_config->is_master() ? $new_config : Dispatcher::config_master() ); - if ( $master_config->get_integer( 'common.instance_id', 0 ) == 0 ) { - $master_config->set( 'common.instance_id', mt_rand() ); + if ( $master_config->get_integer( 'common.instance_id', 0 ) === 0 ) { + $master_config->set( 'common.instance_id', wp_rand() ); if ( ! $new_config->is_master() ) { $master_config->save(); } } - $old_config = new Config(); + $old_config = new Config(); $browsercache_dependencies = array(); if ( $new_config->get_boolean( 'browsercache.enabled' ) ) { @@ -253,7 +256,7 @@ public static function config_save( $current_config, $new_config ) { $new_bc_dependencies_values[] = $new_config->get( $key ); } - if ( serialize( $old_bc_dependencies_values ) != serialize( $new_bc_dependencies_values ) ) { + if ( serialize( $old_bc_dependencies_values ) !== serialize( $new_bc_dependencies_values ) ) { $state_note = Dispatcher::config_state_note(); $state_note->set( 'common.show_note.flush_statics_needed', true ); } @@ -367,7 +370,7 @@ public static function config_save( $current_config, $new_config ) { 'cdn.azure.cname', 'cdn.azure.ssl', 'cdn.azuremi.cname', - 'cdn.azuremi.ssl', + 'cdn.azuremi.ssl', 'cdn.mirror.domain', 'cdn.mirror.ssl', 'cdn.cotendo.domain', @@ -413,7 +416,7 @@ public static function config_save( $current_config, $new_config ) { $new_pgcache_dependencies_values[] = $new_config->get( $pgcache_dependency ); } - if ( serialize( $old_pgcache_dependencies_values ) != serialize( $new_pgcache_dependencies_values ) ) { + if ( serialize( $old_pgcache_dependencies_values ) !== serialize( $new_pgcache_dependencies_values ) ) { $state_note = Dispatcher::config_state_note(); $state_note->set( 'common.show_note.flush_posts_needed', true ); } @@ -510,7 +513,7 @@ public static function config_save( $current_config, $new_config ) { $new_minify_dependencies_values[] = $new_config->get( $minify_dependency ); } - if ( serialize( $old_minify_dependencies_values ) != serialize( $new_minify_dependencies_values ) ) { + if ( serialize( $old_minify_dependencies_values ) !== serialize( $new_minify_dependencies_values ) ) { $state_note = Dispatcher::config_state_note(); $state_note->set( 'minify.show_note.need_flush', true ); } @@ -589,7 +592,7 @@ public static function config_save( $current_config, $new_config ) { $new_objectcache_dependencies_values[] = $new_config->get( $objectcache_dependency ); } - if ( serialize( $old_objectcache_dependencies_values ) != serialize( $new_objectcache_dependencies_values ) ) { + if ( serialize( $old_objectcache_dependencies_values ) !== serialize( $new_objectcache_dependencies_values ) ) { $state_note = Dispatcher::config_state_note(); $state_note->set( 'objectcache.show_note.flush_needed', true ); } @@ -626,31 +629,28 @@ public static function config_save( $current_config, $new_config ) { /** * Empty caches on engine change or cache enable/disable */ - if ( $old_config->get_string( 'pgcache.engine' ) != - $new_config->get_string( 'pgcache.engine' ) || - $old_config->get_string( 'pgcache.enabled' ) != - $new_config->get_string( 'pgcache.enabled' ) ) { + if ( $old_config->get_string( 'pgcache.engine' ) !== $new_config->get_string( 'pgcache.engine' ) || $old_config->get_string( 'pgcache.enabled' ) !== $new_config->get_string( 'pgcache.enabled' ) ) { $pgcacheflush = Dispatcher::component( 'PgCache_Flush' ); - $v = $pgcacheflush->flush(); + $v = $pgcacheflush->flush(); } - if ( $old_config->get_string( 'dbcache.engine' ) != $new_config->get_string( 'dbcache.engine' ) || $old_config->get_string( 'dbcache.enabled' ) != $new_config->get_string( 'dbcache.enabled' ) ) { + if ( $old_config->get_string( 'dbcache.engine' ) !== $new_config->get_string( 'dbcache.engine' ) || $old_config->get_string( 'dbcache.enabled' ) !== $new_config->get_string( 'dbcache.enabled' ) ) { w3tc_dbcache_flush(); } - if ( $old_config->get_string( 'objectcache.engine' ) != $new_config->get_string( 'objectcache.engine' ) || $old_config->getf_boolean( 'objectcache.enabled' ) !== $new_config->getf_boolean( 'objectcache.enabled' ) ) { + if ( $old_config->get_string( 'objectcache.engine' ) !== $new_config->get_string( 'objectcache.engine' ) || $old_config->getf_boolean( 'objectcache.enabled' ) !== $new_config->getf_boolean( 'objectcache.enabled' ) ) { w3tc_objectcache_flush(); } - if ( $old_config->get_string( 'minify.engine' ) != $new_config->get_string( 'minify.engine' ) || $old_config->get_string( 'minify.enabled' ) != $new_config->get_string( 'minify.enabled' ) ) { + if ( $old_config->get_string( 'minify.engine' ) !== $new_config->get_string( 'minify.engine' ) || $old_config->get_string( 'minify.enabled' ) !== $new_config->get_string( 'minify.enabled' ) ) { w3tc_minify_flush(); } /** * Update CloudFront CNAMEs */ - if ( $new_config->get_boolean( 'cdn.enabled' ) && in_array( $new_config->get_string( 'cdn.engine' ), array( 'cf', 'cf2' ) ) ) { - if ( $new_config->get_string( 'cdn.engine' ) == 'cf' ) { + if ( $new_config->get_boolean( 'cdn.enabled' ) && in_array( $new_config->get_string( 'cdn.engine' ), array( 'cf', 'cf2' ), true ) ) { + if ( 'cf' === $new_config->get_string( 'cdn.engine' ) ) { $old_cnames = $old_config->get_array( 'cdn.cf.cname' ); $new_cnames = $new_config->get_array( 'cdn.cf.cname' ); } else { @@ -673,7 +673,7 @@ public static function config_save( $current_config, $new_config ) { /** * Auto upload browsercache files to CDN */ - if ( $new_config->get_boolean( 'cdn.enabled' ) && $new_config->get_string( 'cdn.engine' ) == 'ftp' ) { + if ( $new_config->get_boolean( 'cdn.enabled' ) && 'ftp' === $new_config->get_string( 'cdn.engine' ) ) { self::cdn_delete_browsercache( $current_config ); self::cdn_upload_browsercache( $current_config ); } @@ -692,11 +692,11 @@ public static function config_save( $current_config, $new_config ) { */ public static function cdn_upload_minify() { $w3_plugin_cdn = Dispatcher::component( 'Cdn_Plugin' ); - $common = Dispatcher::component( 'Cdn_Core' ); + $common = Dispatcher::component( 'Cdn_Core' ); $files = $w3_plugin_cdn->get_files_minify(); - $upload = array(); + $upload = array(); $results = array(); foreach ( $files as $file ) { @@ -722,20 +722,20 @@ public static function cdn_upload_browsercache( $config ) { Dispatcher::component( 'Cdn_Core_Admin' ); - $ce = Dispatcher::component( 'Cdn_Environment' ); + $ce = Dispatcher::component( 'Cdn_Environment' ); $rules = $ce->rules_generate_for_ftp( $config ); if ( $config->get_boolean( 'browsercache.enabled' ) ) { - $be = Dispatcher::component( 'BrowserCache_Environment' ); + $be = Dispatcher::component( 'BrowserCache_Environment' ); $rules .= $be->rules_cache_generate_for_ftp( $config ); } $cdn_path = Util_Rule::get_cdn_rules_path(); $tmp_path = W3TC_CACHE_TMP_DIR . '/' . $cdn_path; - if ( @file_put_contents( $tmp_path, $rules ) ) { + if ( @file_put_contents( $tmp_path, $rules ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents $results = array(); - $upload = array( $common->build_file_descriptor( $tmp_path, $cdn_path ) ); + $upload = array( $common->build_file_descriptor( $tmp_path, $cdn_path ) ); $common->upload( $upload, true, $results ); } @@ -767,8 +767,8 @@ public static function cdn_delete_browsercache() { * @return string */ public static function get_cookie_domain() { - $site_url = get_option( 'siteurl' ); - $parse_url = @parse_url( $site_url ); + $site_url = get_option( 'siteurl' ); + $parse_url = @wp_parse_url( $site_url ); if ( $parse_url && ! empty( $parse_url['host'] ) ) { return $parse_url['host']; diff --git a/Util_AttachToActions.php b/Util_AttachToActions.php index 4e5352310..0e8a95a07 100644 --- a/Util_AttachToActions.php +++ b/Util_AttachToActions.php @@ -8,8 +8,9 @@ namespace W3TC; /** - * Attaches to wp actions related to content change, which should fire - * flushes of html content + * Class Util_AttachToActions + * + * Attaches to wp actions related to content change, which should fire flushes of html content */ class Util_AttachToActions { /** diff --git a/Util_Bus.php b/Util_Bus.php index 0aa2dfabe..2eb08fa57 100644 --- a/Util_Bus.php +++ b/Util_Bus.php @@ -1,27 +1,46 @@ 1000 ) { $content = substr( $content, 0, 1000 ); } @@ -37,38 +54,44 @@ static private function _is_html_prepare( $content ) { } $content = ltrim( $content, "\x00\x09\x0A\x0D\x20\xBB\xBF\xEF" ); + return $content; } /** * If content can handle HTML comments, can disable printout per request using filter 'w3tc_can_print_comment' * - * @param unknown $buffer + * @param unknown $buffer Buffer. + * * @return bool */ - static public function can_print_comment( $buffer ) { - if ( function_exists( 'apply_filters' ) ) - return apply_filters( 'w3tc_can_print_comment', Util_Content::is_html_xml( $buffer ) && !defined( 'DOING_AJAX' ) ); - return Util_Content::is_html_xml( $buffer ) && !defined( 'DOING_AJAX' ); + public static function can_print_comment( $buffer ) { + if ( function_exists( 'apply_filters' ) ) { + return apply_filters( 'w3tc_can_print_comment', self::is_html_xml( $buffer ) && ! defined( 'DOING_AJAX' ) ); + } + + return self::is_html_xml( $buffer ) && ! defined( 'DOING_AJAX' ); } /** * Returns GMT date * - * @param integer $time + * @param integer $time Time. + * * @return string */ - static public function http_date( $time ) { + public static function http_date( $time ) { return gmdate( 'D, d M Y H:i:s \G\M\T', $time ); } /** * Escapes HTML comment * - * @param string $comment + * @param string $comment Comment. + * * @return mixed */ - static public function escape_comment( $comment ) { + public static function escape_comment( $comment ) { while ( strstr( $comment, '--' ) !== false ) { $comment = str_replace( '--', '- -', $comment ); } @@ -76,18 +99,16 @@ static public function escape_comment( $comment ) { return $comment; } - - /** * Deprecated. Added to prevent loading-order errors during upgrades * from older w3tc plugin versions - **/ - static public function is_database_error() { + * + * @return bool + */ + public static function is_database_error() { return false; } - - /** * Converts * 127.0.0.1:1234 to ( '123.0.0.1', 1234 ) @@ -96,15 +117,21 @@ static public function is_database_error() { * * Doesnt fit to that class perfectly but selected due to common usage * of loaded classes + * + * @param string $server Server. + * @param int $port_default Port default. + * + * @return array */ - static public function endpoint_to_host_port( $server, $port_default = 0 ) { + public static function endpoint_to_host_port( $server, $port_default = 0 ) { $p = strrpos( $server, ':' ); - if ( substr( $server, 0, 5 ) == 'unix:' || $p === false ) { + if ( 'unix:' === substr( $server, 0, 5 ) || false === $p ) { return array( trim( $server ), $port_default ); } return array( trim( substr( $server, 0, $p ) ), - (int)substr( $server, $p + 1 ) ); + (int) substr( $server, $p + 1 ), + ); } } diff --git a/Util_Debug.php b/Util_Debug.php index a9790d4d8..526933351 100644 --- a/Util_Debug.php +++ b/Util_Debug.php @@ -1,16 +1,27 @@ ', '..' ); + $filename = self::log_filename( $module ); - - static public function log( $module, $message ) { - $message = strtr( $message, '<>', '..' ); - $filename = Util_Debug::log_filename( $module ); - - return @file_put_contents( $filename, '[' . date( 'r' ) . '] ' . - $message . "\n", FILE_APPEND ); + return @file_put_contents( $filename, '[' . gmdate( 'r' ) . '] ' . $message . "\n", FILE_APPEND ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents } - - /** * Log cache purge event + * + * @param unknown $module Module. + * @param string $message Message. + * @param array $parameters Parameters. + * @param array $explicit_postfix Explicit postfix. + * + * @return bool */ - static public function log_purge( $module, $message, $parameters = null, - $explicit_postfix = null ) { - $backtrace = debug_backtrace( 0 ); + public static function log_purge( $module, $message, $parameters = null, $explicit_postfix = null ) { + $backtrace = debug_backtrace( 0 ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace + $backtrace_count = count( $backtrace ); $backtrace_lines = array(); - $pos = 0; - for ( $n = 2; $n < count( $backtrace ); $n++ ) { - if ( !Util_Debug::log_purge_should_print_item( $backtrace, $n ) ) { + $pos = 0; + + for ( $n = 2; $n < $backtrace_count; $n++ ) { + if ( ! self::log_purge_should_print_item( $backtrace, $n ) ) { continue; } - $i = $backtrace[$n]; + $i = $backtrace[ $n ]; $filename = isset( $i['file'] ) ? $i['file'] : ''; $filename = str_replace( ABSPATH, '', $filename ); $line = isset( $i['line'] ) ? $i['line'] : ''; - $method = ( !empty( $i['class'] ) ? $i['class'] . '--' : '' ) . - $i['function']; - $args = ' ' . Util_Debug::encode_params( $i['args'] ); - $backtrace_lines[] = "\t#" . ( $pos ) . ' ' . - $filename . '(' . $line . '): ' . $method . $args; + $method = ( ! empty( $i['class'] ) ? $i['class'] . '--' : '' ) . $i['function']; + $args = ' ' . self::encode_params( $i['args'] ); + $backtrace_lines[] = "\t#" . ( $pos ) . ' ' . $filename . '(' . $line . '): ' . $method . $args; $pos++; } $message = $message; - if ( !is_null( $parameters ) ) { - $message .= Util_Debug::encode_params( $parameters ); + if ( ! is_null( $parameters ) ) { + $message .= self::encode_params( $parameters ); } - $user = function_exists( 'wp_get_current_user' ) ? wp_get_current_user() : null; + $user = function_exists( 'wp_get_current_user' ) ? wp_get_current_user() : null; $username = ( empty( $user ) ? 'anonymous' : $user->user_login ); $message .= "\n\tusername:$username"; @@ -105,36 +130,45 @@ static public function log_purge( $module, $message, $parameters = null, $message .= "\n" . implode( "\n", $backtrace_lines ); - return Util_Debug::log( $module . '-purge', $message ); + return self::log( $module . '-purge', $message ); } - - - static private function log_purge_should_print_item( $backtrace, $n ) { - if ( !empty( $backtrace[$n]['class']) && - $backtrace[$n]['class'] == 'W3TC\\CacheFlush_Locally' ) { + /** + * Log purge should print item + * + * @param array $backtrace Backtrace. + * @param string $n Key. + * + * @return bool + */ + private static function log_purge_should_print_item( $backtrace, $n ) { + if ( ! empty( $backtrace[ $n ]['class'] ) && 'W3TC\\CacheFlush_Locally' === $backtrace[ $n ]['class'] ) { return false; } - if ( !empty( $backtrace[$n]['class']) && - $backtrace[$n]['class'] == 'WP_Hook' && - !empty( $backtrace[$n + 1]['function'] ) ) { - $f = $backtrace[$n + 1]['function']; - if ( $f == 'do_action' || $f == 'apply_filters' ) { + + if ( ! empty( $backtrace[ $n ]['class'] ) && 'WP_Hook' === $backtrace[ $n ]['class'] && ! empty( $backtrace[ $n + 1 ]['function'] ) ) { + $f = $backtrace[ $n + 1 ]['function']; + if ( 'do_action' === $f || 'apply_filters' === $f ) { return false; } - return Util_Debug::log_purge_should_print_item( $backtrace, $n + 1 ); + return self::log_purge_should_print_item( $backtrace, $n + 1 ); } return true; } - - - static private function encode_params( $args ) { + /** + * Encode parameters + * + * @param array $args Arguments. + * + * @return string + */ + private static function encode_params( $args ) { $args_strings = array(); - if ( !is_array( $args ) ) { - $s = (string)$args; + if ( ! is_array( $args ) ) { + $s = (string) $args; if ( strlen( $s ) > 100 ) { $s = substr( $s, 0, 98 ) . '..'; @@ -143,8 +177,7 @@ static private function encode_params( $args ) { $args_strings[] = $s; } else { foreach ( $args as $arg ) { - $s = json_encode( $arg, - JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); + $s = json_encode( $arg, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); if ( strlen( $s ) > 100 ) { $s = substr( $s, 0, 98 ) . '..'; } @@ -158,8 +191,14 @@ static private function encode_params( $args ) { /** * Clean debug output with label headers. + * + * @param string $label Label. + * @param array $data Data. + * + * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log + * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r */ - static public function debug( $label, $data ) { + public static function debug( $label, $data ) { error_log( "\n\n" . '===============Debug ' . $label . ' Start===============' . "\n" . 'Microtime: ' . microtime( true ) . "\n" . diff --git a/Util_DebugPurgeLog_Reader.php b/Util_DebugPurgeLog_Reader.php index a5569862e..78e01c34f 100644 --- a/Util_DebugPurgeLog_Reader.php +++ b/Util_DebugPurgeLog_Reader.php @@ -1,53 +1,91 @@ _read( $module ); } - - + /** + * Read log + * + * @param string $module Module. + * + * @throws \Exception Exception. + * + * @return array + */ private function _read( $module ) { $log_filename = Util_Debug::log_filename( $module . '-purge' ); - if ( !file_exists( $log_filename) ) { + if ( ! file_exists( $log_filename ) ) { return array(); } $h = @fopen( $log_filename, 'rb' ); - if ( !$h ) { + if ( ! $h ) { throw new \Exception( 'Failed to open log file' . $log_filename ); } fseek( $h, 0, SEEK_END ); - $pos = ftell( $h ); + $pos = ftell( $h ); $unparsed_head = ''; $more_log_needed = true; while ( $pos >= 0 ) { $to_read = 26; - $pos -= $to_read; + $pos -= $to_read; + if ( $pos <= 0 ) { $to_read = $to_read + $pos; - $pos = 0; + $pos = 0; } + fseek( $h, $pos ); $s = fread( $h, $to_read ); @@ -56,6 +94,7 @@ private function _read( $module ) { if ( count( $this->lines ) > 100 ) { break; } + if ( $pos <= 0 ) { $this->push_line( $unparsed_head ); break; @@ -65,15 +104,20 @@ private function _read( $module ) { return $this->lines; } - - + /** + * Parse string + * + * @param string $s String. + * + * @return string + */ private function parse_string( $s ) { $first_unparsed = strlen( $s ); - $pos = $first_unparsed; + $pos = $first_unparsed; for ( ; $pos >= 0; $pos-- ) { $c = substr( $s, $pos, 1 ); - if ( $c == "\r" || $c == "\n" ) { + if ( "\r" === $c || "\n" === $c ) { $this->push_line( substr( $s, $pos + 1, $first_unparsed - $pos - 1 ) ); $first_unparsed = $pos; } @@ -82,29 +126,34 @@ private function parse_string( $s ) { return substr( $s, 0, $first_unparsed ); } - - + /** + * Push line + * + * @param string $line Line. + * + * @return string + */ private function push_line( $line ) { if ( empty( $line ) ) { return; } - if ( substr( $line, 0, 1) == "\t" ) { + if ( "\t" === substr( $line, 0, 1 ) ) { array_unshift( $this->current_item, $line ); return; } - // split secondary lines to urls and backtrace - $postfix = array(); + // split secondary lines to urls and backtrace. + $postfix = array(); $backtrace = array(); - $username = ''; + $username = ''; foreach ( $this->current_item as $item ) { $item = trim( $item ); if ( preg_match( '~^(#[^ ]+) ([^:]+): (.*)~', $item, $m ) ) { $backtrace[] = array( - 'number' => $m[1], + 'number' => $m[1], 'filename' => $m[2], - 'function' => $m[3] + 'function' => $m[3], ); } elseif ( preg_match( '~^username:(.*)~', $item, $m ) ) { $username = $m[1]; @@ -116,11 +165,11 @@ private function push_line( $line ) { $m = null; if ( preg_match( '~\\[([^\\]]+)\\] (.*)~', $line, $m ) ) { $this->lines[] = array( - 'date' => $m[1], - 'message' => $m[2], - 'username' => $username, - 'postfix' => $postfix, - 'backtrace' => $backtrace + 'date' => $m[1], + 'message' => $m[2], + 'username' => $username, + 'postfix' => $postfix, + 'backtrace' => $backtrace, ); } diff --git a/Util_Environment.php b/Util_Environment.php index 3ffd65290..e1b792de5 100644 --- a/Util_Environment.php +++ b/Util_Environment.php @@ -9,12 +9,15 @@ /** * Class: Util_Environment + * + * phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged */ class Util_Environment { /** * Is using ,aster config. * * @var bool + * * @static */ private static $is_using_master_config = null; @@ -28,6 +31,7 @@ class Util_Environment { * @param array $params Parameters. * @param bool $skip_empty Skip empty. * @param string $separator Separate. + * * @return string */ public static function url_format( $url = '', $params = array(), $skip_empty = false, $separator = '&' ) { @@ -50,7 +54,7 @@ public static function url_format( $url = '', $params = array(), $skip_empty = f $url .= $parse_url['host']; } - if ( ! empty( $parse_url['port'] ) && $parse_url['port'] != 80 ) { + if ( ! empty( $parse_url['port'] ) && 80 !== $parse_url['port'] ) { $url .= ':' . (int) $parse_url['port']; } } @@ -94,6 +98,7 @@ public static function url_format( $url = '', $params = array(), $skip_empty = f * @param array $params Parameters. * @param bool $skip_empty Skip empty. * @param string $separator Separator. + * * @return string */ public static function url_query( $params = array(), $skip_empty = false, $separator = '&' ) { @@ -134,6 +139,7 @@ public static function url_query( $params = array(), $skip_empty = false, $separ * * @param string $filename Filename. * @param bool $use_site_url Use siteurl. + * * @return string */ public static function filename_to_url( $filename, $use_site_url = false ) { @@ -144,10 +150,10 @@ public static function filename_to_url( $filename, $use_site_url = false ) { if ( substr( $filename, 0, strlen( WP_CONTENT_DIR ) ) === WP_CONTENT_DIR ) { // This is the default location of the wp-content/cache directory. $location = WP_CONTENT_DIR; - } else if ( substr( $filename, 0, strlen( W3TC_CACHE_DIR ) ) === W3TC_CACHE_DIR ) { + } elseif ( substr( $filename, 0, strlen( W3TC_CACHE_DIR ) ) === W3TC_CACHE_DIR ) { // This is needed in the event the cache directory is moved outside of wp-content and replace with a symbolic link. $location = substr( W3TC_CACHE_DIR, 0, -strlen( '/cache' ) ); - } else if ( substr( $filename, 0, strlen( W3TC_CONFIG_DIR ) ) === W3TC_CONFIG_DIR ) { + } elseif ( substr( $filename, 0, strlen( W3TC_CONFIG_DIR ) ) === W3TC_CONFIG_DIR ) { // This is needed in the event the cache directory is moved outside of wp-content and replace with a symbolic link. $location = substr( W3TC_CONFIG_DIR, 0, -strlen( '/w3tc-config' ) ); } else { @@ -156,7 +162,7 @@ public static function filename_to_url( $filename, $use_site_url = false ) { $uri_from_location = substr( $filename, strlen( $location ) ); - if ( DIRECTORY_SEPARATOR != '/' ) { + if ( '/' !== DIRECTORY_SEPARATOR ) { $uri_from_location = str_replace( DIRECTORY_SEPARATOR, '/', $uri_from_location ); } @@ -171,15 +177,17 @@ public static function filename_to_url( $filename, $use_site_url = false ) { * * @static * + * @param Config $config Config. + * * @return bool */ public static function is_dbcluster( $config = null ) { if ( is_null( $config ) ) { - // fallback for compatibility with older wp-content/db.php + // fallback for compatibility with older wp-content/db.php. $config = \W3TC\Dispatcher::config(); } - if ( !self::is_w3tc_pro( $config ) ) { + if ( ! self::is_w3tc_pro( $config ) ) { return false; } @@ -271,6 +279,7 @@ public static function w3tc_header() { * @static * * @param string $url URL. + * * @return bool */ public static function is_url( $url ) { @@ -305,6 +314,8 @@ public static function is_https() { /** * Moves user to preview-mode or opposite. * + * @param bool $is_enabled Is enabled. + * * @static */ public static function set_preview( $is_enabled ) { @@ -382,6 +393,7 @@ public static function is_iis() { * @static * * @param string $url URL. + * * @return string */ public static function url_to_host( $url ) { @@ -402,7 +414,7 @@ public static function url_to_host( $url ) { * @param string $url URL. */ public static function url_to_uri( $url ) { - $uri = @parse_url( $url, PHP_URL_PATH ); + $uri = @wp_parse_url( $url, PHP_URL_PATH ); // Convert FALSE and other return values to string. if ( empty( $uri ) ) { @@ -455,8 +467,9 @@ public static function wp_upload_dir() { $blog_id = self::blog_id(); - if ( ! isset( $values_by_blog[ $blog_id ] ) ) + if ( ! isset( $values_by_blog[ $blog_id ] ) ) { $values_by_blog[ $blog_id ] = wp_upload_dir(); + } return $values_by_blog[ $blog_id ]; } @@ -467,6 +480,7 @@ public static function wp_upload_dir() { * @static * * @param string $section Section. + * * @return string */ public static function cache_dir( $section ) { @@ -480,6 +494,7 @@ public static function cache_dir( $section ) { * * @param string $section Section. * @param int $blog_id Blog id. + * * @return string */ public static function cache_blog_dir( $section, $blog_id = null ) { @@ -514,7 +529,7 @@ public static function cache_blog_dir( $section, $blog_id = null ) { public static function cache_blog_minify_dir() { // when minify manual used with a shared config - shared // minify urls has to be used too, since CDN upload is possible - // only from network admin + // only from network admin. if ( self::is_wpmu() && self::is_using_master_config() && ! Dispatcher::config()->get_boolean( 'minify.auto' ) ) { $path = self::cache_blog_dir( 'minify', 0 ); } else { @@ -530,6 +545,7 @@ public static function cache_blog_minify_dir() { * @static * * @param string $url URL. + * * @return string */ public static function get_url_regexp( $url ) { @@ -547,6 +563,7 @@ public static function get_url_regexp( $url ) { * @static * * @param string $url URL. + * * @return string */ public static function url_to_maybe_https( $url ) { @@ -564,7 +581,6 @@ public static function url_to_maybe_https( $url ) { * * @return string */ - public static function home_domain_root_url() { $home_url = get_home_url(); $parse_url = @parse_url( $home_url ); // phpcs:ignore @@ -604,7 +620,7 @@ public static function home_domain_root_url_regexp() { */ public static function home_url_maybe_https() { $home_url = get_home_url(); - $ssl = self::url_to_maybe_https( $home_url ); + $ssl = self::url_to_maybe_https( $home_url ); return $ssl; } @@ -618,7 +634,7 @@ public static function home_url_maybe_https() { */ public static function home_url_regexp() { $home_url = get_home_url(); - $regexp = self::get_url_regexp( $home_url ); + $regexp = self::get_url_regexp( $home_url ); return $regexp; } @@ -652,13 +668,13 @@ public static function site_path() { if ( false !== $pos ) { $home_path = substr( $script_filename, 0, $pos ); $home_path = trailingslashit( $home_path ); - } else if ( defined( 'WP_CLI' ) ) { + } elseif ( defined( 'WP_CLI' ) ) { $pos = strripos( str_replace( '\\', '/', ABSPATH ), trailingslashit( $wp_path_rel_to_home ) ); - if ( $pos !== false ) { + if ( false !== $pos ) { $home_path = substr( ABSPATH, 0, $pos ); $home_path = trailingslashit( $home_path ); } @@ -698,7 +714,7 @@ public static function document_root() { $php_self = self::normalize_path( htmlspecialchars( stripslashes( $_SERVER['PHP_SELF'] ) ) // phpcs:ignore ); - if ( substr( $script_filename, -strlen( $php_self ) ) == $php_self ) { + if ( substr( $script_filename, -strlen( $php_self ) ) === $php_self ) { $document_root = substr( $script_filename, 0, -strlen( $php_self ) ); $document_root = realpath( $document_root ); return $document_root; @@ -814,7 +830,7 @@ public static function network_home_url_uri() { * a non-relative URI even though scheme is set to relative. */ if ( self::is_url( $uri ) ) { - $uri = parse_url( $uri, PHP_URL_PATH ); + $uri = wp_parse_url( $uri, PHP_URL_PATH ); } if ( empty( $uri ) ) { @@ -858,7 +874,7 @@ public static function host() { $pos = strpos( $host_port, ':' ); - if ( $pos === false ) { + if ( false === $pos ) { return $host_port; } @@ -893,6 +909,7 @@ public static function wp_config_path() { * @static * * @param string $path Path. + * * @return mixed */ public static function parse_path( $path ) { @@ -924,13 +941,14 @@ public static function parse_path( $path ) { * @static * * @param string $file File path. + * * @return string */ public static function normalize_file( $file ) { if ( self::is_url( $file ) ) { if ( strstr( $file, '?' ) === false ) { $home_url_regexp = '~' . self::home_url_regexp() . '~i'; - $file = preg_replace( $home_url_regexp, '', $file ); + $file = preg_replace( $home_url_regexp, '', $file ); } } @@ -950,14 +968,15 @@ public static function normalize_file( $file ) { * * @static * - * @param string $file + * @param string $file File. + * * @return string */ public static function normalize_file_minify( $file ) { if ( self::is_url( $file ) ) { if ( strstr( $file, '?' ) === false ) { $domain_url_regexp = '~' . self::home_domain_root_url_regexp() . '~i'; - $file = preg_replace( $domain_url_regexp, '', $file ); + $file = preg_replace( $domain_url_regexp, '', $file ); } } @@ -976,13 +995,14 @@ public static function normalize_file_minify( $file ) { * * @static * - * @param string $file File path. + * @param string $url URL. + * * @return string */ public static function url_to_docroot_filename( $url ) { $data = array( 'home_url' => get_home_url(), - 'url' => $url, + 'url' => $url, ); $data = apply_filters( 'w3tc_url_to_docroot_filename', $data ); @@ -1003,15 +1023,14 @@ public static function url_to_docroot_filename( $url ) { $path_relative_to_home = str_replace( $home_url, '', $normalized_url ); $home = set_url_scheme( get_option( 'home' ), 'http' ); $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' ); - $home_path = rtrim( Util_Environment::site_path(), '/' ); + $home_path = rtrim( self::site_path(), '/' ); // Adjust home_path if site is not is home. if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) { // $siteurl - $home/ $wp_path_rel_to_home = rtrim( str_ireplace( $home, '', $siteurl ), '/' ); - if ( substr( $home_path, -strlen( $wp_path_rel_to_home ) ) == - $wp_path_rel_to_home ) { + if ( substr( $home_path, -strlen( $wp_path_rel_to_home ) ) === $wp_path_rel_to_home ) { $home_path = substr( $home_path, 0, -strlen( $wp_path_rel_to_home ) ); } } @@ -1024,7 +1043,7 @@ public static function url_to_docroot_filename( $url ) { $docroot = self::document_root(); - if ( substr( $full_filename, 0, strlen( $docroot ) ) == $docroot ) { + if ( substr( $full_filename, 0, strlen( $docroot ) ) === $docroot ) { $docroot_filename = substr( $full_filename, strlen( $docroot ) ); } else { $docroot_filename = $path_relative_to_home; @@ -1046,10 +1065,11 @@ public static function url_to_docroot_filename( $url ) { * @static * * @param string $docroot_filename Document filename. - * @return strin + * + * @return string */ public static function docroot_to_full_filename( $docroot_filename ) { - return rtrim( Util_Environment::document_root(), DIRECTORY_SEPARATOR ) . + return rtrim( self::document_root(), DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR . $docroot_filename; } @@ -1057,6 +1077,10 @@ public static function docroot_to_full_filename( $docroot_filename ) { * Removes WP query string from URL. * * @static + * + * @param string $url URL. + * + * @return string */ public static function remove_query( $url ) { $url = preg_replace( '~(\?|&|&|&)+ver=[a-z0-9-_\.]+~i', '', $url ); @@ -1070,11 +1094,12 @@ public static function remove_query( $url ) { * @static * * @param string $url URL. + * * @return string */ public static function remove_query_all( $url ) { $pos = strpos( $url, '?' ); - if ( $pos === false ) { + if ( false === $pos ) { return $url; } @@ -1087,6 +1112,7 @@ public static function remove_query_all( $url ) { * @static * * @param string $path Path. + * * @return string */ public static function normalize_path( $path ) { @@ -1102,6 +1128,7 @@ public static function normalize_path( $path ) { * @static * * @param string $path Path. + * * @return string */ public static function realpath( $path ) { @@ -1110,11 +1137,11 @@ public static function realpath( $path ) { $absolutes = array(); foreach ( $parts as $part ) { - if ( '.' == $part ) { + if ( '.' === $part ) { continue; } - if ( '..' == $part ) { + if ( '..' === $part ) { array_pop( $absolutes ); } else { $absolutes[] = $part; @@ -1130,17 +1157,18 @@ public static function realpath( $path ) { * @static * * @param string $path Path. + * * @return string */ public static function path_remove_dots( $path ) { - $parts = explode( '/', $path ); + $parts = explode( '/', $path ); $absolutes = array(); foreach ( $parts as $part ) { - if ( '.' == $part ) { + if ( '.' === $part ) { continue; } - if ( '..' == $part ) { + if ( '..' === $part ) { array_pop( $absolutes ); } else { $absolutes[] = $part; @@ -1156,24 +1184,26 @@ public static function path_remove_dots( $path ) { * @static * * @param string $relative_url Relative URL. + * * @return string */ public static function url_relative_to_full( $relative_url ) { $relative_url = self::path_remove_dots( $relative_url ); if ( version_compare( PHP_VERSION, '5.4.7' ) < 0 ) { - if ( substr( $relative_url, 0, 2 ) === '//' ) { + if ( substr( $relative_url, 0, 2 ) === '//' ) { $relative_url = ( self::is_https() ? 'https' : 'http' ) . ':' . $relative_url; } } - $rel = parse_url( $relative_url ); - // it's full url already - if ( isset( $rel['scheme'] ) || isset( $rel['host'] ) ) + $rel = wp_parse_url( $relative_url ); + // it's full url already. + if ( isset( $rel['scheme'] ) || isset( $rel['host'] ) ) { return $relative_url; + } - if ( !isset( $rel['host'] ) ) { - $home_parsed = parse_url( get_home_url() ); + if ( ! isset( $rel['host'] ) ) { + $home_parsed = wp_parse_url( get_home_url() ); $rel['host'] = $home_parsed['host']; if ( isset( $home_parsed['port'] ) ) { $rel['port'] = $home_parsed['port']; @@ -1181,10 +1211,10 @@ public static function url_relative_to_full( $relative_url ) { } $scheme = isset( $rel['scheme'] ) ? $rel['scheme'] . '://' : '//'; - $host = isset( $rel['host'] ) ? $rel['host'] : ''; - $port = isset( $rel['port'] ) ? ':' . $rel['port'] : ''; - $path = isset( $rel['path'] ) ? $rel['path'] : ''; - $query = isset( $rel['query'] ) ? '?' . $rel['query'] : ''; + $host = isset( $rel['host'] ) ? $rel['host'] : ''; + $port = isset( $rel['port'] ) ? ':' . $rel['port'] : ''; + $path = isset( $rel['path'] ) ? $rel['path'] : ''; + $query = isset( $rel['query'] ) ? '?' . $rel['query'] : ''; return "$scheme$host$port$path$query"; } @@ -1195,6 +1225,8 @@ public static function url_relative_to_full( $relative_url ) { * * @param string $url URL. * @param array $params Parameters. + * + * @return void */ public static function redirect( $url = '', $params = array() ) { $url = self::url_format( $url, $params ); @@ -1214,6 +1246,8 @@ public static function redirect( $url = '', $params = array() ) { * @param string $url URL. * @param array $params Parameters. * @param bool $safe_redirect Safe redirect or not. + * + * @return void */ public static function safe_redirect_temp( $url = '', $params = array(), $safe_redirect = false ) { $url = self::url_format( $url, $params ); @@ -1253,6 +1287,7 @@ public static function safe_redirect_temp( $url = '', $params = array(), $safe_r * @static * * @param string $url URL. + * * @return string */ public static function wp_safe_redirect_fallback( $url ) { @@ -1314,6 +1349,7 @@ public static function instance_id() { * @static * * @param Config $config Config. + * * @return string */ public static function w3tc_edition( $config = null ) { @@ -1334,17 +1370,10 @@ public static function w3tc_edition( $config = null ) { * @static * * @param Config $config Config. + * * @return bool */ public static function is_w3tc_pro( $config = null ) { - if ( defined( 'W3TC_PRO' ) && W3TC_PRO ) { - return true; - } - - if ( defined( 'W3TC_ENTERPRISE' ) && W3TC_ENTERPRISE ) { - return true; - } - if ( is_object( $config ) ) { $plugin_type = $config->get_string( 'plugin.type' ); @@ -1374,6 +1403,7 @@ public static function is_w3tc_pro_dev() { * * @param string $string String. * @param string $delimiter Delimeter. + * * @return string */ public static function preg_quote( $string, $delimiter = '~' ) { @@ -1403,6 +1433,7 @@ public static function is_zlib_enabled() { * @static * * @param mixed $var Value. + * * @return mixed */ public static function stripslashes( $var ) { @@ -1423,6 +1454,7 @@ public static function stripslashes( $var ) { * @param object $post Post object. * @param string $module Which cache module to check against (pgcache, varnish, dbcache or objectcache). * @param Config $config Config. + * * @return bool */ public static function is_flushable_post( $post, $module, $config ) { @@ -1461,9 +1493,11 @@ public static function is_flushable_post( $post, $module, $config ) { * Checks if post belongs to a custom post type. * * @since 2.1.7 + * * @static * * @param object $post Post object. + * * @return bool */ public static function is_custom_post_type( $post ) { @@ -1488,32 +1522,33 @@ public static function is_custom_post_type( $post ) { * @static * * @param mixed $value Value. + * * @return bool */ public static function to_boolean( $value ) { if ( is_string( $value ) ) { switch ( strtolower( $value ) ) { - case '+': - case '1': - case 'y': - case 'on': - case 'yes': - case 'true': - case 'enabled': - return true; + case '+': + case '1': + case 'y': + case 'on': + case 'yes': + case 'true': + case 'enabled': + return true; - case '-': - case '0': - case 'n': - case 'no': - case 'off': - case 'false': - case 'disabled': - return false; + case '-': + case '0': + case 'n': + case 'no': + case 'off': + case 'false': + case 'disabled': + return false; } } - return (boolean) $value; + return (bool) $value; } /** @@ -1539,13 +1574,18 @@ public static function get_server_version() { * Checks if current request is REST REQUEST. * * @static + * + * @param string $url URL. + * + * @return string */ public static function is_rest_request( $url ) { - if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) + if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { return true; + } // in case when called before constant is set - // wp filters are not available in that case + // wp filters are not available in that case. return preg_match( '~' . W3TC_WP_JSON_URI . '~', $url ); } @@ -1553,6 +1593,8 @@ public static function is_rest_request( $url ) { * Reset microcache. * * @static + * + * @return void */ public static function reset_microcache() { global $w3_current_blog_id; @@ -1619,10 +1661,12 @@ public static function textarea_to_array( $value ) { * Returns true if any entries between the tewo arrays match string endings or in whole. * * @since 2.7.4 + * * @static * * @param array $array1 Array 1. * @param array $array2 Array 2. + * * @return bool */ public static function array_intersect_partial( array $array1, array $array2 ): bool { @@ -1677,7 +1721,7 @@ public static function array_intersect_partial( array $array1, array $array2 ): * * @return int */ - public static function get_cron_schedule_time(int $cron_time = 0): int { + public static function get_cron_schedule_time( int $cron_time = 0 ): int { // Get the current time in WordPress timezone. $current_time_wp = new \DateTime( 'now', wp_timezone() ); @@ -1686,12 +1730,12 @@ public static function get_cron_schedule_time(int $cron_time = 0): int { $minute = $cron_time % 60; // Create a DateTime for today at the specified hour and minute in the user's timezone. - $scheduled_time_user = new \DateTime( "today", wp_timezone() ); + $scheduled_time_user = new \DateTime( 'today', wp_timezone() ); $scheduled_time_user->setTime( $hour, $minute ); // Convert the user's scheduled time to UTC for WordPress. $scheduled_time_utc = clone $scheduled_time_user; - $scheduled_time_utc->setTimezone( new \DateTimeZone('UTC') ); + $scheduled_time_utc->setTimezone( new \DateTimeZone( 'UTC' ) ); // If the selected time has already passed today in UTC, schedule for tomorrow. if ( $scheduled_time_utc <= $current_time_wp ) { @@ -1713,6 +1757,7 @@ public static function get_cron_schedule_time(int $cron_time = 0): int { * returned. * * @since 2.8.0 + * * @link https://github.com/wp-cli/cron-command/blob/v2.3.1/src/Cron_Command.php#L14-L55 * * @return bool @@ -1755,6 +1800,7 @@ public static function is_wpcron_working(): bool { * request. * * @since 2.8.0 + * * @link https://github.com/wp-cli/cron-command/blob/v2.3.1/src/Cron_Command.php#L57-L91 * * @global $wp_version WordPress version string. diff --git a/Util_Environment_Exception.php b/Util_Environment_Exception.php index ea2581329..c2b6c525e 100644 --- a/Util_Environment_Exception.php +++ b/Util_Environment_Exception.php @@ -1,14 +1,41 @@ technical_message = $technical_message; } + /** + * Get technical message + * + * @return string + */ public function technical_message() { return $this->technical_message; } diff --git a/Util_Environment_Exceptions.php b/Util_Environment_Exceptions.php index ee1d8ebd4..d0095254c 100644 --- a/Util_Environment_Exceptions.php +++ b/Util_Environment_Exceptions.php @@ -1,31 +1,68 @@ exceptions = array(); } + /** + * Push + * + * @param object $ex Exception. + * + * @return void + */ public function push( $ex ) { if ( $ex instanceof Util_Environment_Exceptions ) { - foreach ( $ex->exceptions() as $ex2 ) + foreach ( $ex->exceptions() as $ex2 ) { $this->push( $ex2 ); + } } else { - if ( $this->credentials_form == null && + if ( + null === $this->credentials_form && $ex instanceof Util_WpFile_FilesystemOperationException && - $ex->credentials_form() != null ) + null !== $ex->credentials_form() + ) { $this->credentials_form = $ex->credentials_form(); + } + $this->exceptions[] = $ex; } } /** - * + * Get exceptions * * @return Exception[] */ @@ -33,10 +70,20 @@ public function exceptions() { return $this->exceptions; } + /** + * Get credentials form + * + * @return string + */ public function credentials_form() { return $this->credentials_form; } + /** + * Get combined message + * + * @return string + */ public function getCombinedMessage() { $s = ''; foreach ( $this->exceptions as $m ) { diff --git a/pub/js/setup-guide.js b/pub/js/setup-guide.js index c3c3d8b47..5a0ecb31b 100644 --- a/pub/js/setup-guide.js +++ b/pub/js/setup-guide.js @@ -73,8 +73,6 @@ jQuery(function() { if (window.w3tc_ga) { w3tc_enable_ga = true; - w3tc_ga( 'js', new Date() ); - w3tc_ga( 'config', W3TC_SetupGuide.ga_profile, { 'user_properties': { 'plugin': 'w3-total-cache', @@ -87,7 +85,8 @@ jQuery(function() { 'w3tc_install_version': W3TC_SetupGuide.install_version, 'w3tc_edition': W3TC_SetupGuide.w3tc_edition, 'w3tc_widgets': W3TC_SetupGuide.list_widgets, - 'page': W3TC_SetupGuide.page + 'page': W3TC_SetupGuide.page, + 'w3tc_install_date': W3TC_SetupGuide.w3tc_install_date, } }); }